配置 Runbook 输入参数Configure runbook input parameters

Runbook 输入参数允许在启动 Runbook 时向它传递数据,从而增加 Runbook 的灵活性。Runbook input parameters increase the flexibility of a runbook by allowing data to be passed to it when it's started. 这些参数可让 Runbook 操作以特定方案和环境为目标。These parameters allow runbook actions to be targeted for specific scenarios and environments. 本文介绍如何在 runbook 中配置和使用输入参数。This article describes the configuration and use of input parameters in your runbooks.

可以为 PowerShell、PowerShell 工作流、图形和 Python runbook 配置输入参数。You can configure input parameters for PowerShell, PowerShell Workflow, graphical, and Python runbooks. 一个 Runbook 可以包含具有不同数据类型的多个参数,或者不包含任何参数。A runbook can have multiple parameters with different data types, or no parameters at all. 输入参数可以是必需的或可选的,可以对可选参数使用默认值。Input parameters can be mandatory or optional, and you can use default values for optional parameters.

在启动 Runbook 时分配 Runbook 的输入参数值。You assign values to the input parameters for a runbook when you start it. 可以从 Azure 门户、Web 服务或 PowerShell 启动 Runbook。You can start a runbook from the Azure portal, a web service, or PowerShell. 还可以启动一个 Runbook 作为另一个 Runbook 中内联调用的子 Runbook。You can also start one as a child runbook that is called inline in another runbook.

在 PowerShell Runbook 中配置输入参数Configure input parameters in PowerShell runbooks

Azure 自动化中的 PowerShell 和 PowerShell 工作流 Runbook 支持通过以下属性定义的输入参数。PowerShell and PowerShell Workflow runbooks in Azure Automation support input parameters that are defined through the following properties.

属性Property 说明Description
类型Type 必需。Required. 参数值所需的数据类型。The data type expected for the parameter value. 任何 .NET 类型均有效。Any .NET type is valid.
名称Name 必需。Required. 参数的名称。The name of the parameter. 此名称在 Runbook 中必须唯一,必须以字母开头,并且只能包含字母、数字或下划线字符。This name must be unique within the runbook, must start with a letter, and can contain only letters, numbers, or underscore characters.
必需Mandatory 可选。Optional. 指定参数是否需要值的布尔值。Boolean value specifying if the parameter requires a value. 如果将此值设置为 True,则启动 Runbook 时必须提供一个值。If you set this to True, a value must be provided when the runbook is started. 如果将此值设置为 False,则值是可选的。If you set this to False, a value is optional. 如果没有为 Mandatory 属性指定值,则默认情况下,PowerShell 会将输入参数视为可选参数。If you don't specify a value for the Mandatory property, PowerShell considers the input parameter optional by default.
默认值Default value 可选。Optional. 一个值,在 Runbook 启动时未传入输入值的情况下用于参数。A value that is used for the parameter if no input value is passed in when the runbook starts. Runbook 可以为任何参数设置默认值。The runbook can set a default value for any parameter.

Windows PowerShell 支持的输入参数属性比上面所列的多,例如验证、别名和参数集。Windows PowerShell supports more attributes of input parameters than those listed above, such as validation, aliases, and parameter sets. 但是,Azure 自动化目前仅支持列出的输入参数属性。However, Azure Automation currently supports only the listed input parameter properties.

例如,让我们看一下 PowerShell 工作流 runbook 中的参数定义。As an example, let's look at a parameter definition in a PowerShell Workflow runbook. 此定义具有以下常规形式,其中,多个参数之间用逗号分隔。This definition has the following general form, where multiple parameters are separated by commas.

Param
(
  [Parameter (Mandatory= $true/$false)]
  [Type] $Name1 = <Default value>,

  [Parameter (Mandatory= $true/$false)]
  [Type] $Name2 = <Default value>
)

