Archived blog

These articles remain available as a resource, but some information may be outdated. To contact the owner, visit ba4bes.com.

Automate Azure update management scheduling with PowerShell

· Barbara Forbes

In every IT environment, you need to consider how to handle the updates to the servers. With Azure Update Management, you get tooling that can help you with a variety of systems: On-premises or in Azure, Windows or Linux. In this blog post, I want to focus on automating part of update management: Scheduling updates. Let’s see how we can Automate Azure update management scheduling with PowerShell.

What is Azure Update management?

For the basics on Azure Update management, I recommend this blog post by Thomas Mauer

What I want to emphasize, is how great Azure Update management can be for a hybrid environment. With this tool, you can start updates for all your Azure VMs as well as on-premises servers. While you are at it, you can start using Azure Monitor as well.

Read more about adding your on-premises servers to this solution here.

For this post, I want to focus on a specific part of Azure Update Management, which is Automatically creating update schedules for VMs through PowerShell

The problem

With the update schedules, you have the option to create reoccurring schedules so you always know when your VMs will be updated. But if you for one reason or another need to create the schedules manually every month, this can become quite a large task. Especially if you have a lot of servers with a lot of different needs.

PowerShell to the rescue! Luckily you are able to automate this process. But in my opinion, the cmdlets and process are not very intuitive.

The solution

So let’s walk through Scheduling an update through PowerShell. The complete script will be at the end of this post.

Create a schedule

First thing first, we need to create an automation schedule. This is the same schedule that you would use for a runbook. When you create an update schedule in the portal, this is automatically created for you in the background. In PowerShell, you need to create it yourself.

To do this, you need to create a DateTimeOffSet object that shows the date and time which you want to schedule the updates.
Create a variable with Get-Date, like this:

[datetimeoffset]$StartTime = (Get-Date -Date "01-08-2020 07:00")

Now with the Automation Account name and the resource group name, you can set the schedule like this:

[datetimeoffset]$StartTime = (Get-Date -Date "13-07-2020 08:00")
# Create the time based on the schedule date and schedule time
$ScheduleTime = Get-Date $StartTime.LocalDateTime -Format "yyyy-MM-dd"
# Create the parameters for setting the schedule
$ScheduleParameters = @{
    ResourceGroupName     = "ResourceGroupName"
    AutomationAccountName = "AutomationAccountName"
    name                  = $ScheduleTime
    StartTime             = $StartTime
    OneTime               = $True
}
# Create the schedule that will be used for the updates
$AutomationSchedule = New-AzAutomationSchedule @ScheduleParameters
Set-Schedule.ps1 hosted on GitHub

By assigning to the variable $AutomationSchedule, you can use it for the following step.

UpdateSchedule

Create the update deployment

Now let’s use the schedule we just created to set up the update deployment. There are a few ways to do this. The simplest way is to pass the VMs recourse IDs to the parameter $AzureVMResourceId. The problem with this is that is doesn’t scale very well and it is easy to forget newly created VMs to the schedule.

That’s why I prefer to use Log Analytics Queries. The tricky thing is that they have to be passed in a different way for non-Azure Computers and Azure VMs. The good thing is that you can use both options in one schedule.

Collect non-Azure computers

To collect the non-Azure computers, you first need to create a Computer Group in Log Analytics. In this query you would call on all the computers you want to update. Here you can find more information about creating that computer group.

Collecting the query for automation is a bit tricky. You need to create a custom type for it. You can do that with the following code. Replace LogAnalyticsWorkspace with the name of your workspace.

# Create object for query
$Query = [Microsoft.Azure.Commands.Automation.Model.UpdateManagement.NonAzureQueryProperties]::New()
$Query.FunctionAlias = "Example"
$Query.WorkspaceResourceId = (Get-AzResource -Name '4besloganalyticsworkspace').ResourceId
Create-Query.ps1 hosted on GitHub

Collect Azure Computers

To collect the Azure Computers, you need to create the query with a cmdlet.

To do that, you have to first set the scope for your query. This can be on subscription level or on resource group level. You can select more than one subscription or resource group.

After that, you can optionally add a location-scope or to update only VMs with specific tags. To add them all would look like this:

$QueryParameters = @{
    ResourceGroupName     = (Get-AzResource -Name "LogAnalyticsWorkspace").ResourceGroupName
    AutomationAccountName = "AutomationAccountName"
    Scope                 = "/subscriptions/$((Get-AzContext).Subscription)"
    Location              = "westeurope"
    Tag                   = @{"tagName" = "Example" }
}
$Query = New-AzAutomationUpdateManagementAzureQuery @QueryParameters 
new-AzureQuery.ps1 hosted on GitHub

Create the Update schedule

Now you can create the schedule. In this example, you would install all classifications. If you want to separate the classifications, you can remove some of them.


$UpdateParameters = @{
    ResourceGroupName            = "ResourceGroupName"
    AutomationAccountName        = "AutomationAccountName"
    Schedule                     = $AutomationSchedule
    Windows                      = $true
    Duration                     = New-TimeSpan -Hours 2
    RebootSetting                = "Always"
    NonAzureQuery                = $nonAzQuery
    AzureQuery                   = $AzQuery
    IncludedUpdateClassification = @(
        "Unclassified"
        "Critical"
        "Security"
        "UpdateRollup"
        "FeaturePack"
        "ServicePack"
        "Definition"
        "Tools"
        "Updates"
    )
}
New-AzAutomationSoftwareUpdateConfiguration @UpdateParameters
New-updateschedule.ps1 hosted on GitHub

If you want to make use of pre- or post scripts, you can add them with the following properties:

    PreTaskRunbookName       = "runbookname"
    PreTaskRunbookParameter  = @{
        Parameter01 = "parameter"
    }
    PostTaskRunbookName      = "runbookname"
    PostTaskRunbookParameter = @{
        Parameter01 = "parameter"
    }
extra-parameters.ps1 hosted on GitHub

Conclusion

So this is how you create Automate Azure update management scheduling with PowerShell. To make it all a little easier, I have created a PowerShell Function that will do all these steps for you. The script could be combined with a CSV file. You can find it below.

Automate Azure update management scheduling with PowerShell

