<img alt="" src="https://secure.leadforensics.com/150446.png " style="display:none;">
Go to top icon

How to shut down your Virtual Machine if it is idle for 'X' hours on the basis of CPU Utilization Percentage

Sourabh Majali Oct 05, 2020

Microsoft Azure Virtual Machine PowerShell Script Azure Automation

A Virtual Machine (VM) is an environment that replicates a physical machine, having its own allocation of processing unit, storage, and networking interface. VMs can co-exist with the physical machine it is installed on and allows remote access to data and interfaces. In the new normal, VMs are a great way to provide access to the central repository from virtual locations and help a business stay functioning.

However, like any other process, running VMs come with specific cost requirements, and idle VMs can add up to the company's overall budget. For heavy-duty projects or those requiring lots of remote collaboration and sharing of tools, we need virtual machines with massive CPUs and memory, which are quite expensive! Creating a workflow to shut down idle VMs a great step to ensure you get maximum benefit to managing cost and processing efficiently.

Read more to know how you can create an automated shutdown of VM if it idle for 'X' hours below 'Y' average CPU percentage. Although the idle time for a VM is dependent on the requirement and company standards, it should ideally be around 1 – 2 hours of idle time.

Let us explore a step-by-step method to achieve this:

Prerequisites,

-Virtual Machine
-Azure Automation Account

The process is divided into 3 steps,

  1. Create a Runbook with PowerShell script to Shut down a VM.
  2. Create a Webhook.
  3. Create an alert using Metric (CPU Percentage) less than X percent for Y time.

Step 1. Create a Runbook using PowerShell Script

Automation Account ->Runbook ->Create using PowerShell

Use the following PowerShell to create a Runbook to auto shutdown a VM,

#--------------------Start of Script -----------------------------------------------#

$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
 -ServicePrincipal `
 -TenantId $servicePrincipalConnection.TenantId `
 -ApplicationId $servicePrincipalConnection.ApplicationId `
 -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
} }
# to run this we need to confirm AzureRm.Profile and AzureRM.Insight is installed.
$vm = Get-AzureRmVM -Name myVM -ResourceGroupName myResourceGroup1
try{
Stop-AzureRMvm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force
Write-Host "Shutdown Successful"
}
catch
{
Write-Host "Error"
}
#------End of Script-------#

After adding the script, click 'Save' and 'Publish.'

Virtual Machine Auto Shutdown

Step 2. Create a Webhook

Automation Account -> Select your Runbook -> Webhook ->Add,

Webhooks allow us to extract more from Azure Alerts. We can specify an HTTP or HTTPS endpoints as a webhook while creating or updating an alert on the Azure Portal. Once the URL is hit, the respective Runbook is triggered, henceforth running the PowerShell script we created in Step1.

Add Name and save the URL of the Webhook in a safe place that we will use in Step 3.

VM- Create new webhook

Make sure you have copied the URL of Webhook.

Step 3. Create an Alert with conditions

All Resources -> “YourVMname” -> Alerts -> New Alert Rule,

Creating an Alert Rule proactively notifies you of desired conditional data in your collected monitoring data. We can create our own action group & trigger alerts based on data that is collected. Further, it is divided into 3 parts as follows

  1. Condition
  2. Action Group
  3. Alert Rule Details

a. Condition (Select Condition)

While creating an Alert, we need to provide condition based on Metric Signal type & "Percentage CPU" Signal name, refer the following image,

VM - Configure signal logic

Once we select the above signal, a new window is introduced where we add logic to our alert,

VM - Alert Logic

The above example shows the operator as 'Less Than,' aggregation type as 'Average' & Threshold, e.g., is 10 here our case. Further, Granularity (Period) is set to 1 hour, and 'Frequency' is 15 Minutes.

The alert will be triggered according to the above setting only if the average CPU percentage is less than 10 % for 1 hours duration is matched.

b. Action Group -> Create Action Group

Action Groups within Azure Alerts are typically a group of notifications preferences and actions to be taken once the condition is matched of alerts and alert is triggered, which are used by both Azure Monitor and service alerts. Select the notification type to "E-mail/SMS/Push/Voice" & add E-mail address as Notification type as below snap,

VM - Create action group

Once we select Actions, type "Webhook" & Paste here Webhook URL we created in Step2. This will help us to trigger the Webhook URL and eventually run the PowerShell script.

VM - create action group

c. Alert Rule Details -> Add details & click Create

Adding relevant details to the Alert rule name and description will help us out in identifying specific alerts. We can keep severity from 0 to 5, where 0 being high and 5 being low.

Once the details are filled, we can click on "Create Alert Rule" this will created and enable the rule which will start monitoring our mentioned condition.

VM - alert rule details

Output: An e-mail is sent to the mentioned e-mail address in the action group in Step3b.

VM - alert

Following the above steps helps us create an alert that is triggered if the CPU percentage is less than X for Y time duration. The triggered alert will generate an e-mail & trigger a webhook URL, which will run the PowerShell script we created to shut down the VM.

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.