Stopping multiple Azure VMs with a single line of code in Azure CLI

As I spend a lot of time with open source technologies in Azure, including Ubuntu, Kubernetes, and PostgreSQL to name a few, I have come to appreciate the Azure CLI. It’s simple, concise, shell-script friendly, integrates natively with Azure Pipelines, and works very well from Windows 10 or a variety of Linux hosts.

As an example, stopping and starting multiple VMs is possible with a single line of code, as shown in the examples below.

My first example will stop & deallocate all the VMs in the resource group named “k8s-pete”

az vm deallocate --ids $(az vm list -g "k8s-pete" --query "[].id" -o tsv)

In this option, I’ve removed the resource group (so targeting subscription-wide), but piped my query output to grep to search for VMs with “test” in their name. Grep is so powerful and even supports regular expressions, so I can be very precise in my targeting of subsets of VMs in my subscription.

az vm deallocate --ids $(az vm list --query "[].id" -o tsv | grep "test")

And this option simply stops and deallocates all the VMs in my Azure sub. (very handy for my MSDN sub)

az vm deallocate --ids $(az vm list --query "[].id" -o tsv) 

If you’re not using Azure CLI, it’s can be a great time saver in a variety of provisioning scenarios, and is a great way to get comfortable with shell scripting on the Linux platform. Take a few minutes to give it a try!

Leave a Reply