现在,让我们为输出有关虚拟机(可以是单个 VM 或资源组中的所有 VM)的详细信息的 PowerShell 工作流 Runbook 配置输入参数。Now let's configure the input parameters for a PowerShell Workflow runbook that outputs details about virtual machines, either a single VM or all VMs within a resource group. 如以下屏幕截图中所示,此 Runbook 有两个参数:虚拟机的名称 (VMName) 和资源组的名称 (resourceGroupName)。This runbook has two parameters, as shown in the following screenshot: the name of the virtual machine (VMName) and the name of the resource group (resourceGroupName).

自动化 PowerShell 工作流

在此参数定义中,输入参数是字符串类型的简单参数。In this parameter definition, the input parameters are simple parameters of type string.

请注意,PowerShell 和 PowerShell 工作流 Runbook 对于输入参数支持所有简单类型和复杂类型,例如 ObjectPSCredentialNote that PowerShell and PowerShell Workflow runbooks support all simple types and complex types, such as Object or PSCredential for input parameters. 如果 Runbook 有对象输入参数,则必须使用包含名称/值对的 PowerShell 哈希表来传入值。If your runbook has an object input parameter, you must use a PowerShell hashtable with name-value pairs to pass in a value. 例如,Runbook 中有以下参数。For example, you have the following parameter in a runbook.

[Parameter (Mandatory = $true)]
[object] $FullName

在此情况下,可将以下值传递到该参数。In this case, you can pass the following value to the parameter.

@{"FirstName"="Joe";"MiddleName"="Bob";"LastName"="Smith"}

备注

未将值传递到带有 null 默认值的可选字符串参数时,参数的值会为空字符串而不是 Null。When you do not pass a value to an optional String parameter with a null default value, the value of the parameter is an empty string instead of Null.

在图形 Runbook 中配置输入参数Configure input parameters in graphical runbooks

为了说明图形 Runbook 的输入参数配置,让我们创建输出有关虚拟机(可以是单个 VM 或资源组中的所有 VM)的详细信息的 Runbook。To illustrate the configuration of input parameters for a graphical runbook, let's create a runbook that outputs details about virtual machines, either a single VM or all VMs within a resource group. 有关详细信息,请参阅我的第一个图形 RunbookFor details, see My first graphical runbook.

图形 runbook 使用以下主要 runbook 活动:A graphical runbook uses these these major runbook activities:

  • 配置 Azure 运行方式帐户,以便与 Azure 进行身份验证。Configuration of the Azure Run As account to authenticate with Azure.
  • 定义 Get-AzVM cmdlet 以获取 VM 属性。Definition of a Get-AzVM cmdlet to get VM properties.
  • 使用 Write-Output 活动输出 VM 名称。Use of the Write-Output activity to output the VM names.

Get-AzVM 活动定义了两个输入:VM 名称和资源组名称。The Get-AzVM activity defines two inputs, the VM name and the resource group name. 由于这些名称在每次启动 runbook 时可能不同,因此必须将输入参数添加到 runbook 才能接受这些输入。Since these names can be different each time the runbook starts, you must add input parameters to your runbook to accept these inputs. 请参阅 Azure 自动化中的图形创作Refer to Graphical authoring in Azure Automation.

遵循以下步骤配置输入参数。Follow these steps to configure the input parameters.

  1. 从“Runbook”页选择图形 Runbook,然后单击“编辑”。Select the graphical runbook from the Runbooks page and then click Edit.

  2. 在图形编辑器中单击“输入和输出”按钮,然后单击“添加输入”打开“Runbook 输入参数”窗格。In the graphical editor, click the Input and output button then Add input to open the Runbook Input Parameter pane.

    自动化图形 Runbook

  3. “输入和输出”控件显示针对 Runbook 定义的输入参数列表。The Input and Output control displays a list of input parameters that are defined for the runbook. 在此处可以添加新的输入参数,或编辑现有输入参数的配置。Here you can either add a new input parameter or edit the configuration of an existing input parameter. 若要为 Runbook 添加新参数,请单击“添加输入”以打开“Runbook 输入参数”边栏选项卡,在其中可以使用 Azure 自动化中的图形创作中定义的属性来配置参数。To add a new parameter for the runbook, click Add input to open the Runbook input parameter blade, where you can configure parameters using the properties defined in Graphical authoring in Azure Automation.

    添加新输入

  4. 使用以下属性创建供 Get-AzVM 活动使用的两个参数,然后单击“确定”。Create two parameters with the following properties to be used by the Get-AzVM activity, and then click OK.

    • 参数 1:Parameter 1:

      • 名称 -- VMNameName -- VMName
      • 类型 -- 字符串Type -- String
      • 必需 -- 否Mandatory -- No
    • 参数 2:Parameter 2:

      • 名称 -- resourceGroupNameName -- resourceGroupName
      • 类型 -- 字符串Type -- String
      • 必需 -- 否Mandatory -- No
      • 默认值 -- 自定义Default value -- Custom
      • 自定义默认值 - 包含 VM 的资源组的名称Custom default value -- Name of the resource group that contains the VMs
  5. 查看“输入和输出”控件中的参数。View the parameters in the Input and Output control.

  6. 再次单击“确定”,然后单击“保存”。Click OK again, and then click Save.

  7. 单击“发布”以发布 runbook。Click Publish to publish your runbook.

