- 1 year ago
Execute a custom script on Azure VM Deletion
Comment
1 / 1
To execute a custom script when an Azure virtual machine (VM) is being deleted, you can make use of Azure Automation and Azure Event Grid. Here's a high-level overview of the steps involved:
Create an Azure Automation account:
- Create an Azure Automation account in the Azure portal if you don't have one already.
- Set up the necessary resources and configuration within the Automation account.
Create an Azure Automation runbook:
- In the Automation account, create a runbook that contains the custom script you want to execute when a VM is being deleted.
- Write the script logic in the runbook using PowerShell, Python, or any other supported language.
Configure the Azure Event Grid subscription:
- In the Azure portal, navigate to the VM's resource group or subscription level.
- Set up an Event Grid subscription to capture the
Microsoft.Compute/virtualMachines/delete
event for VM deletions. - Configure the subscription to send the event to an Azure Automation webhook.
Configure the webhook and link it to the runbook:
- In the Automation account, create a webhook that can receive the event from Event Grid.
- Associate the webhook with the previously created runbook.
- Ensure the webhook is authorized to execute the runbook.
Test the solution:
- Perform a VM deletion to trigger the event.
- The event will be sent to Event Grid, which will forward it to the Azure Automation webhook.
- The webhook will execute the associated runbook, which will run your custom script.
By following these steps, you can configure Azure Automation and Event Grid to execute a custom script whenever an Azure VM deletion event occurs. The specific details and implementation may vary based on your requirements and the scripting language you choose.