DEV Community

Cover image for How To Shutdown Your Azure Virtual Machine Automatically When Idle for X minute: A Step-by-Step Guide
Rajesh Kumar Yadav
Rajesh Kumar Yadav

Posted on

How To Shutdown Your Azure Virtual Machine Automatically When Idle for X minute: A Step-by-Step Guide

Managing Azure Virtual Machines (VMs) efficiently is essential for both performance and cost control. One common challenge is dealing with idle VMs that continue to incur costs even when not in use. This blog post will guide you through automating the shutdown of Azure VMs after a specified period of idleness, specifically after 30 minutes.

Why Automate VM Shutdowns?

  • Cost Savings: Azure charges for compute resources while VMs are running. By shutting down idle VMs, you can significantly reduce costs.
  • Resource Optimization: Automatically turning off VMs helps free up resources for other tasks, ensuring that your Azure environment runs efficiently.
  • Simplified Management: Automation simplifies the management of VMs, reducing the manual effort required to monitor and shut down resources.

Step 1: Create an Azure Automation Account

To get started, you need to create an Azure Automation Account.

  1. Log in to the Azure Portal: Go to Azure Portal.
  2. Create an Automation Account:
    • Click on Create a resource.
    • Select Automation and then click on Automation Account.
    • Fill in the required fields:
      • Name: Enter a unique name for your Automation Account.
      • Subscription: Select the appropriate Azure subscription.
      • Resource Group: Choose or create a new resource group.
      • Location: Select the Azure region closest to you.
    • Click Create.

Step 2: Create a Runbook

Runbooks in Azure Automation allow you to write scripts that can perform tasks on your Azure resources.

  1. Navigate to Your Automation Account:
    • Click on the Automation Account you just created.
  2. Create a Runbook:

    • Under Process Automation, click on Runbooks.
    • Click + Create a runbook.
    • Fill in the details:
      • Name: StopIdleVM
      • Runbook type: PowerShell
      • Description: (Optional)
    • Click Create.
  3. Add PowerShell Script:

    • In the Runbook editor, paste the following PowerShell script:
   param (
       [string]$ResourceGroupName,
       [string]$VMName
   )

   # Get the VM status
   $vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName
   if ($vm.PowerState -eq "VM running") {
       # Stop the VM if it is running
       Stop-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -Force
       Write-Output "VM $VMName stopped."
   }
Enter fullscreen mode Exit fullscreen mode

Click Save and then Publish.

Step 3: Create a Schedule for the Runbook

To automate the shutdown process, you need to set up a schedule.

Create a Schedule:

  1. In the Runbook, click on Schedules.
  2. Click + Add a schedule.
  3. Choose Create a new schedule.
  4. Fill in the details:
    • Name: StopVMIdleSchedule
    • Start time: Set to your preferred start time.
    • Recurrence: Set to “Recurring”.
    • Frequency: Set it to “Hourly”.
  5. Click Create.

Link the Schedule to the Runbook:

After creating the schedule, link it to your runbook.

  1. Under Schedule, select StopVMIdleSchedule.
  2. Set parameters for ResourceGroupName and VMName (replace with your actual values).
  3. Click OK.

Step 4: Monitor VM Activity (Optional)

To ensure that your VM only shuts down when truly idle, you can modify the PowerShell script to check CPU usage.

Modify the PowerShell Script:

$cpuUsageThreshold = 5 # in percent
$metrics = Get-AzMetric -ResourceId $vm.Id -MetricName "Percentage CPU" -TimeGrain 00:05:00 -StartTime (Get-Date).AddMinutes(-30)

if ($metrics.Data -ne $null -and ($metrics.Data | Measure-Object -Property Average -Average).Average -lt $cpuUsageThreshold) {
    # Stop the VM if it's idle
    Stop-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -Force
    Write-Output "VM $VMName stopped due to inactivity."
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Costs Associated with Azure Automation

Azure Automation can incur costs based on usage:

  • Automation Account: The account itself is free to create and manage.
  • Runbook Execution: Azure provides a free tier of 500 job minutes per month. Beyond this, the cost is approximately $0.002 per job minute.
  • Azure Resources: Remember that any Azure resources you automate (like VMs) will continue to incur their standard usage charges, even when stopped.

Conclusion

Automating the shutdown of Azure VMs when they are idle can lead to significant cost savings and efficient resource management. By setting up an Azure Automation Account, creating a Runbook, and establishing a schedule, you can ensure that your Azure environment operates optimally.

Implementing these steps not only simplifies management but also helps keep your cloud costs in check. Regular monitoring and adjustments can further enhance your automation strategy, ensuring that resources are only utilized when truly needed.

Call to Action

If you found this guide helpful, feel free to share it with your peers. Have questions or want to share your experience? Drop a comment below!

Top comments (0)