在 Python Runbook 中配置输入参数Configure input parameters in Python runbooks

与 PowerShell、PowerShell 工作流和图形 Runbook 不同,Python Runbook 不使用命名参数。Unlike PowerShell, PowerShell Workflow, and graphical runbooks, Python runbooks do not take named parameters. Runbook 编辑器将所有输入参数分析为参数值的数组。The runbook editor parses all input parameters as an array of argument values. 可以通过将 sys 模块导入 Python 脚本,然后使用 sys.argv 数组来访问数组。You can access the array by importing the sys module into your Python script, and then using the sys.argv array. 请务必注意,数组的第一个元素 sys.argv[0] 是脚本的名称。It is important to note that the first element of the array, sys.argv[0], is the name of the script. 因此第一个实际输入参数是 sys.argv[1]Therefore the first actual input parameter is sys.argv[1].

若要获取如何在 Python Runbook 中使用输入参数的示例,请参阅我在 Azure 自动化中的第一个 Python RunbookFor an example of how to use input parameters in a Python runbook, see My first Python runbook in Azure Automation.

为 Runbook 中的输入参数赋值Assign values to input parameters in runbooks

此部分介绍将值传递给 Runbook 中的输入参数的多种方法。This section describes several ways to pass values to input parameters in runbooks. 可以在以下情况中分配参数值:You can assign parameter values when you:

启动 Runbook 并分配参数Start a runbook and assign parameters

Runbook 有多种启动方式:通过 Azure 门户、Webhook、PowerShell cmdlet、REST API 或 SDK。A runbook can be started in many ways: through the Azure portal, with a webhook, with PowerShell cmdlets, with the REST API, or with the SDK.

使用 Azure 门户启动已发布的 Runbook 并分配参数Start a published runbook using the Azure portal and assign parameters

在 Azure 门户中启动 Runbook 时,“启动 Runbook”边栏选项卡会打开,可以为所创建的参数输入值。When you start the runbook in the Azure portal, the Start Runbook blade opens and you can enter values for the parameters that you have created.

使用门户启动

在输入框下面的标签中,可以查看为定义参数特性(例如必需或可选、类型和默认值)而设置的属性。In the label beneath the input box, you can see the properties that have been set to define parameter attributes, for example, mandatory or optional, type, default value. 参数名称旁边的帮助气球也定义了做出参数输入值相关决策时所需的关键信息。The help balloon next to the parameter name also defines the key information needed to make decisions about parameter input values.

备注

字符串参数支持字符串类型的空值。String parameters support empty values of type String. 在输入参数框中输入 [EmptyString] 将向参数传递空字符串。Entering [EmptyString] in the input parameter box passes an empty string to the parameter. 此外,字符串参数不支持 Null。Also, string parameters don't support Null. 如果未向字符串参数传递任何值,PowerShell 会将值解释为 Null。If you don't pass any value to a string parameter, PowerShell interprets it as Null.

使用 PowerShell cmdlet 启动已发布的 Runbook 并分配参数Start a published runbook using PowerShell cmdlets and assign parameters

  • Azure 资源管理器 cmdlet: 可使用 Start-AzAutomationRunbook 启动在资源组中创建的自动化 Runbook。Azure Resource Manager cmdlets: You can start an Automation runbook that was created in a resource group by using Start-AzAutomationRunbook.

       $params = @{"VMName"="WSVMClassic";"resourceGroupeName"="WSVMClassicSG"}
    
       Start-AzAutomationRunbook -AutomationAccountName "TestAutomation" -Name "Get-AzureVMGraphical" –ResourceGroupName $resourceGroupName -Parameters $params
    
  • Azure 经典部署模型 cmdlet: 可使用 Start-AzureAutomationRunbook 启动在默认资源组中创建的自动化 Runbook。Azure classic deployment model cmdlets: You can start an automation runbook that was created in a default resource group by using Start-AzureAutomationRunbook.

       $params = @{"VMName"="WSVMClassic"; "ServiceName"="WSVMClassicSG"}
    
       Start-AzureAutomationRunbook -AutomationAccountName "TestAutomation" -Name "Get-AzureVMGraphical" -Parameters $params
    

备注

使用 PowerShell cmdlet 启动 runbook 时,将创建默认参数 MicrosoftApplicationManagementStartedBy,其值为 PowerShellWhen you start a runbook using PowerShell cmdlets, a default parameter, MicrosoftApplicationManagementStartedBy, is created with the value PowerShell. 可在“作业详细信息”窗格中查看此参数。You can view this parameter on the Job details pane.

使用 SDK 启动 Runbook 并分配参数Start a runbook using an SDK and assign parameters

  • Azure 资源管理器方法: 可使用编程语言的 SDK 来启动 Runbook。Azure Resource Manager method: You can start a runbook using the SDK of a programming language. 以下 C# 代码段用于在自动化帐户中启动 Runbook。Below is a C# code snippet for starting a runbook in your Automation account. 可以在 GitHub 存储库中查看完整代码。You can view all the code at our GitHub repository.

    public Job StartRunbook(string runbookName, IDictionary<string, string> parameters = null)
        {
          var response = AutomationClient.Jobs.Create(resourceGroupName, automationAccount, new JobCreateParameters
           {
              Properties = new JobCreateProperties
               {
                  Runbook = new RunbookAssociationProperty
                   {
                     Name = runbookName
                   },
                     Parameters = parameters
               }
           });
        return response.Job;
        }
    
  • Azure 经典部署模型方法: 可使用编程语言的 SDK 来启动 Runbook。Azure classic deployment model method: You can start a runbook by using the SDK of a programming language. 以下 C# 代码段用于在自动化帐户中启动 Runbook。Below is a C# code snippet for starting a runbook in your Automation account. 可以在 GitHub 存储库中查看完整代码。You can view all the code at our GitHub repository.

    public Job StartRunbook(string runbookName, IDictionary<string, string> parameters = null)
      {
        var response = AutomationClient.Jobs.Create(automationAccount, new JobCreateParameters
      {
        Properties = new JobCreateProperties
           {
             Runbook = new RunbookAssociationProperty
           {
             Name = runbookName
                },
                  Parameters = parameters
                }
         });
        return response.Job;
      }
    

    若要启动此方法,请创建一个字典来存储 Runbook 参数 VMNameresourceGroupName 及其值。To start this method, create a dictionary to store the runbook parameters VMName and resourceGroupName and their values. 然后启动 Runbook。Then start the runbook. 以下 C# 代码段用于调用上面定义的方法。Below is the C# code snippet for calling the method that's defined above.

    IDictionary<string, string> RunbookParameters = new Dictionary<string, string>();
    
    // Add parameters to the dictionary.
    RunbookParameters.Add("VMName", "WSVMClassic");
    RunbookParameters.Add("resourceGroupName", "WSSC1");
    
    //Call the StartRunbook method with parameters
    StartRunbook("Get-AzureVMGraphical", RunbookParameters);
    

使用 REST API 启动 Runbook 并分配参数Start a runbook using the REST API and assign parameters

可在以下请求 URI 中使用 PUT 方法通过 Azure 自动化 REST API 来创建并启动 Runbook 作业:https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/jobs/{jobName}?api-version=2017-05-15-previewYou can create and start a runbook job with the Azure Automation REST API by using the PUT method with the following request URI: https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/jobs/{jobName}?api-version=2017-05-15-preview

在请求 URI 中替换以下参数:In the request URI, replace the following parameters:

  • subscriptionId:Azure 订阅 ID。subscriptionId: Your Azure subscription ID.
  • resourceGroupName:自动化帐户的资源组的名称。resourceGroupName: The name of the resource group for the Automation account.
  • automationAccountName:托管在指定云服务中的自动化帐户的名称。automationAccountName: The name of the Automation account that's hosted within the specified cloud service.
  • jobName:作业的 GUID。jobName: The GUID for the job. 可以使用 [GUID]::NewGuid().ToString()* 创建 PowerShell 中的 GUID。GUIDs in PowerShell can be created by using [GUID]::NewGuid().ToString()*.

若要将参数传递到 Runbook 作业,请使用请求正文。To pass parameters to the runbook job, use the request body. 它采用以 JSON 格式提供的以下信息:It takes the following information, provided in JSON format:

  • Runbook 名称:必需。Runbook name: Required. 作业要启动的 Runbook 的名称。The name of the runbook for the job to start.
  • Runbook 参数:可选。Runbook parameters: Optional. 采用 (名称, 值) 格式的参数列表的字典,其中的名称应为字符串类型,值可以是任何有效的 JSON 值。A dictionary of the parameter list in (name, value) format, where name is of type String and value can be any valid JSON value.

如果想要启动之前以 VMNameresourceGroupName 作为参数创建的 Get-AzureVMTextual Runbook,请将以下 JSON 格式用于请求正文。If you want to start the Get-AzureVMTextual runbook created earlier with VMName and resourceGroupName as parameters, use the following JSON format for the request body.

    {
      "properties":{
        "runbook":{
        "name":"Get-AzureVMTextual"},
      "parameters":{
         "VMName":"WindowsVM",
         "resourceGroupName":"ContosoSales"}
        }
    }

如果成功创建了作业,将返回 HTTP 状态代码 201。An HTTP status code 201 is returned if the job is successfully created. 有关响应标头和响应正文的详细信息,请参阅使用 REST API 创建 Runbook 作业For more information on response headers and the response body, see create a runbook job by using the REST API.

测试 Runbook 并分配参数Test a runbook and assign parameters

使用测试选项测试 runbook 的草稿版本时,将打开“测试”页。When you test the draft version of your runbook by using the test option, the Test page opens. 使用此页可为已创建的参数配置值。Use this page to configure values for the parameters that you have created.

测试并分配参数

将计划链接到 Runbook,以便在特定的时间启动 Runbook。You can link a schedule to your runbook so that the runbook starts at a specific time. 创建计划时将指定输入参数,Runbook 在按计划启动时,将使用这些值。You assign input parameters when you create the schedule, and the runbook uses these values when it is started by the schedule. 只有在提供所有必需参数值之后,才可以保存计划。You can't save the schedule until all mandatory parameter values are provided.

计划并分配参数

创建 Runbook 的 Webhook 并分配参数Create a webhook for a runbook and assign parameters

可为 Runbook 创建 Webhook 并配置 Runbook 输入参数。You can create a webhook for your runbook and configure runbook input parameters. 只有在提供所有必需参数值之后,才可以保存 Webhook。You can't save the webhook until all mandatory parameter values are provided.

创建 webhook 并分配参数

当使用 Webhook 执行 Runbook 时,将连同定义的输入参数一起发送预定义的输入参数 [WebhookData](automation-webhooks.md)When you execute a runbook by using a webhook, the predefined input parameter [WebhookData](automation-webhooks.md) is sent, along with the input parameters that you define.

WebhookData 参数

将 JSON 对象传递给 runbookPass a JSON object to a runbook

它可用于存储想要传递到 JSON 文件中的 Runbook 的数据。It can be useful to store data that you want to pass to a runbook in a JSON file. 例如,你可能会创建包含所有想要传递给 Runbook 的参数的 JSON 文件。For example, you might create a JSON file that contains all parameters that you want to pass to a runbook. 为此,必须先将 JSON 代码转换为字符串,将字符串转换为 PowerShell 对象,然后再将其传递到 Runbook。To do this, you must convert the JSON code to a string and then convert the string to a PowerShell object before passing it to the runbook.

