Restart VMs
To run this sample, install the latest version of the Azure CLI. To start, run az login
to create a connection with Azure.
Samples for the Azure CLI are written for the bash
shell. To run this sample in Windows PowerShell or Command Prompt, you may need to change
elements of the script.
If you don't have an Azure subscription, create an Azure free account before you begin.
This sample shows a couple of ways to get some VMs and restart them.
The first restarts all the VMs in the resource group.
az vm restart --ids $(az vm list --resource-group myResourceGroup --query "[].id" -o tsv)
The second gets the tagged VMs using az resource list
and filters to the resources that are VMs,
and restarts those VMs.
az vm restart --ids $(az resource list --tag "restart-tag" --query "[?type=='Microsoft.Compute/virtualMachines'].id" -o tsv)
This sample works in a Bash shell. For options on running Azure CLI scripts on Windows client, see Install Azure CLI on Windows.
Sample script
The sample has three scripts. The first one provisions the virtual machines. It uses the no-wait option so the command returns without waiting on each VM to be provisioned. The second waits for the VMs to be fully provisioned. The third script restarts all the VMs that were provisioned, and then just the tagged VMs.
Clean up deployment
After the script sample has been run, the following command can be used to remove the resource groups, VMs, and all related resources.
az group delete -n myResourceGroup --no-wait --yes
Script explanation
This script uses the following commands to create a resource group, virtual machine, availability set, load balancer, and all related resources. Each command in the table links to command specific documentation.
Command | Notes |
---|---|
az group create | Creates a resource group in which all resources are stored. |
az vm create | Creates the virtual machines. |
az vm list | Used with --query to ensure the VMs are provisioned before restarting them, and then to get the IDs of the VMs to restart them. |
az resource list | Used with --query to get the IDs of the VMs using the tag. |
az vm restart | Restarts the VMs. |
az group delete | Deletes a resource group including all nested resources. |
Next steps
For more information on the Azure CLI, see Azure CLI documentation.
Additional virtual machine CLI script samples can be found in the Azure Linux VM documentation.