Setting Up Automated Azure IaaS VM Shutdown
The Tallan Integration Practice heavily utilizes Azure Infrastructure as a Service (IaaS) virtual machines for quickly setting up isolated environments for prototypes and BizTalk development environments. However, with so many virtual machines it is often difficult to remember to shut them off when not needed. With Azure‘s Automation features, we can setup a scheduled job to shut down non mission critical VM’s, saving on hosting costs.
This is achieved by using an Azure Automation Runbook, which will execute the powershell script to shutdown a service and VM.
First the script itself:
# Specify Azure Subscription Name $subName = 'YOUR_SUB_NAME' $cred = Get-AutomationPSCredential –Name 'NAME_OF_CREDENTIAL' Add-AzureAccount -Credential $cred Write-Output "Selecting Subscription" Select-AzureSubscription -SubscriptionName $subName Write-Output "Stopping VMs" # Shutdown VMs Stop-AzureVM -ServiceName 'SERVICE_NAME' -Name 'VM_NAME' -Force
‘YOUR_SUB_NAME’ is the name of your subscription, SERVICE_NAME should be replaced by the name of the cloud service which hosts the VM, and the VM name is not surprisingly the name of the virtual machine to be shut down. The last placeholder in the above script is the ‘NAME_OF_CREDENTIAL’ which corresponds to an Azure Automation credential which will be created alongside the creation of the Automation runbook. Save the powershell script as a text file.
Creation of the Automation and Runbook in the classic Azure Portal is as follows:
Click on New – App Services – Automation – Runbook – Quick Create
I will specify ‘DemoAccount’ as the name of the automation that i want to create
Next we will select the ‘DemoAccount’ Automation that we have just created
We then want to Import the powershell script file that we have created above, I have named it ‘RunbookDemo’
This creates a new Runbook and imports the powershell script.
We will next have to create the credential to be used within the powershell script.
I specified a name of ‘DemoCredential’. This will be the value that should replace ‘NAME_OF_CREDENTIAL’ in the powershell script above.
In the last screen, I have provided the email address and password which I use to login to the Azure Portal, however you can create a unique AD account which has access to the Azure Portal which can be used for automation purposes.
You should now be able to Test the runbook, and finally Publish. The runbook must be Published before a schedule can be assigned.
Now we can create a schedule, which I have created to run daily at 01:00.
That’s it! Now the VM should shutdown at 1 AM every day.