Search code examples
azureautomationcloud

Azure auto-run a script on a VM


I want to automate these 3 steps:

  1. Create a VM
  2. Run a bash script: To configure this newly created VM and run a script. I intend to setup the VM, download code from git and execute the process as required.
  3. Auto delete the VM on successful completion

Whether its a successful completion or unexpected exit will be monitored by a monitoring process which can be run as a daemon before the main process starts. In which case, we can trigger restart as a failsafe mechanism.

I'm using Azure cloud to run my process.

My questions:

  1. Is what I'm thinking a decent way to tackle this use case?
  2. Which tools in Azure cloud can help me with this?

Solution

  • Create a VM

    Several Options to choose from.

    Run Bash Script

    • Option 1: Azure Custom Script Extension Version 2 with Linux virtual machines. May not work bc there is a 90 min window for the script to run.
    • Option 2: Cloud Init. Requires a specific image to work.
    • Option 3: Cron Job. We don't have any Azure specific documentation.

    Deprovision

    As for deprovisioning, you can run the Azure CLI inside the VM after your task is done to delete the VM. The easiest way to do this is with a system-assigned managed identity.

    By default, when you delete a VM it only deletes the VM resource, not the networking and disk resources. You can change this default behavior when you create a VM, or update an existing VM, to delete specific resources along with the VM.

    The cleanest method is to create the VM and all components associated with that VM in a single Resource Group (RG). That way when your script is complete you can just delete the RG and be done.

    az group delete --name ExampleResourceGroup