监视 runbook 输出Monitor runbook output

大多数 Azure 自动化 runbook 都有某种形式的输出。Most Azure Automation runbooks have some form of output. 此输出可能是发给用户的错误消息,也可能是你打算用于另一个 runbook 的复杂对象。This output can be an error message to the user or a complex object intended to be used 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 using the streams when you're creating a runbook.

下表简要介绍了发布的 Runbook 以及测试 Runbook 期间每个流及其在 Azure 门户的行为。The following table briefly describes each stream with its behavior in the Azure portal for published runbooks and during testing of a runbook. 输出流是用于 Runbook 间通信的主流。The output stream is the main stream used for communication between runbooks. 其他流分类为消息流,旨在向用户传递信息。The other streams are classified as message streams, intended to communicate information to the user.

StreamStream 说明Description 已发布Published 测试Test
错误Error 面向用户的错误消息。Error message intended for the user. 与发生异常时不同,默认情况下,在出现错误消息后,Runbook 会继续执行。Unlike with an exception, the runbook continues after an error message by default. 写入作业历史记录Written to job history 显示在测试输出窗格中Displayed in Test output pane
调试Debug 面向交互式用户的消息。Messages intended for an interactive user. 不应在 Runbook 中使用。Shouldn't be used in runbooks. 不会写入作业历史记录Not written to job history 不显示在测试输出窗格中Not displayed in Test output pane
输出Output 对象旨在由其他 Runbook 使用。Objects intended to be consumed by other runbooks. 写入作业历史记录Written to job history 显示在测试输出窗格中Displayed in Test output pane
进度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 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 Test output pane only if VerbosePreference variable is set to Continue in runbook
警告Warning 面向用户的警告消息。Warning message intended for the user. 写入作业历史记录Written to job history 显示在测试输出窗格中Displayed in Test output pane

使用输出流Use the output stream

输出流用于输出脚本或工作流创建的对象(如果该脚本或工作流正常运行)。The output stream is used for the output of objects created by a script or workflow when it runs correctly. Azure 自动化将此流主要用于供调用当前 Runbook 的父 Runbook 使用的对象。Azure Automation primarily uses this stream for objects to be consumed by parent runbooks that call the current runbook. 父 Runbook 调用某个内联 Runbook 时,子 Runbook 会将输出流中的数据返回给父 Runbook。When a parent calls a runbook inline, the child returns data from the output stream to the parent.

仅当某个 runbook 永不会被其他 runbook 调用时,该 runbook 才使用输出流向客户端传递常规信息。Your runbook uses the output stream to communicate general information to the client only if it is never called by another runbook. 但是,最佳做法是 Runbook 通常使用详细流向用户传递常规信息。As a best practice, however, you runbooks should typically use the verbose stream to communicate general information to the user.

让 runbook 使用 Write-Output 将数据写入输出流。Have your runbook write data to the output stream using Write-Output. 或者,你可以在脚本中将对象放置在其自己的行上。Alternatively, you can put the object on its own line in the script.

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

处理函数输出Handle output from a function

当 runbook 函数写入到输出流时,输出会传递回 runbook。When a runbook function writes to the output stream, the output is passed back to the runbook. 如果 Runbook 将该输出分配给某个变量,则不会将输出写入到输出流。If the runbook assigns that output to a variable, the output 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. 请考虑以下示例 PowerShell 工作流 runbook。Consider the following sample PowerShell Workflow 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 is:

Output inside of function
Output outside of function

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

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.

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

下面是输出数据类型的示例:The following are examples of output data types:

  • System.String
  • System.Int32
  • System.Collections.Hashtable
  • Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine

在工作流中声明输出数据类型Declare output data type in a workflow

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

以下示例 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
}

在图形 runbook 中声明输出数据类型Declare output data type in a graphical runbook

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

备注

在“输入和输出”属性窗格中的“输出类型”字段中输入值后,请务必在控件的外部单击,以使其能够识别你的输入。After you enter a value in the Output Type field in the Input and Output properties pane, be sure to click outside the control so that it recognizes your entry.

以下示例展示两个图形 Runbook 来演示输入和输出功能。The following example shows two graphical runbooks to demonstrate the Input and Output feature. 如果应用模块式 Runbook 设计模型,则有一个 Runbook,它作为身份验证 Runbook 模板来管理使用运行方式帐户通过 Azure 进行的身份验证。Applying the modular runbook design model, you have one runbook as the Authenticate Runbook template managing authentication with Azure using the Run As account. 第二个 Runbook 通常执行核心逻辑来自动执行给定方案,在本例中,执行身份验证 Runbook 模板。The second runbook, which normally performs core logic to automate a given scenario, in this case executes the Authenticate Runbook template. 它会将结果显示在测试输出窗格中。It displays 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.

Runbook 包括输出类型 Microsoft.Azure.Commands.Profile.Models.PSAzureContext,它将返回身份验证配置文件属性。The runbook 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 straightforward, there is one configuration item to call out here. 最后一个活动执行 Write-Output cmdlet,将配置文件数据写入到对 Inputobject 参数使用 PowerShell 表达式的变量。The last activity executes the Write-Output cmdlet to write profile data to a variable using a PowerShell expression for the Inputobject parameter. 此参数是 Write-Output 必需的。This parameter is required for Write-Output.

本示例中名为 Test-ChildOutputType 的第二个 Runbook 仅定义两项活动。The second runbook in this example, named Test-ChildOutputType, simply defines two activities.
示例子输出类型 RunbookExample Child Output Type Runbook

第一个活动调用 AuthenticateTo-Azure Runbook。The first activity calls the AuthenticateTo-Azure runbook. 第二个活动运行 Write-Verbose cmdlet,其中“数据源”设置为“活动输出”。The second activity runs the Write-Verbose cmdlet with Data source set to Activity output. 此外,“字段路径”设置为 Context.Subscription.SubscriptionName,上下文输出来自 AuthenticateTo-Azure Runbook。Also, Field path is set to Context.Subscription.SubscriptionName, 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 结果

监视消息流Monitor message streams

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

监视警告和错误流Monitor warning and error streams

警告和错误流记录 Runbook 中出现的问题。The warning and error streams log problems that occur in a runbook. 执行 Runbook 时,Azure 自动化会将这些流写入作业历史记录。Azure Automation writes these streams to the job history when executing a runbook. 在测试 Runbook 时,自动化包括 Azure 门户的“测试输出”窗格中的流。Automation includes the streams in the Test output pane in the Azure portal when a runbook is tested.

默认情况下,在出现警告或错误后,Runbook 将继续执行。By default, a runbook continues to execute after a warning or error. 创建消息之前,可以通过在 Runbook 中设置首选项变量,指定应在出现警告或错误时挂起 Runbook。You can specify that your runbook should suspend on a warning or error by having the runbook set a preference variable before creating the message. 例如,要使 Runbook 在出现错误时挂起(就像发生异常时那样),请将 ErrorActionPreference 变量设置为 Stop。For example, to cause the runbook to suspend on an error as it does on an exception, set the ErrorActionPreference variable to Stop.

使用 Write-WarningWrite-Error cmdlet 创建警告或错误消息。Create a warning or error message using the Write-Warning or Write-Error cmdlet. 活动还可以写入警告和错误流。Activities can also write to the warning and error 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."

监视调试流Monitor debug stream

Azure 自动化对交互式用户使用调试消息流。Azure Automation uses the debug message stream for interactive users. 不应在 Runbook 中使用。It should not be used in runbooks.

监视详细流Monitor verbose stream

详细消息流支持有关 Runbook 操作的一般信息。The Verbose message stream supports general information about runbook operation. 由于调试流在 Runbook 中不可用,因此,应该为调试信息使用详细消息。Since the debug stream is not available for a runbook, your runbook should use verbose messages for debug information.

出于性能方面的原因,默认情况下,作业历史记录不会存储来自已发布 Runbook 的详细消息。By default, the job history does not store verbose messages from published runbooks, for performance reasons. 若要存储详细消息,请使用 Azure 门户“配置”选项卡和“日志详细记录”设置,将已发布的 Runbook 配置为记录详细消息。To store verbose messages, use the Azure portal Configure tab with the Log Verbose Records setting to configure your published runbooks to log verbose messages. 启用此选项的目的只是为了排查 Runbook 的问题或对它进行调试。Turn on this option only to troubleshoot or debug a runbook. 在大多数情况下,应该保留默认设置,即,不记录详细记录。In most cases, you should keep the default setting of not logging verbose records.

测试 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 创建详细消息。The following code creates a verbose message using the Write-Verbose cmdlet.

#The following line creates a verbose message.

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

处理进度记录Handle progress records

你可以使用 Azure 门户的“配置”选项卡将 Runbook 配置为记录进度记录。You can use the Configure tab of the Azure portal to configure a runbook to log progress records. 默认设置为不记录这些记录,以最大程度地提高性能。The default setting is to not log the records, to maximize performance. 在大多数情况下,应该保留默认设置。In most cases, you should keep the default setting. 启用此选项的目的只是为了排查 Runbook 的问题或对它进行调试。Turn on this option only to troubleshoot or debug a runbook.

如果启用进度记录的日志记录,Runbook 会在每个活动运行前后向作业历史记录中写入一条记录。If you enable progress record logging, your runbook writes a record to job history before and after each activity runs. 测试 Runbook 不会显示进度消息,即使已将该 Runbook 配置为记录进度记录也不显示。Testing a runbook does not display progress messages 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.

使用首选项变量Work with preference variables

你可以在 runbook 中设置某些 Windows PowerShell 首选项变量,以控制发送到不同输出流的数据的响应。You can set certain Windows PowerShell preference variables in your runbooks to control the response to data sent to different output streams. 下表列出了可在 Runbook 中使用的首选项变量及其默认值和有效值。The following table lists the preference variables that can be used in runbooks, with their default and valid values. 在 Azure 自动化外部的 Windows PowerShell 中使用时,首选项变量可使用其他值。Additional values are available for the preference variables when used in Windows PowerShell outside of Azure Automation.

变量Variable 默认值Default Value 有效值Valid Values
WarningPreference 继续Continue 停止Stop
继续Continue
SilentlyContinueSilentlyContinue
ErrorActionPreference 继续Continue 停止Stop
继续Continue
SilentlyContinueSilentlyContinue
VerbosePreference SilentlyContinueSilentlyContinue 停止Stop
继续Continue
SilentlyContinueSilentlyContinue

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

Value 行为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 输出和消息Retrieve runbook output and messages

检索 Azure 门户中的 Runbook 输出和消息Retrieve runbook output and messages in Azure portal

可以在 Azure 门户中使用 Runbook 的“作业”选项卡查看 Runbook 作业的详细信息。You can view the details of a runbook job in the Azure portal using the Jobs tab for the runbook. 作业摘要显示输入参数和输出流,此外,还显示有关作业的一般信息以及发生的任何异常。The job summary displays the input parameters and the output stream, in addition to general information about the job and any exceptions that have occurred. “作业历史记录”包括来自输出流以及警告和错误流的消息。The job history includes messages from the output stream and warning and error streams. 如果 runbook 已配置为记录详细记录和进度记录,其还包含来自详细流以及进度记录的消息。It also includes messages from the verbose stream and progress records if the runbook is configured to log verbose and progress records.

在 Windows PowerShell 中检索 Runbook 输出和消息Retrieve runbook output and messages in Windows PowerShell

在 Windows PowerShell 中,可以使用 Get-AzAutomationJobOutput cmdlet 检索 Runbook 的输出和消息。In Windows PowerShell, you can retrieve output and messages from a runbook using the Get-AzAutomationJobOutput cmdlet. 此 cmdlet 需要作业的 ID,还有一个名为 Stream 的参数(用于指定要检索的流)。This cmdlet requires the ID of the job and has a parameter called Stream in which to specify the stream to retrieve. 可以为此参数指定 Any 值,以检索作业的所有流。You can specify a value of Any for this parameter to retrieve all streams for the job.

以下示例将启动一个示例 Runbook,然后等待该 Runbook 完成。The following example starts a sample runbook and then waits for it to complete. Runbook 执行完毕后,该脚本将从作业收集 Runbook 输出流。Once the runbook completes execution, the script collects the runbook output stream 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

检索图形 Runbook 中的 Runbook 输出和消息Retrieve runbook output and messages in graphical runbooks

对于图形 Runbook,以活动级别跟踪形式提供了输出和消息的额外日志记录。For graphical runbooks, extra logging of output and messages is available in the form of activity-level tracing. 有两个级别的跟踪:基本和详细。There are two levels of tracing: Basic and Detailed. 基本跟踪显示 runbook 中每个活动的开始和结束时间,以及与任何活动重试相关的信息。Basic tracing displays the start and end time for each activity in the runbook, plus information related to any activity retries. 一些示例是活动的尝试次数和开始时间。Some examples are the number of attempts and the start time of the activity. 详细跟踪包括基本跟踪功能以及每个活动的输入和输出数据日志记录。Detailed tracing includes basic tracing features plus logging of input and output data for each activity.

当前活动级别跟踪使用详细流写入记录。Currently activity-level tracing writes records using the verbose stream. 因此,当启用跟踪时,必须启用详细日志记录。Therefore 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 image that enabling verbose logging and tracing for graphical runbooks makes much more information available in the production Job Streams view. 此额外信息对于故障排除 Runbook 的生产问题可能至关重要。This extra information can be essential for troubleshooting production problems with a runbook.

但是,除非需要此信息来跟踪 Runbook 进度以进行故障排除,否则你可能想要按一般做法使跟踪保持关闭状态。However, unless you require this information to track the progress of a runbook for troubleshooting, you might want to keep tracing turned off 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 your configuration of Basic or Detailed tracing.

若要启用活动级别跟踪:To enable activity-level tracing:

  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”页上,从 Runbook 列表中选择图形 Runbook。On the Runbooks page, 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.

  6. 在“活动级别跟踪”下,根据所需的跟踪级别,将跟踪级别更改为“基本”或“详细”。Under Activity-level tracing, change the trace level to Basic or Detailed, based on the level of tracing you require.

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

在 Azure Monitor 日志中检索 Runbook 输出和消息Retrieve runbook output and messages in Azure Monitor logs

Azure 自动化可以将 Runbook 作业状态和作业流发送到 Log Analytics 工作区。Azure Automation can send runbook job status and job streams to your Log Analytics workspace. Azure Monitor 支持允许你执行以下操作的日志:Azure Monitor supports logs that allow you to:

  • 获取有关自动化作业的见解。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 job streams.
  • 跨自动化帐户关联作业。Correlate jobs across Automation accounts.
  • 可视化作业历史记录。Visualize job history.

有关配置与 Azure Monitor 日志的集成以收集、关联和处理作业数据的详细信息,请参阅将作业状态和作业流从自动化转发到 Azure Monitor 日志For more information on configuring 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