Azure 自动化中的 Runbook 输出和消息Runbook output and messages in Azure Automation

大多数 Azure 自动化 runbook 都有某种形式的输出。Most Azure Automation runbooks have some form of output. 此输出可能是发给用户的错误消息,也可能是你打算用于另一个 runbook 的复杂对象。This output could be an error message to the user or a complex object you intend to use with another runbook. Windows PowerShell 提供 多个流 ,以便从脚本或工作流发送输出。Windows PowerShell provides multiple streams to send output from a script or workflow. Azure 自动化以不同方式处理每个流。Azure Automation works with each of these streams differently. 在创建 runbook 时,应遵循如何使用每种方法的最佳实践。You should follow best practices for how to use each when you're creating a runbook.

下表简要介绍了 Azure 门户中的每个流及其对已发布的 runbook 的行为以及测试 runbook 的时间。The following table provides a brief description of each of the streams and their behavior in the Azure portal for published runbooks and when testing a runbook. 后面的部分将提供有关每个流的更多详细信息。Further details on each stream are provided in later sections.

StreamStream 说明Description 已发布Published 测试Test
输出Output 对象旨在由其他 Runbook 使用。Objects intended to be consumed by other runbooks. 写入作业历史记录。Written to the job history. 显示在测试输出窗格中。Displayed in the Test Output Pane.
警告Warning 面向用户的警告消息。Warning message intended for the user. 写入作业历史记录。Written to the job history. 显示在测试输出窗格中。Displayed in the Test Output Pane.
错误Error 面向用户的错误消息。Error message intended for the user. 与发生异常时不同,默认情况下,在出现错误消息后,Runbook 会继续执行。Unlike an exception, the runbook continues after an error message by default. 写入作业历史记录。Written to the job history. 显示在测试输出窗格中。Displayed in the Test Output Pane.
详细Verbose 提供一般信息或调试信息的消息。Messages that give general or debugging information. 仅当为 Runbook 启用了详细日志记录时,才写入作业历史记录。Written to job history only if verbose logging is turned on for the runbook. 仅当在 Runbook 中将 $VerbosePreference 设置为 Continue 时,才显示在“测试输出”窗格中。Displayed in the Test Output pane only if $VerbosePreference is set to Continue in the runbook.
进度Progress 完成 Runbook 中每个活动之前和之后自动生成的记录。Records automatically generated before and after each activity in the runbook. 由于 runbook 面向交互式用户,因此不应尝试创建自身的进度记录。The runbook shouldn't try to create its own progress records since they're intended for an interactive user. 仅当为 Runbook 启用了进度日志记录时,才写入作业历史记录。Written to job history only if progress logging is turned on for the runbook. 不显示在测试输出窗格中。Not displayed in the Test Output Pane.
调试Debug 面向交互式用户的消息。Messages intended for an interactive user. 不应在 Runbook 中使用。Shouldn't be used in runbooks. 不会写入作业历史记录。Not written to job history. 不会写入测试输出窗格。Not written to Test Output Pane.

输出流Output stream

输出流旨在输出脚本或工作流创建的对象(如果该脚本或工作流正常运行)。The Output stream is intended for output of objects, which are created by a script or workflow when it runs correctly. 在 Azure 自动化中,此流主要用于调用当前 Runbook 的父 Runbook 使用的对象。In Azure Automation, this stream is primarily used for objects intended to be consumed by parent runbooks that call the current runbook. 从父 Runbook 调用某个内嵌 Runbook 时,被调用的 Runbook 会将输出流中的数据返回给父级。When you call a runbook inline from a parent runbook, it returns data from the output stream to the parent. 仅在知道该 runbook 永不会被其他 runbook 调用时,才使用输出流将一般信息传回给用户。Only use the output stream to communicate general information back to the user if you know the runbook is never called by another runbook. 但是,作为最佳实践,通常应该使用 详细流 向用户传递一般信息。As a best practice, however, you should typically use the Verbose Stream to communicate general information to the user.

可以使用 Write-Output,或者在 Runbook 中将对象放置在其对应行中,向输出流写入数据。You can write data to the output stream using Write-Output or by putting the object on its own line in the runbook.

