I need to install a custom execution script to Azure VM through terraform. The challenge though is we can only have one (custom)extension. So I need to delete any existing extensions before I add a new one. To delete an extension, I should know the name of the extension. Below is the code to delete it (if I know the name) and this works fine. But this approach fails, if the custom extension does not exist. Question is, how do I query and find if the extension exists? One approach is to use “null_resource”. I’d like to keep that as my last choice. Wondering if there are any other ways to list them, especially the custom one's?
resource "azapi_resource_action" "delete_vm_custom_extension" {
provider = azapi
for_each = local.vm_extensions
type = Microsoft.Compute/virtualMachines/extensions@2023-03-01
resource_id = "/subscriptions/${data.azurerm_client_config.this.subscription_id}/resourceGroups/${var.data_factory.resource_group_name}/providers/Microsoft.Compute/virtualMachines/${each.value.vm}/extensions/${each.value.custom_extension}"
method = "DELETE"
response_export_values = ["*"]
}
It'd be nice if I can achieve the same with azapi methods
As there is no direct way to check the existing extensions before creating the new one on
Azure VM
with conditions such as wanting to delete any extensions found and install a new one if not found, all these conditions are not possible viaTerraform
without using a null resource.PowerShell script:
The
PowerShell
script will first list all extensions. If extensions are found, it will iterate through them, delete each extension one by one usingRemove-AzVMExtension
, and install a new extension on the Azure VM.script.ps1
Terraform code:
terraform apply
Portal result