In azure, we have a total of 6 ways to create VMs either with VM or VMSS resources:
azurerm_linux_virtual_machine,
azurerm_windows_virtual_machine,
azurerm_virtual_machine,
azurerm_linux_virtual_machine_scale_set,
azurerm_virtual_machine_scale_set,
azurerm_windows_virtual_machine_scale_set.
We would want to mandate all VMs gets created using any of the above resources should always also have extensions on those machine using below resources:
azurerm_virtual_machine_extension & azurerm_virtual_machine_scale_set_extension
resource “azurerm_virtual_machine_extension” “example” {
name = “AzurePolicyforLinux”
virtual_machine_id = azurerm_virtual_machine.main.id
publisher = “Microsoft.GuestConfiguration”
type = “ConfigurationforLinux”
type_handler_version = “1.0”
settings = <<SETTINGS
{
“commandToExecute”: “hostname && uptime”
}
SETTINGS
}
resource “azurerm_virtual_machine_scale_set_extension” “example” {
name = “example”
virtual_machine_scale_set_id = azurerm_linux_virtual_machine_scale_set.main.id
publisher = “Microsoft.GuestConfiguration”
type = “ConfigurationforLinux”
type_handler_version = “1.0”
settings = jsonencode({
“commandToExecute” = “echo $HOSTNAME”
})
}
I can do it using finding the length of all the resources and doing a lot of if…else but wanted to look for a simple and better option to handle this use-case.