Recently had a request to automate the shutdown (Stop) of VMs within and azure environment based on CPU usage. The scenario is there are high powered virtual machines that run workloads that can last anywhere from 3 – 14 hours, once these jobs are complete, the user returns and then shuts the virtual machine down at which point it gets deallocated. This can be quite costly especially if the jobs finish right before a weekend, thats at least 48 hours of a high spec VM running while not being used!

Using Azure Alerts on the VM and Web hooks in automation accounts, I was able to come up with a way to shut the virtual machines down and de-allocated when the CPU reached a certain threshold. 

This is how I achieved that:

Create an automation account if you don’t have one already; In the Automation account create a new runbook for shutting down virtual machines

 

I used the following runbook type – “Powershell”

Once the runbook is created, I used the following powershell code to actually do the dealloction and stop of the VM.

 

param(

  [Parameter(Mandatory)]$vmname,

  [Parameter(Mandatory)]$resourcegroup

)

$connectionName = "AzureRunAsConnection"

try

{

#Use the Azure Run As Connection defined above

$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName

"Logging in to Azure..."

Add-AzureRmAccount  -ServicePrincipal -TenantId $servicePrincipalConnection.TenantId -ApplicationId $servicePrincipalConnection.ApplicationId -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint

}

catch {

if (!$servicePrincipalConnection)

{

#Display any errors while logging in using Run As Account

$ErrorMessage = "Connection $connectionName not found."

throw $ErrorMessage

} else{

#Display any other errors

Write-Error -Message $_.Exception

throw $_.Exception

} }

# Required Modules - AzureRm.Profile and AzureRM.Insight. Define the Virtual machine being shutdown by this script.

$vm = Get-AzureRmVM -Name $vmname -ResourceGroupName $resourcegroup

try{

Stop-AzureRMvm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force

Write-Host "Shutdown of $($vm.Name) Successful"

}

catch

{

Write-Host "Error"

}

 

Click publish to save the runbook

 

Then click on Webhooks under the Resources section

 

Add a new webhook with the parameters of the VM Name and resource group of the VM

 

 

Once the web hook is created, go to the VM in the “VMNAME” parameter and click on the alerts option:

 

 

Add a new alert – Select the “Percentage CPU” metric and configure your thresholds, in this example, the machine will trigger an alert if the average CPU value for the past 5 minutes is less than 5%

Next, add a new action group and create an action of “Webhook”

 

Paste in the webhook URL from the webhook you created for the VM.

 

Once the action group is done, complete the alert config with a name and click ok to save the alert. Next time the alert triggers the VM will be stopped and deallocated.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>