管理前脚本和后脚本Manage pre-scripts and post-scripts

在执行更新部署之前(前任务)和之后(后任务),前脚本和后脚本是在 Azure 自动化帐户中运行的 Runbook。Pre-scripts and post-scripts are runbooks to run in your Azure Automation account before (pre-task) and after (post-task) an update deployment. 前脚本和后脚本在 Azure 上下文中运行,而不是在本地运行。Pre-scripts and post-scripts run in the Azure context, not locally. 前脚本在更新部署开始时运行。Pre-scripts run at the beginning of the update deployment. 后脚本在部署结束时以及在配置的任何重新启动之后运行。Post-scripts run at the end of the deployment and after any reboots that are configured.

前脚本和后脚本要求Pre-script and post-script requirements

要将某个 Runbook 用作前脚本或后脚本,必须将其导入到自动化帐户中并发布这个 RunbookFor a runbook to be used as a pre-script or post-script, you must import it into your Automation account and publish the runbook.

前脚本和后脚本参数Pre-script and post-script parameters

配置前脚本和后脚本时,可以像计划 Runbook 时一样传入参数。When you configure pre-scripts and post-scripts, you can pass in parameters just like scheduling a runbook. 参数是在创建更新部署时定义的。Parameters are defined at the time of update deployment creation. 前脚本和后脚本支持以下类型:Pre-scripts and post-scripts support the following types:

  • [char][char]
  • [byte][byte]
  • [int][int]
  • [long][long]
  • [decimal][decimal]
  • [single][single]
  • [double][double]
  • [DateTime][DateTime]
  • [string][string]

前脚本和后脚本 Runbook 参数不支持布尔、对象或数组类型。Pre-script and post-script runbook parameters don't support boolean, object, or array types. 这些值会导致 Runbook 失败。These values cause the runbooks to fail.

如果需要其他对象类型,可以在 runbook 中使用自己的逻辑将它强制转换为其他类型。If you need another object type, you can cast it to another type with your own logic in the runbook.

除了标准的 Runbook 参数以外,还提供了一个 SoftwareUpdateConfigurationRunContext 参数(类型为 JSON 字符串)。In addition to your standard runbook parameters, the SoftwareUpdateConfigurationRunContext parameter (type JSON string) is provided. 如果在前脚本或后脚本 Runbook 中定义该参数,更新部署会自动传入该参数。If you define the parameter in your pre-script or post-script runbook, it's automatically passed in by the update deployment. 该参数包含有关更新部署的信息(SoftwareUpdateconfigurations API 返回的信息的子集)。The parameter contains information about the update deployment, which is a subset of information returned by the SoftwareUpdateconfigurations API. 以下部分定义关联的属性。Sections below define the associated properties.

SoftwareUpdateConfigurationRunContext 属性SoftwareUpdateConfigurationRunContext properties

属性Property 说明Description
SoftwareUpdateConfigurationNameSoftwareUpdateConfigurationName 软件更新配置的名称。The name of the software update configuration.
SoftwareUpdateConfigurationRunIdSoftwareUpdateConfigurationRunId 运行的唯一 ID。The unique ID for the run.
SoftwareUpdateConfigurationSettingsSoftwareUpdateConfigurationSettings 与软件更新配置相关的属性集合。A collection of properties related to the software update configuration.
SoftwareUpdateConfigurationSettings.operatingSystemSoftwareUpdateConfigurationSettings.operatingSystem 面向更新部署的操作系统。The operating systems targeted for the update deployment.
SoftwareUpdateConfigurationSettings.durationSoftwareUpdateConfigurationSettings.duration 符合 ISO8601 的更新部署最长运行持续时间,格式为 PT[n]H[n]M[n]S,也称为“维护时段”。The maximum duration of the update deployment run as PT[n]H[n]M[n]S as per ISO8601; also called the maintenance window.
SoftwareUpdateConfigurationSettings.WindowsSoftwareUpdateConfigurationSettings.Windows 与 Windows 计算机相关的属性集合。A collection of properties related to Windows computers.
SoftwareUpdateConfigurationSettings.Windows.excludedKbNumbersSoftwareUpdateConfigurationSettings.Windows.excludedKbNumbers 从更新部署中排除的 KB 数列表。A list of KBs that are excluded from the update deployment.
SoftwareUpdateConfigurationSettings.Windows.includedUpdateClassificationsSoftwareUpdateConfigurationSettings.Windows.includedUpdateClassifications 为更新部署选择的更新分类。Update classifications selected for the update deployment.
SoftwareUpdateConfigurationSettings.Windows.rebootSettingSoftwareUpdateConfigurationSettings.Windows.rebootSetting 更新部署的重新启动设置。Reboot settings for the update deployment.
azureVirtualMachinesazureVirtualMachines 更新部署中 Azure VM 的 resourceIds 列表。A list of resourceIds for the Azure VMs in the update deployment.
nonAzureComputerNamesnonAzureComputerNames 更新部署中的非 Azure 计算机 FQDN 列表。A list of the non-Azure computers FQDNs in the update deployment.

下面是传入 SoftwareUpdateConfigurationRunContext 参数的 JSON 字符串示例:The following example is a JSON string passed in to the SoftwareUpdateConfigurationRunContext parameter:

"SoftwareUpdateConfigurationRunContext":{
      "SoftwareUpdateConfigurationName":"sampleConfiguration",
      "SoftwareUpdateConfigurationRunId":"00000000-0000-0000-0000-000000000000",
      "SoftwareUpdateConfigurationSettings":{
         "operatingSystem":"Windows",
         "duration":"PT2H0M",
         "windows":{
            "excludedKbNumbers":[
               "168934",
               "168973"
            ],
            "includedUpdateClassifications":"Critical",
            "rebootSetting":"IfRequired"
         },
         "azureVirtualMachines":[
            "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresources/providers/Microsoft.Compute/virtualMachines/vm-01",
            "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresources/providers/Microsoft.Compute/virtualMachines/vm-02",
            "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresources/providers/Microsoft.Compute/virtualMachines/vm-03"
         ],
         "nonAzureComputerNames":[
            "box1.contoso.com",
            "box2.contoso.com"
         ]
      }
   }

可以在以下位置找到包含所有属性的完整示例:按名称获取软件更新配置A full example with all properties can be found at: Get software update configuration by name.

备注

SoftwareUpdateConfigurationRunContext 对象可以包含计算机的重复项。The SoftwareUpdateConfigurationRunContext object can contain duplicate entries for machines. 这可能会导致在同一台计算机上多次运行前脚本和后脚本。This can cause pre-scripts and post-scripts to run multiple times on the same machine. 若要解决此行为,请使用 Sort-Object -Unique 仅选择唯一的 VM 名称。To work around this behavior, use Sort-Object -Unique to select only unique VM names.

在部署中使用脚本前脚本或后脚本Using a pre-script or post-script in a deployment

若要在更新部署中使用前脚本或后脚本,请先创建一个更新部署。To use a pre-script or post-script in an update deployment, start by creating an update deployment. 选择“前脚本 + 后脚本”。Select Pre-scripts + Post-Scripts. 此操作会打开“选择前脚本 + 后脚本”页面。This action opens the Select Pre-scripts + Post-scripts page.

选择脚本

选择要使用的脚本。Select the script you want to use. 在此示例中,我们将使用 UpdateManagement-TurnOnVms Runbook。In this example, we use the UpdateManagement-TurnOnVms runbook. 选择 Runbook 时,将打开“配置脚本”页。When you select the runbook, the Configure Script page opens. 选择“前脚本”,然后选择“确定” 。Select Pre-Script, and then select OK.

针对 UpdateManagement-TurnOffVms 脚本重复此过程。Repeat this process for the UpdateManagement-TurnOffVms script. 但是如果选择“脚本类型”,请选择“后脚本” 。But when you choose the Script type, select Post-Script.

“选定的项”部分现在将显示所选的脚本。The Selected items section now shows both your scripts selected. 一个是前脚本,另一个是后脚本:One is a pre-script and the other is a post-script:

选定的项

完成更新部署的配置。Finish configuring your update deployment.

更新部署完成后,可以转到“更新部署”查看结果。When your update deployment is complete, you can go to Update deployments to view the results. 可以看到,此处提供了前脚本和后脚本的状态:As you can see, the status is provided for the pre-script and post-script:

更新结果

选择更新部署运行后,你会看到前脚本和后脚本的其他详细信息。By selecting the update deployment run, you're shown additional details of pre-scripts and post-scripts. 此时会提供运行时的脚本源的链接。A link to the script source at the time of the run is provided.

部署运行

脚本中结果。es in your script.

停止部署Stopping a deployment

如果要基于前脚本停止部署,则必须引发异常。If you want to stop a deployment based on a pre-script, you must throw an exception. 否则,部署和后脚本仍将运行。If you don't, the deployment and post-script will still run. 下面的代码片段演示如何引发异常。The following code snippet shows how to throw an exception.

#In this case, we want to terminate the patch job if any run fails.
#This logic might not hold for all cases - you might want to allow success as long as at least 1 run succeeds
foreach($summary in $finalStatus)
{
    if ($summary.Type -eq "Error")
    {
        #We must throw in order to fail the patch deployment.
        throw $summary.Summary
    }
}

与计算机交互Interacting with machines

前脚本和后任务在自动化帐户中作为 Runbook 运行,而不是直接在部署中的计算机上运行。Pre-scripts and post-tasks run as runbooks in your Automation account and not directly on the machines in your deployment. 前任务和后任务还可在 Azure 上下文中运行,无法访问非 Azure 计算机。Pre-tasks and post-tasks also run in the Azure context and don't have access to non-Azure machines. 以下部分介绍如何直接与计算机交互,无论是 Azure VM 还是非 Azure 计算机。The following sections show how you can interact with the machines directly, whether they're Azure VMs or non-Azure machines.

与 Azure 计算机交互Interact with Azure machines

前任务和后任务作为 Runbook 运行,而不是在部署中的 Azure VM 上以本机的方式运行。Pre-tasks and post-tasks run as runbooks and don't natively run on your Azure VMs in your deployment. 若要与 Azure VM 进行交互,必须具有以下项:To interact with your Azure VMs, you must have the following items:

  • 一个运行方式帐户A Run As account
  • 要运行的 RunbookA runbook you want to run

若要与 Azure 计算机交互,应使用 Invoke-AzVMRunCommand cmdlet 与 Azure VM 进行交互。To interact with Azure machines, you should use the Invoke-AzVMRunCommand cmdlet to interact with your Azure VMs. 有关如何执行此操作的示例,请参阅 Runbook 示例更新管理 - 使用 Run 命令运行脚本For an example of how to do this, see the runbook example Update Management – run script with Run command.

与非 Azure 计算机交互Interact with non-Azure machines

前任务和后任务在 Azure 上下文中运行,无法访问非 Azure 计算机。Pre-tasks and post-tasks run in the Azure context and don't have access to non-Azure machines. 若要与非 Azure 计算机进行交互,必须具有以下项:To interact with the non-Azure machines, you must have the following items:

  • 一个运行方式帐户A Run As account
  • 在计算机上安装的混合 Runbook 辅助角色Hybrid Runbook Worker installed on the machine
  • 要在本地运行的 RunbookA runbook you want to run locally
  • 父 RunbookA parent runbook

若要与非 Azure 计算机交互,需在 Azure 上下文中运行一个父 Runbook。To interact with non-Azure machines, a parent runbook is run in the Azure context. 此 Runbook 使用 Start-AzureRmAutomationRunbook cmdlet 调用子 Runbook。This runbook calls a child runbook with the Start-AzureRmAutomationRunbook cmdlet. 必须指定 RunOn 参数,并提供运行脚本的混合 Runbook 辅助角色的名称。You must specify the RunOn parameter and provide the name of the Hybrid Runbook Worker for the script to run on. 请参阅 Runbook 示例更新管理 - 本地运行脚本See the runbook example Update Management – run script locally.

中止修补程序部署Aborting patch deployment

如果你的前脚本返回错误,建议中止部署。If your pre-script returns an error, you might want to abort your deployment. 若要执行此操作,必须在脚本中引发错误,以查找导致失败的任何逻辑。To do that, you must throw an error in your script for any logic that would constitute a failure.

if (<My custom error logic>)
{
    #Throw an error to fail the patch deployment.
    throw "There was an error, abort deployment"
}

示例Samples

可以在脚本中心库PowerShell 库中找到前脚本和后脚本的示例。Samples for pre-scripts and post-scripts can be found in the Script Center Gallery and the PowerShell Gallery.

也可按脚本名称搜索这些示例,如以下列表中所示:Or you can search for them by their script name, as shown in the following list:

  • 更新管理 - 启用 VMUpdate Management - Turn On VMs
  • 更新管理 - 禁用 VMUpdate Management - Turn Off VMs
  • 更新管理 - 本地运行脚本Update Management - Run Script Locally
  • 更新管理 - 前脚本/后脚本的模板Update Management - Template for Pre/Post Scripts
  • 更新管理 - 具有 Run 命令运行脚本Update Management - Run Script with Run Command

重要

导入 Runbook 后,必须先发布,然后才可以使用它们。After you import the runbooks, you must publish them before they can be used. 为此,请在自动化帐户中找到该 Runbook,选择“编辑”,然后选择“发布” 。To do that, find the runbook in your Automation account, select Edit, and then select Publish.

所有这些示例都基于以下示例中定义的基本模板。The samples are all based on the basic template that's defined in the following example. 使用此模板可以创建自己的 Runbook 来配合前脚本和后脚本。This template can be used to create your own runbook to use with pre-scripts and post-scripts. 此模板还包含了用于在 Azure 中进行身份验证以及处理 SoftwareUpdateConfigurationRunContext 参数的必需逻辑。The necessary logic for authenticating with Azure and handling the SoftwareUpdateConfigurationRunContext parameter is included.

<#
.SYNOPSIS
 Barebones script for Update Management Pre/Post

.DESCRIPTION
  This script is intended to be run as a part of Update Management pre/post-scripts.
  It requires a RunAs account.

.PARAMETER SoftwareUpdateConfigurationRunContext
  This is a system variable which is automatically passed in by Update Management during a deployment.
#>

param(
    [string]$SoftwareUpdateConfigurationRunContext
)
#region BoilerplateAuthentication
#This requires a RunAs account
$ServicePrincipalConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'

Add-AzureRmAccount `
    -EnvironmentName AzureChinaCloud `
    -ServicePrincipal `
    -TenantId $ServicePrincipalConnection.TenantId `
    -ApplicationId $ServicePrincipalConnection.ApplicationId `
    -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint

$AzureContext = Select-AzureRmSubscription -SubscriptionId $ServicePrincipalConnection.SubscriptionID
#endregion BoilerplateAuthentication

#If you wish to use the run context, it must be converted from JSON
$context = ConvertFrom-Json  $SoftwareUpdateConfigurationRunContext
#Access the properties of the SoftwareUpdateConfigurationRunContext
$vmIds = $context.SoftwareUpdateConfigurationSettings.AzureVirtualMachines | Sort-Object -Unique
$runId = $context.SoftwareUpdateConfigurationRunId

Write-Output $context

#Example: How to create and write to a variable using the pre-script:
<#
#Create variable named after this run so it can be retrieved
New-AzureRmAutomationVariable -ResourceGroupName $ResourceGroup –AutomationAccountName $AutomationAccount –Name $runId -Value "" –Encrypted $false
#Set value of variable
Set-AutomationVariable –Name $runId -Value $vmIds
#>

#Example: How to retrieve information from a variable set during the pre-script
<#
$variable = Get-AutomationVariable -Name $runId
#>

备注

对于非图形 PowerShell Runbook,Add-AzureRMAccountConnect-AzureRmAccount 的别名。For non-graphical PowerShell runbooks, Add-AzureRMAccount are aliases for Connect-AzureRmAccount.

后续步骤Next steps

请继续学习以下教程,了解如何管理 Windows 虚拟机的更新:Go on to the following tutorial to learn how to manage updates for your Windows virtual machines: