Posted on 2 Comments

Run powershell command on virtual machines scale set

Azure Virtual Machine Scale Sets let you create and manage a group of load balanced VMs. The number of VM instances can automatically increase or decrease in response to demand or a defined schedule. Scale sets are commonly used for critical infrastructure like Kubernetes and service fabric. In this guide we will examine how we can perform an action massively on all nodes of the vmss.

The below vmss is composed of windows virtual machines that belong to an azure resource.

When you need to update all the nodes of vmss with a specific action, for instance to install a powershell module, you will need to use the run-command.

az vmss run-command | Microsoft Learn

First you will need to get all instances ids as they are a parameter for the next commands.

az vmss list-instances -n $vmss_name -g $rg_name --query "[].id" --output tsv

The output should be similar with the below.

/subscriptions/ID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmssname/virtualMachines/0
/subscriptions/ID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmssname/virtualMachines/1
/subscriptions/ID/resourceGroups/rg/providers/Microsoft.Compute/virtualMachineScaleSets/vmssname/virtualMachines/2

Then you can execute a powershell script on the vmss nodes by specifying the node id of the previous command and the resource group name along with the vmss name.

az vmss run-command invoke  --command-id RunPowerShellScript -n $vmss_name -g $rg_name --scripts 'hostname' --instance-id 0

Youtube video: