在 Azure 自动化中管理 RunbookManage runbooks in Azure Automation

可以通过以下方法将 Runbook 添加到 Azure 自动化:创建新的 Runbook 或从文件中导入现有 Runbook。You can add a runbook to Azure Automation by either creating a new one or importing an existing one from a file. 本文介绍如何管理从文件中导入的 Runbook。This article provides information for managing a runbook imported from a file.

创建 runbookCreate a runbook

使用 Azure 门户或 Windows PowerShell 在 Azure 自动化中创建新的 Runbook。Create a new runbook in Azure Automation using the Azure portal or Windows PowerShell. Runbook 创建后,就可使用下文中的信息编辑它:Once the runbook has been created, you can edit it using information in:

在 Azure 门户中创建 RunbookCreate a runbook in the Azure portal

  1. 在 Azure 门户中,打开自动化帐户。In the Azure portal, open your Automation account.
  2. 从中心内,在“流程自动化”下选择“Runbook”,打开 Runbook 的列表 。From the hub, select Runbooks under Process Automation to open the list of runbooks.
  3. 单击“创建 Runbook”。Click Create a runbook.
  4. 键入 Runbook 的名称并选择其类型Enter a name for the runbook and select its type. Runbook 名称必须以字母开头,可包含字母、数字、下划线和短划线。The runbook name must start with a letter and can contain letters, numbers, underscores, and dashes.
  5. 单击“创建”以创建 Runbook 并打开编辑器。Click Create to create the runbook and open the editor.

通过 PowerShell 创建 RunbookCreate a runbook with PowerShell

使用 New-AzAutomationRunbook cmdlet 创建空的 Runbook。Use the New-AzAutomationRunbook cmdlet to create an empty runbook. 使用 Type 参数指定为 New-AzAutomationRunbook 定义的其中一种 Runbook 类型。Use the Type parameter to specify one of the runbook types defined for New-AzAutomationRunbook.

以下示例演示了如何创建新的空 Runbook。The following example shows how to create a new empty runbook.

New-AzAutomationRunbook -AutomationAccountName MyAccount `
-Name NewRunbook -ResourceGroupName MyResourceGroup -Type PowerShell

导入 RunbookImport a runbook

可导入 PowerShell 或 PowerShell 工作流脚本 (.ps1)、图形 Runbook (.graphrunbook) 或 Python 2 脚本 (.py) 来创建自己的 Runbook 。You can import a PowerShell or PowerShell Workflow (.ps1) script, a graphical runbook (.graphrunbook), or a Python 2 script (.py) to make your own runbook. 必须指定在导入期间创建的 Runbook 类型,并考虑以下注意事项。You must specify the type of runbook that is created during import, taking into account the following considerations.

  • 可将不含工作流的 .ps1 文件导入 PowerShell RunbookPowerShell 工作流 RunbookYou can import a .ps1 file that doesn't contain a workflow into either a PowerShell runbook or a PowerShell Workflow runbook. 如果将其导入 PowerShell 工作流 Runbook,它将转换为工作流。If you import it into a PowerShell Workflow runbook, it is converted to a workflow. 这样的话,Runbook 会包含注释来描述所作的更改。In this case, comments are included in the runbook to describe the changes made.

  • 仅可将包含 PowerShell 工作流的 .ps1 文件导入 PowerShell 工作流 RunbookYou can import only a .ps1 file containing a PowerShell Workflow into a PowerShell Workflow runbook. 如果该文件包含多个 PowerShell 工作流,则导入将失败。If the file contains multiple PowerShell workflows, the import fails. 必须将每个工作流保存到各自的文件中,并分别导入每个工作流。You must save each workflow to its own file and import each separately.

  • 请勿将包含 PowerShell 工作流的 .ps1 文件导入 PowerShell Runbook,因为 PowerShell 脚本引擎无法识别它。Do not import a .ps1 file containing a PowerShell Workflow into a PowerShell runbook, as the PowerShell script engine can't recognize it.

  • 仅可将 .graphrunbook 文件导入新的图形 RunbookOnly import a .graphrunbook file into a new graphical runbook.

通过 Azure 门户导入 RunbookImport a runbook from the Azure portal

可通过以下过程将脚本文件导入 Azure 自动化。You can use the following procedure to import a script file into Azure Automation.

备注

只能通过此门户将 .ps1 文件导入 PowerShell 工作流 Runbook。You can only import a .ps1 file into a PowerShell Workflow runbook using the portal.

  1. 在 Azure 门户中,打开自动化帐户。In the Azure portal, open your Automation account.
  2. 在“流程自动化”下选择“Runbook”,以打开 Runbook 的列表。 Select Runbooks under Process Automation to open the list of runbooks.
  3. 单击“导入 Runbook”。Click Import a runbook.
  4. 单击“Runbook 文件”并选择要导入的文件。Click Runbook file and select the file to import.
  5. 如果启用了“名称”字段,则你可更改 Runbook 名称。If the Name field is enabled, you have the option of changing the runbook name. 该名称必须以字母开头,可包含字母、数字、下划线和短划线。The name must start with a letter and can contain letters, numbers, underscores, and dashes.
  6. 将自动选择 Runbook 类型,但可以在考虑适用的限制后更改该类型。The runbook type is automatically selected, but you can change the type after taking the applicable restrictions into account.
  7. 单击“创建”。Click Create. 新的 runbook 会出现在自动化帐户的 runbook 列表中。The new runbook appears in the list of runbooks for the Automation account.
  8. 必须先发布 Runbook,才能运行它。You must publish the runbook before you can run it.

备注

导入图形 Runbook 后,可将其转换为其他类型。After you import a graphical runbook, you can convert it to another type. 但是,无法将图形 Runbook 转换为文本 Runbook。However, you can't convert a graphical runbook to a textual runbook.

使用 Windows PowerShell 导入 RunbookImport a runbook with Windows PowerShell

使用 Import-AzAutomationRunbook cmdlet 将脚本文件作为草稿 Runbook 导入。Use the Import-AzAutomationRunbook cmdlet to import a script file as a draft runbook. 如果该 Runbook 已存在,则导入将失败,除非你将 Force 参数与 cmdlet 一起使用。If the runbook already exists, the import fails unless you use the Force parameter with the cmdlet.

以下示例演示了如何将脚本文件导入到 Runbook 中。The following example shows how to import a script file into a runbook.

$automationAccountName =  "AutomationAccount"
$runbookName = "Sample_TestRunbook"
$scriptPath = "C:\Runbooks\Sample_TestRunbook.ps1"
$RGName = "ResourceGroup"

Import-AzAutomationRunbook -Name $runbookName -Path $scriptPath `
-ResourceGroupName $RGName -AutomationAccountName $automationAccountName `
-Type PowerShellWorkflow

处理资源Handle resources

如果你的 Runbook 创建了一项资源脚本应检查看看在尝试创建该资源之前它是否已存在。If your runbook creates a resource, the script should check to see if the resource already exists before attempting to create it. 下面是一个基本示例。Here's a basic example.

$vmName = "WindowsVM1"
$resourceGroupName = "myResourceGroup"
$myCred = Get-AutomationPSCredential "MyCredential"
$vmExists = Get-AzResource -Name $vmName -ResourceGroupName $resourceGroupName

if(!$vmExists)
    {
    Write-Output "VM $vmName does not exist, creating"
    New-AzVM -Name $vmName -ResourceGroupName $resourceGroupName -Credential $myCred
    }
else
    {
    Write-Output "VM $vmName already exists, skipping"
    }

从活动日志中检索详细信息Retrieve details from Activity log

可从自动化帐户的活动日志中检索 Runbook 详细信息,例如启动 Runbook 的人员或帐户。You can retrieve runbook details, such as the person or account that started a runbook, from the Activity log for the Automation account. 以下 PowerShell 示例显示了运行指定 Runbook 的最后一名用户。The following PowerShell example provides the last user to run the specified runbook.

$SubID = "00000000-0000-0000-0000-000000000000"
$AutomationResourceGroupName = "MyResourceGroup"
$AutomationAccountName = "MyAutomationAccount"
$RunbookName = "MyRunbook"
$StartTime = (Get-Date).AddDays(-1)
$JobActivityLogs = Get-AzLog -ResourceGroupName $AutomationResourceGroupName -StartTime $StartTime `
                                | Where-Object {$_.Authorization.Action -eq "Microsoft.Automation/automationAccounts/jobs/write"}

$JobInfo = @{}
foreach ($log in $JobActivityLogs)
{
    # Get job resource
    $JobResource = Get-AzResource -ResourceId $log.ResourceId

    if ($JobInfo[$log.SubmissionTimestamp] -eq $null -and $JobResource.Properties.runbook.name -eq $RunbookName)
    {
        # Get runbook
        $Runbook = Get-AzAutomationJob -ResourceGroupName $AutomationResourceGroupName -AutomationAccountName $AutomationAccountName `
                                            -Id $JobResource.Properties.jobId | ? {$_.RunbookName -eq $RunbookName}

        # Add job information to hashtable
        $JobInfo.Add($log.SubmissionTimestamp, @($Runbook.RunbookName,$Log.Caller, $JobResource.Properties.jobId))
    }
}
$JobInfo.GetEnumerator() | sort key -Descending | Select-Object -First 1

跟踪进度Track progress

最佳做法是,使用可轻松重用和重启的逻辑将 Runbook 创作为本质上模块化的内容。It's a good practice to author your runbooks to be modular in nature, with logic that can be reused and restarted easily. 跟踪在 Runbook 中的进度可确保 Runbook 逻辑在出现问题时正确执行。Tracking progress in a runbook ensures that the runbook logic executes correctly if there are issues.

可使用外部源(例如存储帐户、数据库或共享文件)来跟踪 Runbook 的进度。You can track the progress of a runbook by using an external source, such as a storage account, a database, or shared files. 在 Runbook 中创建逻辑,从而先检查所执行的最后一个操作的状态。Create logic in your runbook to first check the state of the last action taken. 然后,根据检查结果,可跳过逻辑,或者逻辑在 Runbook 中继续特定任务。Then, based on the results of the check, the logic can either skip or continue specific tasks in the runbook.

预防并发作业Prevent concurrent jobs

如果一些 Runbook 同时跨多个作业运行,则它们可能会表现得很奇怪。Some runbooks behave strangely if they run across multiple jobs at the same time. 在这种情况下,重要的是让 Runbook 实现逻辑来确定是否已有正在运行的作业。In this case, it's important for a runbook to implement logic to determine if there is already a running job. 下面是一个基本示例。Here's a basic example.

# Authenticate to Azure
$connection = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzAccount -ServicePrincipal -Tenant $connection.TenantID `
-ApplicationId $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint -Environment AzureChinaCloud

$AzureContext = Get-AzSubscription -SubscriptionId $connection.SubscriptionID

# Check for already running or new runbooks
$runbookName = "<RunbookName>"
$rgName = "<ResourceGroupName>"
$aaName = "<AutomationAccountName>"
$jobs = Get-AzAutomationJob -ResourceGroupName $rgName -AutomationAccountName $aaName -RunbookName $runbookName -AzContext $AzureContext

# Check to see if it is already running
$runningCount = ($jobs | ? {$_.Status -eq "Running"}).count

If (($jobs.status -contains "Running" -And $runningCount -gt 1 ) -Or ($jobs.Status -eq "New")) {
    # Exit code
    Write-Output "Runbook is already running"
    Exit 1
} else {
    # Insert Your code here
}

处理依赖时间的脚本中的暂时性错误Handle transient errors in a time-dependent script

Runbook 必须可靠且能够处理错误,包括可能导致其重启或失败的暂时性错误。Your runbooks must be robust and capable of handling errors, including transient errors that can cause them to restart or fail. 如果 Runbook 失败,Azure 自动化将重试它。If a runbook fails, Azure Automation retries it.

如果你的 Runbook 通常在一定时间内运行,请让脚本实现逻辑来检查执行时间。If your runbook normally runs within a time constraint, have the script implement logic to check the execution time. 该项检查可确保仅在特定的时间内运行诸如启动、关闭或横向扩展之类的操作。This check ensures the running of operations such as startup, shutdown, or scale-out only during specific times.

备注

Azure 沙盒上的本地时间被设置为 UTC。The local time on the Azure sandbox process is set to UTC. Runbook 中的日期和时间计算需要考虑到这一点。Calculations for date and time in your runbooks must take this fact into consideration. 使用自定义脚本:To use a custom script:

  1. 创建一个自动化帐户并获取参与者角色Create an Automation account and obtain a Contributor role.
  2. 将帐户关联到 Azure 工作区.Link the account to the Azure workspace.
  3. 启用混合 Runbook 辅助角色更新管理或其他自动化功能。Enable Hybrid Runbook Worker, Update Management, or another Automation feature.
  4. 如果是在 Linux 计算机上,则需要很高的权限。If on a Linux machine, you need high permissions. 登录来关闭签名检查Log in to turn off signature checks.

测试 RunbookTest a runbook

测试 Runbook 时,将执行草稿版,并会完成其所执行的任何操作。When you test a runbook, the Draft version is executed and any actions that it performs are completed. 不会创建作业历史记录,但会在“测试输出”窗格中显示输出警告和错误No job history is created, but the output and warning and error streams are displayed in the Test output pane. 仅当 VerbosePreference 变量设置为 Continue 时,“输出”窗格中才会显示发送到详细流的消息。Messages to the verbose stream are displayed in the Output pane only if the VerbosePreference variable is set to Continue.

即使草稿版正在运行,该 Runbook 也仍会正常执行,并针对环境中的资源执行任何操作。Even though the draft version is being run, the runbook still executes normally and performs any actions against resources in the environment. 因此,只能在非生产资源中测试 Runbook。For this reason, you should only test runbooks on non-production resources.

测试各类型的 Runbook 的流程相同。The procedure to test each type of runbook is the same. Azure 门户中文本编辑器测试与图形编辑器测试之间没有区别。There's no difference in testing between the textual editor and the graphical editor in the Azure portal.

  1. 文本编辑器图形编辑器中打开 Runbook 的草稿版本。Open the Draft version of the runbook in either the textual editor or the graphical editor.
  2. 单击“测试”打开测试页面。Click Test to open the Test page.
  3. 如果 Runbook 具有参数,它们会在左窗格中列出,你可在这里提供要用于测试的值。If the runbook has parameters, they're listed in the left pane, where you can provide values to be used for the test.
  4. 若要对混合 Runbook 辅助角色运行测试,请将“运行设置”更改为“混合辅助角色”,并选择目标组的名称 。If you want to run the test on a Hybrid Runbook Worker, change Run Settings to Hybrid Worker and select the name of the target group. 否则,保留默认值 Azure,以在云中运行测试。Otherwise, keep the default Azure to run the test in the cloud.
  5. 单击“启动”,开始测试。Click Start to begin the test.
  6. 在测试期间,可使用“输出”窗格下面的按钮来停止或暂停 PowerShell 工作流图形 Runbook。You can use the buttons under the Output pane to stop or suspend a PowerShell Workflow or graphical runbook while it's being tested. 暂停 Runbook 时,该 Runbook 会完成它在被暂停之前正在进行的活动。When you suspend the runbook, it completes the current activity before being suspended. 暂停 Runbook 后,可以将它停止或重启。Once the runbook is suspended, you can stop it or restart it.
  7. 在“输出”窗格中检查来自 Runbook 的输出。Inspect the output from the runbook in the Output pane.

发布 RunbookPublish a runbook

创建或导入新的 Runbook 时,必须先将其发布,然后才能导入。When you create or import a new runbook, you must publish it before you can run it. Azure 自动化中的每个 Runbook 都有一个草稿版本和一个已发布版本。Each runbook in Azure Automation has a Draft version and a Published version. 只有已发布版才能用来运行,只有草稿版才能用来编辑。Only the Published version is available to be run, and only the Draft version can be edited. 已发布版不受对草稿版所做的任何更改的影响。The Published version is unaffected by any changes to the Draft version. 当应该提供草稿版本时,你要发布它,使用草稿版本覆盖当前的已发布版本。When the Draft version should be made available, you publish it, overwriting the current Published version with the Draft version.

在 Azure 门户中发布 RunbookPublish a runbook in the Azure portal

  1. 在 Azure 门户中打开 Runbook。Open the runbook in the Azure portal.
  2. 单击 “编辑”Click Edit.
  3. 单击“发布”,然后在对验证消息的响应中单击“是” 。Click Publish and then Yes in response to the verification message.

使用 PowerShell 运行 RunbookPublish a runbook using PowerShell

使用 Publish-AzAutomationRunbook cmdlet 发布 Runbook。Use the Publish-AzAutomationRunbook cmdlet to publish your runbook.

$automationAccountName =  "AutomationAccount"
$runbookName = "Sample_TestRunbook"
$RGName = "ResourceGroup"

Publish-AzAutomationRunbook -AutomationAccountName $automationAccountName `
-Name $runbookName -ResourceGroupName $RGName

在 Azure 门户中计划 RunbookSchedule a runbook in the Azure portal

当你的 Runbook 已发布后,可计划它进行操作:When your runbook has been published, you can schedule it for operation:

  1. 在 Azure 门户中打开 Runbook。Open the runbook in the Azure portal.
  2. 在“资源”下选择“计划” 。Select Schedules under Resources.
  3. 选择“添加计划”。Select Add a schedule.
  4. 在“计划 Runbook”窗格中,选择“将计划关联到 Runbook”。In the Schedule Runbook pane, select Link a schedule to your runbook.
  5. 在“计划”窗格中选择“创建新计划”。Choose Create a new schedule in the Schedule pane.
  6. 在“新建计划”窗格中输入名称、说明和其他参数。Enter a name, description, and other parameters in the New schedule pane.
  7. 创建计划后,将其突出显示并单击“确定”。Once the schedule is created, highlight it and click OK. 它现应与你的 Runbook 关联。It should now be linked to your runbook.
  8. 查看邮箱中的电子邮件,里面有 Runbook 的状态。Look for an email in your mailbox to notify you of the runbook status.

获取作业状态Obtain job statuses

在 Azure 门户中查看状态View statuses in the Azure portal

可通过作业查看在 Azure 自动化中处理的作业的详细信息。Details of job handling in Azure Automation are provided in Jobs. 准备好查看 Runbook 作业后,使用 Azure 门户并访问你的自动化帐户。When you are ready to see your runbook jobs, use Azure portal and access your Automation account. 你可在右侧的“作业统计信息”中看到所有 Runbook 作业的摘要。On the right, you can see a summary of all the runbook jobs in Job Statistics.

作业统计信息磁贴

该摘要显示了所执行的每项作业的状态的计数和图形表示形式。The summary displays a count and graphical representation of the job status for each job executed.

单击磁贴可显示“作业”页面,其中有所执行的全部作业的汇总列表。Clicking the tile presents the Jobs page, which includes a summarized list of all jobs executed. 该页面会显示每项作业的状态、Runbook 名称、开始时间和完成时间。This page shows the status, runbook name, start time, and completion time for each job.

自动化帐户作业页

可选择“筛选作业”来筛选作业的列表。You can filter the list of jobs by selecting Filter jobs. 根据特定 Runbook、作业状态或从下拉列表中选择的内容进行筛选,并提供搜索的时间范围。Filter on a specific runbook, job status, or a choice from the dropdown list, and provide the time range for the search.

筛选作业状态

或者,可从自动化帐户中的 Runbook 页面上选择特定的 Runbook,然后选择“作业”来查看该 Runbook 的作业摘要详情。Alternatively, you can view job summary details for a specific runbook by selecting that runbook from the Runbooks page in your Automation account and then selecting Jobs. 该操作会显示“作业”页面。This action presents the Jobs page. 你可在这里单击作业记录,查看它的详细信息和输出内容。From here, you can click a job record to view its details and output.

自动化帐户作业页

使用 PowerShell 检索作业状态Retrieve job statuses using PowerShell

使用 Get-AzAutomationJob cmdlet 检索为 Runbook 创建的作业和特定作业的详细信息。Use the Get-AzAutomationJob cmdlet to retrieve the jobs created for a runbook and the details of a particular job. 如果使用 Start-AzAutomationRunbook 启动 Runbook,它会返回生成的作业。If you start a runbook using Start-AzAutomationRunbook, it returns the resulting job. 使用 Get-AzAutomationJobOutput 检索作业输出。Use Get-AzAutomationJobOutput to retrieve job output.

以下示例会获取示例 Runbook 的最后一项作业,并显示它的状态、为 Runbook 参数提供的值以及作业的输出内容。The following example gets the last job for a sample runbook and displays its status, the values provided for the runbook parameters, and the job output.

$job = (Get-AzAutomationJob -AutomationAccountName "MyAutomationAccount" `
-RunbookName "Test-Runbook" -ResourceGroupName "ResourceGroup01" | sort LastModifiedDate -desc)[0]
$job.Status
$job.JobParameters
Get-AzAutomationJobOutput -ResourceGroupName "ResourceGroup01" `
-AutomationAccountName "MyAutomationAcct" -Id $job.JobId -Stream Output

以下示例会检索特定作业的输出,并返回每条记录。The following example retrieves the output for a specific job and returns each record. 如果其中一个记录出现异常,脚本将写出异常而不是值。If there's an exception for one of the records, the script writes the exception instead of the value. 此行为非常有用,因为异常可提供在输出过程中可能无法正常记录的其他信息。This behavior is useful since exceptions can provide additional information that might not be logged normally during output.

$output = Get-AzAutomationJobOutput -AutomationAccountName <AutomationAccountName> -Id <jobID> -ResourceGroupName <ResourceGroupName> -Stream "Any"
foreach($item in $output)
{
    $fullRecord = Get-AzAutomationJobOutputRecord -AutomationAccountName <AutomationAccountName> -ResourceGroupName <ResourceGroupName> -JobId <jobID> -Id $item.StreamRecordId
    if ($fullRecord.Type -eq "Error")
    {
        $fullRecord.Value.Exception
    }
    else
    {
    $fullRecord.Value
    }
}

后续步骤Next steps