Azure VMSS Custom Data refresh the existing VMs using terraform.
For this kind of requirement, you can use create_before_destroy along with lifecycle rules and a null resource using commands which can trigger whenever there is a change in custom data.
This setup works as same as AWS Auto Scaling and meets the requikrement.
Configuration:
resource "null_resource" "vmss_reimage_trigger" {
triggers = {
custom_data_hash = filemd5("custom_data.sh")
}
provisioner "local-exec" {
command = "echo 'Changes detected, will re-image VMSS'"
}
}
resource "azurerm_windows_virtual_machine_scale_set" "vmss" {
name = "vmss-demo"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
admin_username = "adminuser"
admin_password = "P@55w0rd1234!"
sku = "Standard_F2"
instances = 1
custom_data = base64encode(file("custom_data.sh"))
os_disk {
storage_account_type = "Standard_LRS"
caching = "ReadWrite"
}
source_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2019-Datacenter"
version = "latest"
}
upgrade_mode = "Automatic"
health_probe_id = azurerm_lb_probe.lb_probe.id
automatic_instance_repair {
enabled = true
grace_period = "PT10M"
}
network_interface {
name = "example"
primary = true
ip_configuration {
name = "internal"
primary = true
subnet_id = azurerm_subnet.internal.id
load_balancer_backend_address_pool_ids = [azurerm_lb_backend_address_pool.bap.id]
}
}
lifecycle {
create_before_destroy = true
}
depends_on = [null_resource.vmss_reimage_trigger]
}
Deployment:


refer:
azurerm_windows_virtual_machine_scale_set | Resources | hashicorp/azurerm | Terraform | Terraform Registry
The lifecycle Meta-Argument - Configuration Language | Terraform | HashiCorp Developer