Suppose you have hundreds of Linux VMs in Azure across dozens of Azure subscriptions and you would like to run some commands programmatically on them.
Each VM in Azure gets what they call guest agent, that helps the underlying Virtual Machine communicate with the Azure Fabric. This is needed for operations like installing extensions on the VM, resetting root password on the VM from Azure Portal and so on.
There is anĀ Invoke Run Command API that you can invoke from the Azure Control Plane onto your VM that will run command within your Virtual Machine.
First, get list of all the Azure subscriptions that your user executing the Powershell have access to
$subs = Get-AzSubscription
Then produce the script that you would like to execute on the VM
echo '#!/bin/bash' >>.\msgtst.sh echo 'echo test: $1 $2 $3 $4 $5 $6' >>.\msgtst.sh $Script_paramz = [ordered]@{"par1" = "val1"; "par2" = "val2"; "par3" = "val3"; "par4" = "val4"; "par5" = "val5"; "par6" = "val6" }
Then get a list of all VMs which have been tagged as Dept = Billing
$VMs = Get-AzResource | Where-Object { $_.ResourceType -eq 'Microsoft.Compute/virtualMachines' } | Where-Object { $_.Tags -ne $null } | Where-Object { $_.Tags['Dept'] -eq "Billing" }
Then this will be the command that you’d need to execute for each individual VM
Invoke-AzVMRunCommand -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -ScriptPath ".\msgtst.sh" -CommandId RunShellScript -Parameter $Script_paramz -Verbose
Then everything together, looping thru list of subscriptions, looping through all the VMs with the tag, and then executing the command
Connect-AzAccount $subs = Get-AzSubscription foreach ($sub in $subs) { Select-AzSubscription -SubscriptionId $sub.Id echo '#!/bin/bash' >>.\msgtst.sh echo 'echo test: $1 $2 $3 $4 $5 $6' >>.\msgtst.sh $Script_paramz = [ordered]@{"par1" = "val1"; "par2" = "val2"; "par3" = "val3"; "par4" = "val4"; "par5" = "val5"; "par6" = "val6" } $VMs = Get-AzResource | Where-Object { $_.ResourceType -eq 'Microsoft.Compute/virtualMachines' } | Where-Object { $_.Tags -ne $null } | Where-Object { $_.Tags['Dept'] -eq "Billing" } foreach ($vm in $VMs) { Invoke-AzVMRunCommand -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -ScriptPath ".\msgtst.sh" -CommandId RunShellScript -Parameter $Script_paramz -Verbose } }
The same script can be modified to run on Windows VMs.