Custom Script extension not Executing on VMSS

618 Views Asked by At

I am creating a VMSS using terraform to use for Azure Devops agent pool. I'm able to create VMSS successfully but when I try to run script to enroll it to agent pool, I'm hitting a wall. Nothing seems to work. Here is my TF code:

data "local_file" "template" {
  filename = "./agent_install_script.ps1"
}

data "template_file" "script" {
  template = data.local_file.template.content
  vars = {
    agent_name     = var.agent_name
    pool_name      = var.agent_pool_name
    token          = var.pat_token
    user_name      = var.vmss_admin_username
    logon_password = random_password.vm_password.result
  }
}

module "vmss_windows2022g2" {
  source              = "../modules/vmss_windows"
  environment         = var.environment
  resource_group_name = var.resource_group

  vmss_sku           = "Standard_DS2_v2"
  vmss_nic_subnet_id = module.vnet_mgt.subnet_windows_vmss_id
  vmss_nsg_id        = module.nsg.vmss_nsg_id

  vmss_computer_name = "win2022g2"

  vmss_admin_username = var.vmss_admin_username
  vmss_admin_password = random_password.vm_password.result

  windows_image_id = data.azurerm_image.windows_server2022_gen2.id

  vmss_storage_uri = data.azurerm_storage_account.vm_storage.primary_blob_endpoint

  overprovision = false

  #this will be stored at %SYSTEMDRIVE%\AzureData\CustomData.bin
  customData = data.template_file.script.rendered

  tags = local.env_tags_map
}

resource "azurerm_virtual_machine_scale_set_extension" "ext" {
  name                         = "InstallDevOpsAgent"
  virtual_machine_scale_set_id = module.vmss_windows2022g2.id
  publisher                    = "Microsoft.Azure.Extensions"
  type                         = "CustomScript"
  type_handler_version         = "2.0"

  settings = jsonencode({
    "commandToExecute" = "dir C:\\ > C:\\temp\\test.txt"
 
   #"cd C:\\AzureData; mv .\\CustomData.bin .\\install_agent.ps1; powershell -ExecutionPolicy Unrestricted -File .\\install_agent.ps1; del .\\install_agent.ps1;"
  })
  #protected_settings = var.protected_settings

  failure_suppression_enabled = false
  auto_upgrade_minor_version  = false
  automatic_upgrade_enabled   = false

  provision_after_extensions = []

  timeouts {
    create = "1h"
  }
}

As you can see, I'm copying the powershell script via custom_data and that is working fine with all the variables substituted properly. I have tried executing simple command dir C:\\ > C:\\temp\\test.txt to see if anything works, but am not getting any output.

TF version 1.12, azurerm provider version 3.32.0

1

There are 1 best solutions below

0
On

Azure DevOps should install an extension on the scale set (and in turn the VM's) which will automatically enrol the agent without the need for a script.

More details here: https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/scale-set-agents?view=azure-devops#lifecycle-of-a-scale-set-agent