Using Azure Runbooks to automate scale set operations with Powershell jobs

Azure Powershell runbooks are cool. I’ve been exploring using them as a way to avoid using a dedicated VM for running simple PowerShell Scripts in Azure. I have a group of instances that are running from a dedicated Scale Set that I need to reboot nightly. It’s pretty easy to get this going. You can import my PS1 runbook with the following cmdlet

Import-AzureRmAutomationRunbook -Path reboot_az_server.ps1 -ResourceGroup "ResourceGroup" -AutomationAccountName "AutomationAccount" -Type Powershell

If you don’t have the the AZ Powershell module – you can easily install it with this snippet:

if ($PSVersionTable.PSEdition -eq 'Desktop' -and (Get-Module -Name AzureRM -ListAvailable)) {
    Write-Warning -Message ('Az module not installed. Having both the AzureRM and ' +
      'Az modules installed at the same time is not supported.')
} else {
    Install-Module -Name Az -AllowClobber -Scope CurrentUser
}

If you don’t want to do that, Simply launch the Azure Cloud Shell and import the runbook with that. If you need to grab the script, you can use invoke-webrequest

Invoke-WebRequest https://gist.githubusercontent.com/nshores/0eba281bcfb8d2a4a8329a60129a7531/raw/9b8e65e510fd8df38face171ebc37b316d5b366a/reboot_az_server.ps1 -
OutFile reboot_az_server.ps1

You can successfully make sure it’s imported by using get-azautomationrunbook:

S /home/it> Get-AzAutomationRunbook -ResourceGroupName $rg -AutomationAccountName $automation_account | select Name,CreationTime

Name                           CreationTime
----                           ------------
reboot_rds_nightly             7/6/2020 8:42:46 PM +00:00

PS /home/it>

After it’s imported, run it with

start-azautomationrunbook -name reboot_az_server -ResourceGroupName -$rg -AutomationAccountName $automation_account

If the script has output, such as mine, you can view the output like so:

$rg = 'automation'
$automation_account = 'automation-account'

$azjob = Get-AzAutomationJob -AutomationAccountName $automation_account -ResourceGroupName $rg | select -First 1
$azjoboutput = (Get-AzAutomationJobOutput -ResourceGroupName $rg -Stream Output -Id $azjob.JobId -AutomationAccountName $automation_account | get-AzAutomationJobOutputRecord).value
$azjoboutput.value
PS /home/it> $azjoboutput.value
Connection count is 1

Here’s the complete script below. It will do the following –

  • Find a scale set (currentley it only supports one in an acount)
  • For each scale set, find all the running instances.
  • Restart that instance and write-output a notice about what was done.

Share this content:

Leave a Comment

Your email address will not be published. Required fields are marked *