此部分使用一个示例,其中 PowerShell 脚本会调用 Start-AzAutomationRunbook 来启动 PowerShell Runbook,将 JSON 文件的内容传递给 Runbook。This section uses an example in which a PowerShell script calls Start-AzAutomationRunbook to start a PowerShell runbook, passing the contents of the JSON file to the runbook. 该 PowerShell Runbook 通过从 JSON 对象检索 Azure VM 的参数,来启动该 VM。The PowerShell runbook starts an Azure VM by retrieving the parameters for the VM from the JSON object.

创建 JSON 文件Create the JSON file

在文本文件中键入以下代码,并在本地计算机上将其保存为 test.json。Type the following code in a text file, and save it as test.json somewhere on your local computer.

{
   "VmName" : "TestVM",
   "ResourceGroup" : "AzureAutomationTest"
}

创建 RunbookCreate the runbook

在 Azure 自动化中创建名为“Test-Json”的新 PowerShell Runbook。Create a new PowerShell runbook named Test-Json in Azure Automation. 请参阅我的第一个 PowerShell RunbookSee My first PowerShell runbook.

要接受 JSON 数据,Runbook 必须将一个对象作为输入参数。To accept the JSON data, the runbook must take an object as an input parameter. 然后,Runbook 可以使用 JSON 文件中定义的属性。The runbook can then use the properties defined in the JSON file.

Param(
     [parameter(Mandatory=$true)]
     [object]$json
)

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

# Convert object to actual JSON
$json = $json | ConvertFrom-Json

# Use the values from the JSON object as the parameters for your command
Start-AzVM -Name $json.VMName -ResourceGroupName $json.ResourceGroup

在自动化帐户中保存并发布此 Runbook。Save and publish this runbook in your Automation account.

通过 PowerShell 调用 RunbookCall the runbook from PowerShell

现在可以通过 Azure PowerShell 从本地计算机调用 Runbook。Now you can call the runbook from your local machine by using Azure PowerShell.

  1. 如图所示登录 Azure。Sign in to Azure as shown. 之后,系统会提示输入 Azure 凭据。Afterward, you're prompted to enter your Azure credentials.

    Connect-AzAccount -Environment AzureChinaCloud
    

    备注

    对于 PowerShell Runbook,Add-AzAccountAdd-AzureRMAccountConnect-AzAccount 的别名。For PowerShell runbooks, Add-AzAccount and Add-AzureRMAccount are aliases for Connect-AzAccount. 请注意,这些别名不适用于图形 Runbook。Note that these aliases are not available for graphical runbooks. 图形 Runbook 只能使用 Connect-AzAccount 本身。A graphical runbook can only use Connect-AzAccount itself.

  2. 获取已保存 JSON 文件的内容并将其转换为字符串。Get the contents of the saved JSON file and convert it to a string. JsonPath 指示保存 JSON 文件的位置路径。JsonPath indicates the path where you saved the JSON file.

    $json =  (Get-content -path 'JsonPath\test.json' -Raw) | Out-string
    
  3. $json 的字符串内容转换为 PowerShell 对象。Convert the string contents of $json to a PowerShell object.

    $JsonParams = @{"json"=$json}
    
  4. Start-AzAutomationRunbook 的参数创建哈希表。Create a hashtable for the parameters for Start-AzAutomationRunbook.

    $RBParams = @{
         AutomationAccountName = 'AATest'
         ResourceGroupName = 'RGTest'
         Name = 'Test-Json'
         Parameters = $JsonParams
    }
    

    请注意,你正在将 Parameters 的值设置为包含 JSON 文件中的值的 PowerShell 对象。Notice that you're setting the value of Parameters to the PowerShell object that contains the values from the JSON file.

  5. 启动 Runbook。Start the runbook.

    $job = Start-AzAutomationRunbook @RBParams
    

后续步骤Next steps