Use Azure Automation to Shut Down VMs Automatically

Posted by Graham Smith on December 4, 20146 Comments (click here to comment)

If you have an MSDN subscription (which gives you Azure credits) you will hopefully only forget to shut down your VMs after you have finished using them once. This happened to me and I was dismayed a few days later to find my Azure credits had been used up and I had to wait until the next billing cycle to carry on using Azure. There are a few ways to keep costs down (use a basic VM, size appropriately and don't install an image with a pre-loaded application such as SQL Server and instead install from an ISO from your MSDN subscription) but the most effective is to deallocate your VMs when you are finished using them.

As a safeguard after the episode where I ran down my credits I created a PowerShell script that I set up as a scheduled task to run daily at 1am on an always-on server that runs in my home datacentre under the stairs. Doable but not ideal, not least because of all the components that are installed by Azure PowerShell just to run one script. However, the recent launch of Azure Automation means this script can now be run from within Azure itself. Getting started with Azure Automation used to be a bit of a pain as there were quite a lot of steps to go through to set up authentication using certificates. The process is much simpler now as Azure Active Directory can be used. If you are just getting going with Azure Automation it's worth watching the Azure Friday Automation 101, 102 and 103 videos. When you are ready to start using Automation this post has the instructions for setting up the authentication. Once that is in place it's a case of navigating to the Automation pane in the Portal and creating an Automation Account. You then create a Runbook using the Quick Create feature and start editing it in draft mode. The following code is an example of how you might go about shutting down your VMs:

If you were to use the example code above you would need to have created a Runbook called Stop-AzureVMExceptDomainController and be using an Azure Active Directory user called Automation. (The code also ensures that a VM called ALMDC isn't shut down.) With the Runbook in place you can link it to a Schedule. You'll need to publish it first, although the typical workflow is to run in draft to test it until you are satisfied that it's working correctly. When you do finally publish you click the Schedule tab where you can link to a new or an existing schedule -- I have mine set to 1am.

Once your Runbook is in place you can of course run it manually as a convenient way to shut your VMs down when you have finished with them. No longer do you have to wait for PowerShell running locally to finish before you can turn your PC off. And if you do forget to shut your VMs off you can relax knowing that your schedule will kick in and do the job for you.

Cheers -- Graham