Search code examples
azureazure-resource-managerazure-marketplace

Delete VM is custom script fails in azure resource manager templat


I am using an Azure Resource Manager template to deploy a VM in Azure. I have a custom script that runs once the VM is up. The script runs, even when the script fails the VM stays up. Is there a way to tear down the VM if the custom script fails?

  "properties": {
    "publisher": "Microsoft.Azure.Extensions",
    "type": "CustomScript",
    "typeHandlerVersion": "2.0",
    "autoUpgradeMinorVersion": true,
    "settings": {
      "fileUris": [
        "[uri(parameters('_artifactsLocation'), concat('scripts/copyfilefromazure.sh', parameters('_artifactsLocationSasToken')))]"
      ]
    },
    "protectedSettings": {
      "commandToExecute": "[concat('bash ', variables('scriptFileName'), ' ', variables('scriptArgs'))]"
    }

Solution

  • For your requirements, you need to learn about the sequence of the template deployment progress.

    When you create the VM with extension. It will create the VM first and then execute the VM extension in the VM. SO no matter the VM extension executes in failure or success. The VM is already running. And I'm afraid there is no feature for you that if the custom extension fails, the template deletes all the resources itself. As I know, Azure Template cannot delete the resources.

    So I think an appropriate solution is that create a script to check if the VM extension executes successfully, if not, then delete the extension with the CLI command az vm extension delete (I assume you use the Azure CLI). Then install the VM extension again with the CLI command az vm extension set.