Azure IaaS Patching

When on a customer site recently, one requirement the customer was looking to achieve was to incorporate their IaaS virtual machines into their monthly patching policy. Their Iaas VM’s were shutdown nightly and all day on a weekend by a runbook.

This can be done with a relatively simple PowerShell script split into two functions; Start-AzurePatching and Stop-AzurePatching. The logic of the Start-AzurePatching function is as follows:

  • Connect into Azure PowerShell and choose the subscription you want to work with.
  • First the script will aggregate the VM properties inside each resource group.
  • The runbook being used to shut down your VM’s is looking to interact with a Tag named “AutoShutdownSchedule”
  • If it finds any VM with the tag “AutoShutdownSchedule”  it will remove it, replacing it with one that will allow it to start on a Saturday.
  • The new tags will be set against the virtual machine
  • The VM’s will be started.

The logic of the Stop-AzurePatching is similar:

  • The script will again aggregate all the VM’s settings, specifically looking for VM’s with the “AutoShutdownSchedule” tag.
  • The tag set by Start-AzurePatching will be replaced with a tag that includes the original shutdown settings, meaning the VM’s will be shutdown on a saturday and sunday.
  • The new tags will then be applied to the VM’s.

There isn’t a need to then shut the machines down via this script, as the runbook upon its next cycle will identify these machines as being VM’s that should be offline, and shut them down for you.

<#
Azure Patching PowerShell script.
#>

Function Start-AzurePatching {

Login-AzureRmAccount
$subId = ( Get-AzureRmSubscription |
Out-GridView `
-Title “Select an Azure Subscription” -OutputMode Single
).SubscriptionId
Select-AzureRmSubscription -SubscriptionId $subId

foreach($AzureRmVm in (Get-AzureRmResourceGroup | Get-AzureRmVm))
{
if($AzureRmVm.Tags.Keys -like “*AutoShutdownSchedule*”)
{
$AzureRmVm.Tags.Remove(‘AutoShutdownSchedule’) | Out-Null
$AzureRmVm.Tags.Add(‘AutoShutdownSchedule’,’8PM -> 5AM, Sunday, December 25′) | Out-Null

Set-AzureRmResource -ResourceGroupName $AzureRmVm.ResourceGroupName -Name $AzureRMVm.Name -Tag $AzureRmVm.Tags -ResourceType ‘Microsoft.Compute/VirtualMachines’
}

}

Start-AzureRmVM -Name $AzureRmVm.Name -ResourceGroupName $AzureRmVm.ResourceGroupName
}

#Run this post patching, when you are ready for the servers to be turned off again.

function Stop-AzurePatching {

foreach($AzureRmVm in (Get-AzureRmResourceGroup | Get-AzureRmVm))
{
if($AzureRmVm.Tags.Keys -like “*AutoShutdownSchedule*”)
{
$AzureRmVm.Tags.Remove(‘AutoShutdownSchedule’) | Out-Null
$AzureRmVm.Tags.Add(‘AutoShutdownSchedule’,’8PM -> 5AM, Saturday, Sunday, December 25′) | Out-Null

Set-AzureRmResource -Confirm:$FALSE -ResourceGroupName $AzureRmVm.ResourceGroupName -Name $AzureRMVm.Name -Tag $AzureRmVm.Tags -ResourceType ‘Microsoft.Compute/VirtualMachines’
}
}

}

There is more on Azure Fundamentals here.