Automation Runbook To Shutdown Azure Resource Manager (ARM) VM

Here I will be sharing an automation runbook which you can parameterise to shut down VMs within a subscription based on a resource group using tags.   This article will not be a how to guide but a reference point for this script. 

You may add a parameter for the resource groups or you could even use a loops to run through all the resource groups by modifying this code.

If for example you have tags on your VMs such as Autoshutdown : YES then the runbook will pick these VMs to shut down.

Automation Runbook to Stop Azure VMs by Tag

<#

    .SYNOPSIS

        Stops all the Azure VMs in a specific Azure Resource Group if autoshutdown tag is set to Yes

 

    .DESCRIPTION

        This sample runbooks stops all of the virtual machines in the specified Azure Resource Group.

        For more information about how this runbook authenticates to your Azure subscription, see the

        Microsoft documentation here: http://aka.ms/fxu3mn.

 

    .PARAMETER ResourceGroupName

        Name of the Azure Resource Group containing the VMs to be stopped.

        Shutdown value – Can be set to YES by default or use a time zone for example CET and pass this in as a param and run at required time.  Useful when the group of Vms have different time zone requirements.

 

    .REQUIREMENTS

        This runbook will only return VMs deployed using the new Azure IaaS features available in the Azure Preview Portal and Azure Resource Manager templates. For more information, see

        http://azure.microsoft.com/en-us/documentation/videos/build-2015-introduction-and-what-s-new-in-azure-iaas/.

   

    .NOTES

        AUTHOR: Mitesh Chauhan 02/08/2016

        LASTEDIT: 17/1/2016

#>

 

workflow shutdown-dev-vms

{

       param(

             [Parameter(Mandatory=$true)]

        [String] $ResourceGroupName  = “RG NAME”,

 

       #The name of the Automation Credential Asset this runbook will use to authenticate to Azure.

        [Parameter(Mandatory=$true)]

        [String] $CredentialAssetName  = “Azure Automation Cred”,

 

        [Parameter(Mandatory=$true)]

        [String] $SubscriptionID  = “Sub ID”,

 

        [Parameter(Mandatory=$true)]

        [String] $Shutdownvalue  = “Yes”

         )

 

    #Get the credential with the above name from the Automation Asset store

    $Cred = Get-AutomationPSCredential -Name $CredentialAssetName

    if(!$Cred) {

        Throw “Could not find an Automation Credential Asset named ‘${CredentialAssetName}‘. Make sure you have created one in this Automation Account.”

                }

              

Login-AzureRmAccount -Credential $Cred

Select-AzureRmSubscription -Subscriptionid $SubscriptionID

 

# To get all VMs in a subscription use the following line.

# Also change stop line to Stop-AzureRmVM -ResourceGroupName $vm.ResourceGroupName

# $vmList = Find-AzureRmResource -TagName Autoshutdown -TagValue $Shutdownvalue | Where-Object {$_.ResourceType -eq “Microsoft.Compute/virtualMachines”} | Select Name, ResourceGroupName

 

# Gather all VMs with auto shutdown tag set to the tag value in the parameters

$vmList = Find-AzureRmResource -TagName Autoshutdown -TagValue $Shutdownvalue | Where-Object {$_.ResourceGroupName -eq $ResourceGroupName -and $_.ResourceType -eq “Microsoft.Compute/virtualMachines”} | Select Name, ResourceGroupName

 

foreach ($VM in $vmlist)

            {

                $PowerState = (Get-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $VM.Name -Status -ErrorAction $ErrorActionPreference -WarningAction $WarningPreference).Statuses.Code[1]

 

                if ($PowerState -eq ‘PowerState/deallocated’)

                   {

                    $VM.Name + ” is already shut down.”

                   }

                else

                  {

                    $VM.Name + ” is being shut down.”

                    $ShutdownState = (Stop-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $VM.Name -Force -ErrorAction $ErrorActionPreference -WarningAction $WarningPreference).IsSuccessStatusCode

                    start-sleep -Seconds 10                             

                              if ($ShutdownState -eq ‘True’)

                      {

                    $VM.Name + ” Has been shut down successfully.”

                       }

                    else

                       {

                    $VM.Name + ” Has failed to shut down. Shutdown Status  = “ + $ShutdownState

                       }

                  }

             }

Write-output “Script complete”

}

 

Thank You For Visiting.

About Mitesh Chauhan
Mitesh Chauhan, Azure Cloud Solutions Architect. This is my blog where I share articles and thoughts on IT Infrastructure and architecture. The topics I am most passionate about are Implementation and architecture of rock solid Cloud Infrastructure based around SQL Server and Windows Server mainly using Microsoft Azure. MCTS - Azure Architecture MCTS - Azure Implementation MCSE Server Infrastructure (Windows Server 2012) , MCITP SQL Server 2008, Togaf Certified, Prince 2 Practitioner.

One Response to Automation Runbook To Shutdown Azure Resource Manager (ARM) VM

  1. Great job Mitesh! I suggest checking out VMPower.io (https://vmpower.io/). There’s a calendar feature that makes automating shutdown, startup and resize of VMs pretty seamless to do in <15 minutes. With the GUI, it's very accessible to non-technical team members (who normally shy away from scripts) too.

    Also for the folks handling multiple cloud providers, you can manage all of your VMs across multiple cloud subscriptions (Azure, AWS, & GCE) in one unified dashboard.

    Cheers!
    Taylor

    P.S. Big fan of your "Five Tips to Help Save Money on Your Azure IaaS Spend" post: https://miteshc.wordpress.com/2016/11/30/five-tips-to-help-save-money-on-your-azure-iaas-spend/

Leave a comment