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,
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.'
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.
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
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,
Once we select the above signal, a new window is introduced where we add logic to our alert,
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,
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.
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.
Output: An e-mail is sent to the mentioned e-mail address in the action group in Step3b.
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.