BASH script to start or deallocate all VMs in Resource Group

For the first time here, I will use Azure CLI 2.0. It is written in Python and You can install it with pip install azure-cli.

First of all we need to login to our Azure account. If You are using MS Account there will be an interactive login procedure. You can also use Azure AD credentials or Service Principal for Your application/script (the same way as described here.

az login

Next, we need to set subscription we want to use (if there is more than one associated with Your account).

az account set --subscription subscription-id

Replace subscription-id with Your's subscription of choice ID.

And now let's deallocate all VMs in Resource Group of choice:

rg=rgname; az vm list -g $rg -o tsv | for i in $(awk -F

\t' '{print $8}'); do az vm deallocate -g $rg -n $i -o tsv 2>&1 | tee -a azure.log & done

Replace rgname with the name of the RG in which You want to deallocate all VMs.

And almost the same script to start all VMs in RG.

rg=rgname; az vm list -g $rg -o tsv | for i in $(awk -F

\t' '{print $8}'); do az vm start -g $rg -n $i -o tsv 2>&1 | tee -a azure.log & done

In both scripts first command is a RG name declaration. Then we are listing all VMs in this RG, picking only their names from TSV output of the command (with awk). For each VM in RG we are performing az vm deallocate or az vm start command. For logging purposes we are using TSV output format and redirect standard output and error to log file named azure.log (this part is optional). The very important part of the script is & before done. With this, our script will perform "for each VM" part in parallel and in "background". Without this it will iterate all VMs one by one.