How to: Schedule Azure VM Shutdown based on CPU, Disk, Network Usage
In my previous post, I talked about how you can schedule Azure VMs to shutdown based on times of the day or week with a 3rd party service called VMPower. However you may also want to shutdown your VMs based on cpu, disk or network utilization. This is useful for things such as machines that users regularly remote desktop into or VMs that run tasks which vary in the time they take (such as CI/Build servers).
My Desktop Linux Machine
I have an internal 'jumpbox' Linux development machine which I use to directly access things on an internal subnet within an Azure Virtual Network. I use VNC (similar to RDP for Windows) to connect to it. Here's the network utilization of the VM when someone is connected to this machine, vs when someone is not:
Just based on Network utilization alone, it is easy to tell when this VM is in use. It would be great if this VM can turn off after I stop using it - incase I forget to turn it off myself.
The Hard Way
You can do this using Azure automation by creating a Powershell script which reads from the Azure metrics API. At some point you would call the Virtual Machines API at the right time (and optionally send a notification) . This way requires a bit of Powershell scripting prowess and can be a bit time consuming setting up the policies which control how your VMs shutdown.
The Easy Way
You can also do the same thing very quickly with VMPower. It allows you to set Azure VMs to shutdown based on cpu, disk, and network utilization average or maximum values. It also handles sending your team notifications via email and Slack.
Step 1) Signup for an account at VMPower.io. It doesn’t require a credit card and they have a decent free tier as well as credit-card-free trials.
Step 2) Connect your Azure subscription to VMPower like I mention in my last blog post.
Step 3) Create a VM Group, again like I mention in my last blog post.
Step 5) Click Idle Settings where you can select when your VM should be considered Idle. You can enable or disable a variety of statistics based on network, cpu, or disk activity.
Step 6) Click Update
Now the service will monitor the virtual machines in this VM Group. Whenever any VM is detected idle by the settings you defined in Step 5 the VM will be shutdown after a specified number of hours.
The nice thing about this is that VMPower will send a handy email before a VM shuts down with a link to temporarily delay the VM from turning off.
After the VM is turned off another email notification is sent with a link to turn on the VM. These links can be shared with your team and can even be triggered from mobile devices.
Although using 3rd party services aren't ideal, this is a nice end-to-end solution compared to the work of developing and maintaining an automation script which monitors disk/cpu/network utilization.