#The following lines both write an object to the output stream.
Write-Output -InputObject $object
$object

函数的输出Output from a function

向 runbook 中包含的函数写入输出流时,输出将传回到 runbook。When you write to the output stream in a function that's included in your runbook, the output is passed back to the runbook. 如果 Runbook 将该输出分配给某个变量,则不会将数据写入到输出流。If the runbook assigns that output to a variable, then it is not written to the output stream. 向函数内部的任何其他流写入数据会向 Runbook 的相应流写入数据。Writing to any other streams from within the function writes to the corresponding stream for the runbook.

请考虑以下示例 Runbook:Consider the following sample runbook:

Workflow Test-Runbook
{
  Write-Verbose "Verbose outside of function" -Verbose
  Write-Output "Output outside of function"
  $functionOutput = Test-Function
  $functionOutput

  Function Test-Function
  {
    Write-Verbose "Verbose inside of function" -Verbose
    Write-Output "Output inside of function"
  }
}

Runbook 作业的输出流会是:The output stream for the runbook job would be:

Output inside of function
Output outside of function

Runbook 作业的详细流将是:The verbose stream for the runbook job would be:

Verbose outside of function
Verbose inside of function

发布 runbook 后,在启动它之前,还必须在 runbook 设置中打开详细日志记录,以获取详细的流输出。Once you've published the runbook and before you start it, you must also turn on Verbose logging in the runbook settings to get the Verbose stream output.

声明输出数据类型Declaring output data type

工作流可以使用 OutputType 属性指定其输出的数据类型。A workflow can specify the data type of its output using the OutputType attribute. 此属性在运行时不起作用,但在设计时,它可以向 Runbook 作者指明 Runbook 的预期输出。This attribute has no effect during runtime, but it provides an indication to the runbook author at design time of the expected output of the runbook. 随着 Runbook 工具集的持续发展,在设计时声明输出数据类型的重要性也在不断提升。As the toolset for runbooks continues to evolve, the importance of declaring output data types at design time increases in importance. 因此,最佳做法是在创建的所有 runbook 中包含此声明。As a result, it's a best practice to include this declaration in any runbooks that you create.

以下是示例输出类型列表:Here is a list of example output types:

  • System.StringSystem.String
  • System.Int32System.Int32
  • System.Collections.HashtableSystem.Collections.Hashtable
  • Microsoft.Azure.Commands.Compute.Models.PSVirtualMachineMicrosoft.Azure.Commands.Compute.Models.PSVirtualMachine

以下示例 Runbook 输出一个字符串对象,并包含其输出类型的声明。The following sample runbook outputs a string object and includes a declaration of its output type. 如果 Runbook 输出了特定类型的数组,则你仍应该指定相对于该类型数组的类型。If your runbook outputs an array of a certain type, then you should still specify the type as opposed to an array of the type.

Workflow Test-Runbook
{
  [OutputType([string])]

  $output = "This is some string output."
  Write-Output $output
}

要在图形 PowerShell 工作流 Runbook 中声明输出类型,可选择“输入和输出” 菜单选项,并键入输出类型的名称。To declare an output type in Graphical or Graphical PowerShell Workflow runbooks, you can select the Input and Output menu option and type in the name of the output type. 建议使用完整的 .NET 类名,以便从父 runbook 引用该类时可轻松识别它。It's recommended you use the full .NET class name to make it easily identifiable when referencing it from a parent runbook. 这会向 Runbook 中的数据总线公开该类的所有属性,并在将其用于条件逻辑、日志记录和作为 Runbook 中其他活动的值引用时提供很大灵活性。This exposes all the properties of that class to the data bus in the runbook and provides much flexibility when using them for conditional logic, logging, and referencing as values for other activities in the runbook.
Runbook 输入和输出选项Runbook Input and Output option

以下示例使用两个图形 Runbook 来演示此功能。In the following example, you have two graphical runbooks to demonstrate this feature. 如果应用模块式 Runbook 设计模型,则有一个 Runbook,它作为身份验证 Runbook 模板 来管理使用运行方式帐户通过 Azure 进行的身份验证。If you apply the modular runbook design model, you have one runbook, which serves as the Authentication Runbook template managing authentication with Azure using the Run As account. 在此情况下,通常执行核心逻辑以自动实施给定方案的第二个 Runbook 将执行该身份验证 Runbook 模板 ,并在“测试” 输出窗格中显示结果。Our second runbook, which would normally perform the core logic to automate a given scenario, in this case is going to execute the Authentication Runbook template and display the results to your Test output pane. 在正常情况下,会使用此 Runbook 针对利用子 Runbook 输出的资源执行某些操作。Under normal circumstances, you would have this runbook do something against a resource leveraging the output from the child runbook.

下面是 AuthenticateTo-Azure Runbook 的基本逻辑。Here is the basic logic of the AuthenticateTo-Azure runbook.
身份验证 Runbook 模板示例Authenticate Runbook Template Example.

它包括 Microsoft.Azure.Commands.Profile.Models.PSAzureContext 输出类型,此输出类型将返回身份验证配置文件属性。It includes the output type Microsoft.Azure.Commands.Profile.Models.PSAzureContext, which returns the authentication profile properties.
Runbook 输出类型示例Runbook Output Type Example

尽管此 Runbook 操作非常简单,此处仍需调出一个配置项。While this runbook is straight forward, there is one configuration item to call out here. 最后的活动执行 Write-Output cmdlet,并使用该 cmdlet 所需 Inputobject 参数的 PowerShell 表达式将配置文件数据写入 $_ 变量。The last activity is executing the Write-Output cmdlet and writes the profile data to a $_ variable using a PowerShell expression for the Inputobject parameter, which is required for that cmdlet.

对于本示例中名为 Test-ChildOutputType 的第二个 Runbook,仅需提供两项活动。For the second runbook in this example, named Test-ChildOutputType, you simply have two activities.
示例子输出类型 RunbookExample Child Output Type Runbook

第一个活动调用 AuthenticateTo Azure Runbook,第二个活动运行包含活动输出 数据源Write-Verbose cmdlet,并且字段路径的值为 Context.Subscription.SubscriptionName,用于指定来自 AuthenticateTo-Azure Runbook 的上下文输出。The first activity calls the AuthenticateTo-Azure runbook and the second activity is running the Write-Verbose cmdlet with the Data source of Activity output and the value for Field path is Context.Subscription.SubscriptionName, which is specifying the context output from the AuthenticateTo-Azure runbook.
Write-Verbose cmdlet 参数数据源Write-Verbose cmdlet Parameter Data Source

生成的输出是订阅名称。The resulting output is the name of the subscription.
Test-ChildOutputType Runbook 结果

备注

在“输入和输出属性” 窗格的“输出类型” 框中输入值后,必须在控件外部单击,以便控件可以识别输入。After you enter a value in the Output Type box in the Input and Output properties pane, you have to click outside the control so that your entry can be recognized by the control.

消息流Message streams

与输出流不同,消息流旨在向用户传递信息。Unlike the output stream, message streams are intended to communicate information to the user. 有多个消息流用于传递不同类型的信息,Azure 自动化以不同的方式处理每个消息流。There are multiple message streams for different kinds of information, and each is handled differently by Azure Automation.

警告和错误流Warning and error streams

警告和错误流旨在记录 Runbook 中出现的问题。The Warning and Error streams are intended to log problems that occur in a runbook. 在执行 Runbook 时,这些流将写入作业历史记录;在测试 Runbook 时,它们将包含在 Azure 门户的测试输出窗格中。They are written to the job history when a runbook is executed, and are included in the Test Output Pane in the Azure portal when a runbook is tested. 默认情况下,在出现警告或错误后,Runbook 将继续执行。By default, the runbook will continue executing after a warning or error. 在创建消息之前,可以通过在 Runbook 中设置 preference 变量 ,指定 Runbook 应在出现警告或错误时挂起。You can specify that the runbook should be suspended on a warning or error by setting a preference variable in the runbook before creating the message. 例如,要使 Runbook 在出现错误时挂起(就像发生异常时那样),请将 $ErrorActionPreference 设置为 Stop。For example, to cause a runbook to suspend on an error as it would an exception, set $ErrorActionPreference to Stop.

使用 Write-WarningWrite-Error cmdlet 创建警告或错误消息。Create a warning or error message using the Write-Warning or Write-Error cmdlet. 活动可能也会向这些流写入数据。Activities may also write to these streams.

#The following lines create a warning message and then an error message that will suspend the runbook.

$ErrorActionPreference = "Stop"
Write-Warning -Message "This is a warning message."
Write-Error -Message "This is an error message that will stop the runbook because of the preference variable."

详细流Verbose stream

详细消息流用于传递有关 Runbook 操作的一般信息。The Verbose message stream is for general information about the runbook operation. 由于 调试流 在 Runbook 中不可用,因此,应该为调试信息使用详细消息。Since the Debug Stream is not available in a runbook, verbose messages should be used for debug information. 默认情况下,来自已发布 runbook 的详细消息不会存储在作业历史记录中。By default, verbose messages from published runbooks are not stored in the job history. 要存储详细消息,请在 Azure 门户中 Runbook 的“配置”选项卡上,将已发布 Runbook 配置为“记录详细记录”。To store verbose messages, configure published runbooks to Log Verbose Records on the Configure tab of the runbook in the Azure portal. 在大多数情况下,出于性能方面的原因,应该保留默认设置,即,不记录详细记录。In most cases, you should keep the default setting of not logging verbose records for a runbook for performance reasons. 启用此选项的目的只是为了排查 Runbook 的问题或对它进行调试。Turn on this option only to troubleshoot or debug a runbook.

测试 runbook 时,即使已将该 runbook 配置为记录详细记录,详细消息也不会显示。When testing a runbook, verbose messages aren't displayed even if the runbook is configured to log verbose records. 要在测试 Runbook时显示详细消息,必须将 $VerbosePreference 变量设置为 Continue。To display verbose messages while testing a runbook, you must set the $VerbosePreference variable to Continue. 设置该变量后,Azure 门户的测试输出窗格中会显示详细消息。With that variable set, verbose messages are displayed in the Test Output Pane of the Azure portal.

使用 Write-Verbose cmdlet 创建详细消息。Create a verbose message using the Write-Verbose cmdlet.

#The following line creates a verbose message.

Write-Verbose -Message "This is a verbose message."

调试流Debug stream

调试流旨在供交互式用户使用,不应在 Runbook 中使用。The Debug stream is intended for use with an interactive user and should not be used in runbooks.

进度记录Progress records

如果将 Runbook 配置为记录进度记录(在 Azure 门户中 Runbook 的“配置”选项卡上),则在运行每个活动之前和之后,会向作业历史记录中写入一条记录。If you configure a runbook to log progress records (on the Configure tab of the runbook in the Azure portal), then a record will be written to the job history before and after each activity is run. 在大多数情况下,应该保留默认设置,即,不记录 Runbook 的进度记录,以最大程度地提高性能。In most cases, you should keep the default setting of not logging progress records for a runbook in order to maximize performance. 启用此选项的目的只是为了排查 Runbook 的问题或对它进行调试。Turn on this option only to troubleshoot or debug a runbook. 在测试 Runbook 时,不会显示进度消息,即使已将该 Runbook 配置为记录进度记录。When testing a runbook, progress messages are not displayed even if the runbook is configured to log progress records.

Write-Progress cmdlet 在 runbook 中无效,因为此 cmdlet 旨在供交互式用户使用。The Write-Progress cmdlet is not valid in a runbook, since this cmdlet is intended for use with an interactive user.

Preference 变量Preference variables

Windows PowerShell 使用 Preference 变量确定如何响应发送到不同输出流的数据。Windows PowerShell uses preference variables to determine how to respond to data sent to different output streams. 可以在 Runbook 中设置这些变量,以控制 Runbook 如何响应发送到不同流中的数据。You can set these variables in a runbook to control how it responds to data sent into different streams.

下表列出了可在 Runbook 中使用的 preference 变量及其有效值和默认值。The following table lists the preference variables that can be used in runbooks with their valid and default values. 此表仅包含在 Runbook 中有效的值。This table only includes the values that are valid in a runbook. preference 变量的其他值在 Azure 自动化外部的 Windows PowerShell 中使用时有效。Additional values are valid for the preference variables when used in Windows PowerShell outside of Azure Automation.

变量Variable 默认值Default Value 有效值Valid Values
WarningPreferenceWarningPreference 继续Continue 停止Stop
继续Continue
SilentlyContinueSilentlyContinue
ErrorActionPreferenceErrorActionPreference 继续Continue 停止Stop
继续Continue
SilentlyContinueSilentlyContinue
VerbosePreferenceVerbosePreference SilentlyContinueSilentlyContinue StopStop
继续Continue
SilentlyContinueSilentlyContinue

下表列出了在 Runbook 中有效的 preference 变量值的行为。The following table lists the behavior for the preference variable values that are valid in runbooks.

ValueValue 行为Behavior
继续Continue 记录消息并继续执行 Runbook。Logs the message and continues executing the runbook.
SilentlyContinueSilentlyContinue 继续执行 Runbook 但不记录消息。Continues executing the runbook without logging the message. 该值会导致忽略消息。This value has the effect of ignoring the message.
停止Stop 记录消息并挂起 Runbook。Logs the message and suspends the runbook.

检索 runbook 输出和消息Retrieving runbook output and messages

Azure 门户Azure portal

可以从 Azure 门户中 Runbook 的“作业”选项卡查看 Runbook 作业的详细信息。You can view the details of a runbook job in the Azure portal from the Jobs tab of a runbook. 作业的“摘要”会显示输入参数和输出流 ,此外,还显示有关作业的一般信息以及发生的任何异常。The Summary of the job displays the input parameters and the Output Stream in addition to general information about the job and any exceptions if they occurred. “历史记录”包含来自输出流以及警告和错误流的消息;此外,如果 runbook 已配置为记录详细记录和进度记录,则还包含详细流进度记录The History includes messages from the Output Stream and Warning and Error Streams as well as the Verbose Stream and Progress Records if the runbook is configured to log verbose and progress records.

Windows PowerShellWindows PowerShell

在 Windows PowerShell 中,可以使用 Get-AzureAutomationJobOutput cmdlet 检索 Runbook 的输出和消息。In Windows PowerShell, you can retrieve output and messages from a runbook using the Get-AzureAutomationJobOutput cmdlet. 此 cmdlet 需要作业的 ID,如果指定了要返回的流,则它还要使用一个名为 Stream 的参数。This cmdlet requires the ID of the job and has a parameter called Stream where you specify which stream to return. 可以指定 Any 来返回作业的所有流。You can specify Any to return all streams for the job.

以下示例将启动一个示例 Runbook,并等待该 Runbook 完成。The following example starts a sample runbook and then waits for it to complete. 完成后,从作业收集该 Runbook 的输出流。Once completed, its output stream is collected from the job.

$job = Start-AzAutomationRunbook -ResourceGroupName "ResourceGroup01" `
  -AutomationAccountName "MyAutomationAccount" -Name "Test-Runbook"

$doLoop = $true
While ($doLoop) {
  $job = Get-AzAutomationJob -ResourceGroupName "ResourceGroup01" `
    -AutomationAccountName "MyAutomationAccount" -Id $job.JobId
  $status = $job.Status
  $doLoop = (($status -ne "Completed") -and ($status -ne "Failed") -and ($status -ne "Suspended") -and ($status -ne "Stopped"))
}

Get-AzAutomationJobOutput -ResourceGroupName "ResourceGroup01" `
  -AutomationAccountName "MyAutomationAccount" -Id $job.JobId -Stream Output

# For more detailed job output, pipe the output of Get-AzAutomationJobOutput to Get-AzAutomationJobOutputRecord
Get-AzAutomationJobOutput -ResourceGroupName "ResourceGroup01" `
  -AutomationAccountName "MyAutomationAccount" -Id $job.JobId -Stream Any | Get-AzAutomationJobOutputRecord

图形创作Graphical Authoring

对于图形 Runbook,以活动级别跟踪形式提供了额外的日志记录。For graphical runbooks, extra logging is available in the form of activity-level tracing. 有两个级别的跟踪:基本和详细。There are two levels of tracing: Basic and Detailed. 在基本跟踪中,可以查看 runbook 中每个活动的开始和结束时间,以及与任何活动重试相关的信息。In Basic tracing, you can see the start and end time of each activity in the runbook plus information related to any activity retries. 一些示例是活动的尝试次数和开始时间。Some examples are, the number of attempts and start time of the activity. 在详细跟踪中,可获取基本跟踪以及每个活动的输入和输出数据。In Detailed tracing, you get Basic tracing plus input and output data for each activity. 目前跟踪记录是使用详细流写入的,因此,必须在启用跟踪时启用详细日志记录。Currently the trace records are written using the verbose stream, so you must enable Verbose logging when you enable tracing. 对于启用了跟踪的图形 runbook,无需记录进度记录。For graphical runbooks with tracing enabled, there's no need to log progress records. 基本跟踪起着相同的目的,并且提供更多信息。Basic tracing serves the same purpose and is more informative.

“图形创作作业流”视图

从前面的屏幕截图可以看出,为图形 Runbook 启用详细日志记录和跟踪时,在“生产作业流”视图中会提供更多信息。You can see from the preceding screenshot that when you enable Verbose logging and tracing for Graphical runbooks, much more information is available in the production Job Streams view. 此额外信息对于解决 Runbook 的生产问题是非常必要的,因此应仅为该目的启用它,而不是作为一种常规做法。This extra information can be essential for troubleshooting production problems with a runbook, and therefore you should only enable it for that purpose and not as a general practice. “跟踪”记录可以特别大量。The Trace records can be especially numerous. 使用图形 Runbook 跟踪,每个活动可以获取二至四条记录,具体取决于是配置了基本跟踪还是详细跟踪。With Graphical runbook tracing, you can get two to four records per activity depending on whether you have configured Basic or Detailed tracing. 除非需要此信息来跟踪 Runbook 进度以进行故障排除,否则你可能想要使跟踪保持关闭状态。Unless you need this information to track the progress of a runbook for troubleshooting, you might want to keep Tracing turned off.

若要启用活动级别跟踪,请执行以下步骤:To enable activity-level tracing, perform the following steps:

  1. 在 Azure 门户中,打开自动化帐户。In the Azure portal, open your Automation account.

  2. 在“流程自动化”下选择“Runbook”,打开 Runbook 的列表。 Under Process Automation, select Runbooks to open the list of runbooks.

  3. 在“Runbook”页上,单击以从 Runbook 列表中选择图形 Runbook。On the Runbooks page, click to select a graphical runbook from your list of runbooks.

  4. 在“设置” 下,单击“日志记录和跟踪” 。Under Settings, click Logging and tracing.

  5. 在“日志记录和跟踪”页的“日志详细记录”下,单击“启用”以启用详细日志记录;在“活动级别跟踪”下,根据所需的跟踪级别,将跟踪级别更改为“基本”或“详细” 。On the Logging and Tracing page, under Log verbose records, click On to enable verbose logging and under Activity-level tracing, change the trace level to Basic or Detailed based on the level of tracing you require.

    “图形创作日志记录和跟踪”页面

Azure Monitor 日志Azure Monitor logs

自动化可以将 Runbook 作业状态和作业流发送到 Log Analytics 工作区。Automation can send runbook job status and job streams to your Log Analytics workspace. 可以使用 Azure Monitor 日志进行以下操作:With Azure Monitor logs you can,

  • 获取有关自动化作业的见解Get insight on your Automation jobs
  • 基于 Runbook 作业状态(例如失败或暂停)触发电子邮件或警报Trigger an email or alert based on your runbook job status (for example, failed or suspended)
  • 针对所有作业流编写高级查询Write advanced queries across your job streams
  • 跨自动化帐户关联作业Correlate jobs across Automation accounts
  • 可视化不同时间段的作业历史记录Visualize your job history over time

有关如何配置与 Azure Monitor 日志的集成以收集、关联和处理作业数据的详细信息,请参阅将作业状态和作业流从自动化转发到 Azure Monitor 日志For more information on how to configure integration with Azure Monitor logs to collect, correlate and act on job data, see Forward job status and job streams from Automation to Azure Monitor logs.

后续步骤Next steps