Search code examples
azureazure-powershellazure-automationazure-runbookazure-vm-role

If azure VM is idle for 30 minutes I need to shut it down


If an azure VM is idle for 30 minutes I need to shut it down. By idle I mean CPU percent is less than 30%. How can I achieve this?

I have tried with run books default functions but it has shutdown and start but not with idle time.


Solution

  • Try this by Powershell , you can run this command as a scheduled job based on your requirement :

    $vm = Get-AzureRmVM -Name <your vm name> -ResourceGroupName <your resource group name>
    $current = Get-Date
    
    #get cpuMetrics for each minute in past 30 mins 
    $cpuMetrics = Get-AzureRmMetric -ResourceId $vm.Id -TimeGrain 00:01:00 -StartTime $current.AddMinutes(-30) -EndTime $current -DetailedOutput -MetricNames "Percentage CPU"
    $CPUUsangeRange = ($cpuMetrics.Data | select Average).Average | measure -Maximum
    
    #get Maximum value of cpu usage percentage in past 30 mins, if the Maximum value less than 30% ,its idle and stop it .
    if($CPUUsangeRange.Maximum -lt 30){
       Stop-AzureRMvm -Name $vm.Name -ResourceGroupName $vm.ResourceGroupName -Force
    }
    

    Sometimes you cannot get last 2 or 3 mins cpu Metrics data as there will be some latency.