If, like me, you use an MSDN account with a fixed amount of monthly Azure credit, you will know how easy it is to burn through it if you leave VMs on 24×7.
To cut down on my monthly spend I have been looking at ways to make more efficient use of the resources I provision into Azure, and I have found the best and simplest method is to simply shutdown my VMs at night and over the weekend. That is all well and good, providing you remember to ACTUALLY shut them down… I normally realise I have forgotten to do so first thing on Monday morning, at which point it is too late…!
Here is where Azure Automation is your friend. Using PowerShell, graphical runbooks and workflows it is easy to automate almost any task to be run on a schedule of your choosing. If it can be done in PowerShell it can, for the most part, be automated using Azure Automation.
Firstly, you will need a user account capable of performing the action you wish to automate. In my case I created a user in my Azure AD called email@example.com and granted it Virtual Machine Operator rights on the desired Resource Group using RBAC (Rights Based Access Control).
See here for more information about RBAC in Azure Resource Manager – https://azure.microsoft.com/en-us/documentation/articles/role-based-access-control-configure/#custom-roles-in-azure-rbac
This user account is then securely saved as an Automation Credential and called at runtime using the Get-AutomationPSCredential command.
See here for more information on storing passwords in the Azure Automation credential store – https://azure.microsoft.com/en-gb/documentation/articles/automation-credentials/#creating-a-new-credential-asset
Next, I created a new PowerShell workflow runbook which gets all the VMs within a given Resource Group, stores them in a variable and then pipes them to the Stop-AzureRMVM command in parallel.
The parameter values are supplied when you schedule the job to run and once set are used each time. You could hard code these in, but I prefer to use parameters wherever possible so my scripts are reusable in any environment with little or no alteration required.
This is a quick and easy method of shutting down every VM you have in a particular Resource Group, however you may want to add some additional logic if you have machines you don’t want to shutdown so they are not included in the “Foreach” loop.
The uses for this workflow are endless – you may have Dev/Test environments sitting in Azure that don’t need to be on overnight, production workloads that never get used at weekends or servers you just want to power cycle once a week, with automation anything is possible.
This script is available in the Azure Automation gallery, feel free to use it in your environment and save yourself some money!