Function New-AzUpdateDeploymentSchedule {
    <#
.SYNOPSIS
Schedule Azure updates
.DESCRIPTION
This cmdlet combines the three cmdlets that are needed to create a update schedule.
New-AzAutomationSchedule
New-AzAutomationUpdateManagementAzureQuery
New-AzAutomationSoftwareUpdateConfiguration
Created for Azure Update Automation.
.PARAMETER StartTime
DateTimeOffset object to define the time updates should start
.PARAMETER ResourceGroupName
The resourcegroup where the automation account is placed
.PARAMETER AutomationAccountName
The name of the automation account
.PARAMETER LogAnalyticsWorkspace
The name of the log analytics workspace
.PARAMETER UpdateClassification
What classifications need to be updated.
Defaults to selects all classifications.
.PARAMETER AzureQuery
Switch to show if you need an AzureQuery
.PARAMETER Scope
Only if you need a Azure Query: The scope for the updates.
Defaults to the subscription of the subscription
.PARAMETER Location
Only if you need an Azure Query:
Only update the Azure VMs with this location
.PARAMETER Tags
Only if you need an Azure Query:
Only update Azure VMs with these tags
.PARAMETER NonAzureQueryName
When using Non-Azure VMs, pass the query name
.EXAMPLE
$Parameters = @{
    StartTime              = (Get-Date -Date "13-07-2020 08:00")
    ResourceGroupName      = "ResourceGroupName"
    AutomationAccountName  = "AutomationAccountName"
    LogAnalyticsWorkspace = "4besloganalyticsworkspace"
    AzureQuery             = $true
    Location               = "westeurope"
    Tags                   = @{"example" = "true" }
}
New-AzUpdateDeploymentSchedule @Parameters

.EXAMPLE
$Parameters = @{
    StartTime              = (Get-Date -Date "02-08-2020 08:00")
    ResourceGroupName      = "ResourceGroupName"
    AutomationAccountName  = "AutomationAccountName"
    LogAnalyticsWorkspace  = "4besloganalyticsworkspace"
    NonAzureSavedQueryName = "Example"
}
New-AzUpdateDeploymentSchedule @Parameters
.NOTES
Created by Barbara Forbes
@ba4bes
https://4bes.nl
#>
    [CmdletBinding(DefaultParameterSetName = "__AllParameterSets")]
    param(
        [Parameter(
            Mandatory = $true,
            ParameterSetName = "__AllParameterSets"
        )]
        [System.DateTimeOffset]$StartTime ,
        [Parameter(ParameterSetName = "__AllParameterSets")]
        [string]$ResourceGroupName ,
        [Parameter(ParameterSetName = "__AllParameterSets")]
        [string]$AutomationAccountName ,
        [Parameter(ParameterSetName = "__AllParameterSets")]
        [string]$LogAnalyticsWorkspace ,
        [Parameter(ParameterSetName = "__AllParameterSets")]
        [string[]]$UpdateClassification = @(
            "Unclassified"
            "Critical"
            "Security"
            "UpdateRollup"
            "FeaturePack"
            "ServicePack"
            "Definition"
            "Tools"
            "Updates"
        ),
        [Parameter(ParameterSetName = "__AllParameterSets")]
        [string]$NonAzureSavedQueryName,
        [Parameter(ParameterSetName = "__AzureSavedQuery")]
        [switch]$AzureQuery ,
        [Parameter(ParameterSetName = "__AzureSavedQuery")]
        [array]$Scope = @("/subscriptions/$((Get-AzContext).Subscription.Id)"),
        [Parameter(ParameterSetName = "__AzureSavedQuery")]
        [string]$Location ,
        [Parameter(ParameterSetName = "__AzureSavedQuery")]
        [hashtable]$Tags
    )

    # Create the time based on the schedule date and schedule time
    $ScheduleTime = Get-Date $StartTime.LocalDateTime -Format "yyyy-MM-dd"
    # Create the parameters for setting the schedule
    $ScheduleParameters = @{
        ResourceGroupName     = $ResourceGroupName
        AutomationAccountName = $AutomationAccountName
        name                  = $ScheduleTime
        StartTime             = $StartTime
        OneTime               = $True
    }
    # Create the schedule that will be used for the updates
    Try {
        $AutomationSchedule = New-AzAutomationSchedule @ScheduleParameters -ErrorAction Stop -Verbose
        Write-Verbose "Schedule has been created"
    }
    Catch {
        Throw "Could not create Automation Schedule: $_"
    }

    # create the parameters for the updateschedule
    $UpdateParameters = @{
        ResourceGroupName            = $ResourceGroupName
        AutomationAccountName        = $AutomationAccountName
        Schedule                     = $AutomationSchedule
        Windows                      = $true
        Duration                     = New-TimeSpan -Hours 2
        RebootSetting                = "Always"
        IncludedUpdateClassification = $UpdateClassification
    }
    if ($NonAzureSavedQueryName) {
        # Create object for query
        $nonAzQuery = [Microsoft.Azure.Commands.Automation.Model.UpdateManagement.NonAzureQueryProperties]::New()
        $nonAzQuery.FunctionAlias = $NonAzureSavedQueryName
        $nonAzQuery.WorkspaceResourceId = (Get-AzResource -Name $LogAnalyticsWorkspace).ResourceId

        $UpdateParameters.Add("NonAzureQuery", $nonAzQuery)
    }
    if ($AzureQuery) {
        $QueryParameters = @{
            ResourceGroupName     = (Get-AzResource -Name $LogAnalyticsWorkspace).ResourceGroupName
            AutomationAccountName = $AutomationAccountName
            Scope                 = $Scope
        }
        if ($Location) {
            $QueryParameters.Add("Location", $Location)
        }
        if ($Tags) {
            $QueryParameters.Add("Tag", $Tags)
        }
        Try {
            $AzQuery = New-AzAutomationUpdateManagementAzureQuery @QueryParameters -Verbose -ErrorAction Stop
            Write-Verbose "Query has been created"
        }
        Catch {
            Throw "Could not create query: $_"
        }
        $UpdateParameters.Add("AzureQuery", $AzQuery)
    }
    # Set the Automation Schedule
    Try {
        New-AzAutomationSoftwareUpdateConfiguration @UpdateParameters -Verbose -ErrorAction Stop
    }
    Catch {
        Throw "Could not create update schedule: $_"
    }
}
New-AzUpdateDeploymentSchedule.ps1 hosted on GitHub

Categories: Azure Automation, Powershell

Tags: Automation, Automation Account, Automation Accounts, Azure, Azure Automation, Powershell, VMs

Comments

Commenting is no longer available on this archived blog. The comments below are preserved from the original site.

  1. ICYMI: PowerShell Week of 17-July-2020 | PowerShell.org ·

    […] Automate Azure update management scheduling with PowerShell […]

  2. ICYMI: PowerShell Week of 17-July-2020 &#8211; 247 TECH ·

    […] Automate Azure update management scheduling with PowerShell […]