Runbook Automation for VMSS Windows Instances

Ovidiu Borlean
3 min readApr 2, 2022

The following how-to provide the solution for running remote scripts on Windows instance of VMSS. This script can be run in following ways:

- By Schedule, configure direct in Automation Account

- One Time Only — Executing from Automation Account

- Event initiated from different Azure resources

The running of this script is stateless and Job based, no information are saved between different running sessions. Also it does support only a temporary storage space that is used for creating this script. It is not saved between sessions.

The procedure for creating and managing Automation Account is as follows:

  1. Searching in Azure Portal for Automation Account

2. Creating Automation Account in desired Resource Group

3. For interacting with different subscription resources we need to create a RunAs Account. We select Run As Account in the left menu and follow the steps described. This will create a Service Principal that will be used for interactions with resources.

4. As we will use the PowesShell Runbook with ManagedIdentity, we need to provide the SPN used by this account the necessary RBAC roles on our resources. For shake of simplicity will provide the Contributor Role at the Subscription level. We select our Azure Portal Subscription, Access Control Panel

Adding Contributor Role for the Automation Account Identity.

5. We select our newly created Automation Account, open the Runbook Tab and select AzureAutomationTutorialwithIdentity

Select Edit and replace the code with the provided Code Snippet:

$vmssName = “akswinx” #VMSS Name

$vmssRG = “MC_aks_aks_westeurope” #VMSS Resource Group

try

{

“Logging in to Azure…”

Connect-AzAccount -Identity

}

catch {

Write-Error -Message $_.Exception

throw $_.Exception

}

# Creating a temporary file on Automation Account for PowerShell script

New-Item -Path ‘C:\Temp\script.ps1’ -ItemType File

# Here starts the content of the script used to configure VMSS

#Add-Content -Path C:\Temp\script.ps1 -Exclude help* -Value “Add-MpPreference -ExclusionPath ‘C:\Program Files\Docker\*’”

Add-Content C:\Temp\script.ps1 ‘Add-MpPreference -ExclusionPath “C:\Program Files\Docker”’

#Add-Content C:\Temp\script.ps1 ‘Add-MpPreference -ExclusionPath “C:\k\*”’

# Here is ending the content of the script

# The following part wil loop through Instances of the VMSS machines and will run the configuration on every instance

Get-Content -Path c:\Temp\script.ps1

$vmss = Get-AzVmssVM -ResourceGroupName $vmssRG -VMScaleSetName $vmssName

foreach ($item in $vmss.InstanceID) {

Write-Host “Applying Configuration Change for “ $item

$converted = Out-String -InputObject $vmss.InstanceID

$val = $item.InstanceID -as [Int]

Write-Output $val

Invoke-AzVmssVMRunCommand -ResourceGroupName $vmssRG -VMScaleSetName $vmssName -InstanceId $val -CommandId ‘RunPowerShellScript’ -ScriptPath (“C:\Temp\script.ps1”)

}

--

--