教程:创建 PowerShell 工作流 RunbookTutorial: Create a PowerShell Workflow runbook

本教程指导在 Azure 自动化中创建 PowerShell 工作流 RunbookThis tutorial walks you through the creation of a PowerShell Workflow runbook in Azure Automation. PowerShell 工作流 Runbook 是基于 Windows PowerShell 工作流的文本 Runbook。PowerShell Workflow runbooks are text runbooks based on Windows PowerShell Workflow. 可以在 Azure 门户中使用文本编辑器创建和编辑 Runbook 的代码。You can create and edit the code of the runbook using the text editor in the Azure portal.

  • 创建简单的 PowerShell 工作流 RunbookCreate a simple PowerShell Workflow runbook
  • 测试并发布 RunbookTest and publish the runbook
  • 运行 Runbook 作业并跟踪其状态Run and track the status of the runbook job
  • 更新 Runbook 以使用 Runbook 参数启动 Azure 虚拟机Update the runbook to start an Azure virtual machine with runbook parameters

先决条件Prerequisites

要完成本教程,需要:To complete this tutorial, you need:

  • Azure 订阅。Azure subscription. 如果没有订阅,可注册试用版If you don't have one yet, you can sign up for a Trial.
  • 自动化帐户 ,用来保存 Runbook 以及向 Azure 资源进行身份验证。Automation account to hold the runbook and authenticate to Azure resources. 此帐户必须有权启动和停止虚拟机。This account must have permission to start and stop the virtual machine.
  • Azure 虚拟机。An Azure virtual machine. 由于我们要停止并启动此虚拟机,因此它不应是用于生产的 VM。Since you stop and start this machine, it shouldn't be a production VM.

步骤 1 - 创建新的 RunbookStep 1 - Create new runbook

首先创建一个输出文本 Hello World 的简单 Runbook。Start by creating a simple runbook that outputs the text Hello World.

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

    通过自动化帐户页面可快速查看此帐户中的资源。The Automation account page gives you a quick view of the resources in this account. 应该已拥有某些资产。You should already have some assets. 其中的大多数资产都是自动包含在新自动化帐户中的模块。Most of those assets are the modules automatically included in a new Automation account. 此外,应准备好与订阅关联的凭据资产。You should also have the Credential asset associated with your subscription.

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

  3. 选择“创建 Runbook”,创建一个新的 Runbook。Create a new runbook by selecting Create a runbook.

  4. 将该 Runbook 命名为 MyFirstRunbook-WorkflowGive the runbook the name MyFirstRunbook-Workflow.

  5. 在此示例中,我们将创建 PowerShell Workflow RunbookIn this case, you're going to create a PowerShell Workflow runbook. 对于“Runbook 类型”,请选择“PowerShell 工作流”。 Select PowerShell Workflow for Runbook type.

  6. 单击“创建”以创建 Runbook 并打开文本编辑器 。Click Create to create the runbook and open the textual editor.

步骤 2 - 将代码添加到 RunbookStep 2 - Add code to the runbook

可以直接将代码键入 Runbook 中,或者从“库”控件中选择 cmdlet、Runbook 和资产,并使用任何相关的参数将它们添加到 Runbook。You can either type code directly into the runbook, or you can select cmdlets, runbooks, and assets from the Library control and add them to the runbook with any related parameters. 对于本教程,请直接在 Runbook 中键入代码。For this tutorial, you type code directly into the runbook.

  1. Runbook 目前为空,只有必需的 Workflow 关键字、Runbook 名称以及括住整个工作流的大括号。Your runbook is currently empty with only the required Workflow keyword, the name of the runbook, and the braces that encase the entire workflow.

    Workflow MyFirstRunbook-Workflow
    {
    }
    
  2. 在大括号中键入 Write-Output "Hello World"Type Write-Output "Hello World" between the braces.

    Workflow MyFirstRunbook-Workflow
    {
    Write-Output "Hello World"
    }
    
  3. 通过单击“保存” 保存 Runbook。Save the runbook by clicking Save.

步骤 3 - 测试 RunbookStep 3 - Test the runbook

在发布 Runbook 以使其可在生产环境中使用之前,应该对其进行测试,以确保它能正常工作。Before you publish the runbook to make it available in production, you should test it to make sure that it works properly. 测试 Runbook 会运行其草稿版,可以交互方式查看其输出。Testing a runbook runs its Draft version and allows you to view its output interactively.

  1. 选择“测试窗格”打开“测试”窗格。Select Test pane to open the Test pane.

  2. 单击“启动”以启动测试,并测试唯一启用的选项。Click Start to start the test, with testing the only enabled option.

  3. 请注意,已创建了一个 Runbook 作业,其状态显示在窗格中。Note that a runbook job is created and its status is displayed in the pane.

    作业状态最初为“已排队”,表示该作业正在等待云中的 Runbook 辅助角色变为可用状态。The job status starts as Queued, indicating that the job is waiting for a runbook worker in the cloud to become available. 在某个辅助角色认领该作业后,状态将更改为“正在启动”。The status changes to Starting when a worker claims the job. 最后,在 Runbook 实际开始运行时,状态将变为“正在运行”。Finally, the status becomes Running when the runbook actually starts to run.

  4. Runbook 作业完成后,“测试”窗格会显示其输出。When the runbook job completes, the Test pane displays its output. 在本例中,你会看到 Hello WorldIn this case, you see Hello World.

    Hello World

  5. 关闭测试窗格以返回到画布。Close the Test pane to return to the canvas.

步骤 4 - 发布和启动 RunbookStep 4 - Publish and start the runbook

你创建的 Runbook 仍处于草稿模式。The runbook that you've created is still in Draft mode. 必须先发布它,然后才能在生产中运行它。You must publish it before you can run it in production. 当发布 Runbook 时,可以用草稿版本覆盖现有的已发布版本。When you publish a runbook, you overwrite the existing Published version with the Draft version. 在本例中,还没有已发布版本,因为刚刚创建 Runbook。In this case, you don't have a Published version yet because you just created the runbook.

  1. 单击“发布”以发布该 Runbook,并在出现提示时单击“是” 。Click Publish to publish the runbook and then Yes when prompted.

  2. 向左滚动以在“Runbook”页上查看该 Runbook,请注意“创作状态”字段设置为“已发布”。 Scroll left to view the runbook in the Runbooks page and note that the Authoring Status field is set to Published.

  3. 向右滚动以查看 MyFirstRunbook-Workflow 的页面。Scroll back to the right to view the page for MyFirstRunbook-Workflow.

    顶部的选项现在可用于启动 Runbook、计划将来的启动时间,或创建一个 webhook 以便通过 HTTP 调用来启动 Runbook。The options across the top allow you to start the runbook now, schedule a future start time, or create a webhook so that the runbook can be started through an HTTP call.

  4. 选择“启动”,并在出现提示时选择“是” 启动 runbook。Select Start and then Yes when prompted to start the runbook.

    启动 Runbook

  5. 此时将打开已创建的 Runbook 作业的“作业”窗格。A Job pane is opened for the runbook job that has been created. 在这种情况下,请使窗格保持打开,以便可以查看作业进度。In this case, leave the pane open so you can watch the job's progress.

  6. 请注意,作业状态显示在“作业摘要”中。Note that the job status is shown in Job Summary. 此状态与测试 runbook 时看到的状态相匹配。This status matches the statuses that you saw when testing the runbook.

    作业摘要

  7. 在 Runbook 状态显示为“已完成”后,单击“输出”。Once the runbook status shows Completed, click Output. 此时会打开“输出”页,可以在其中看到 Hello World 消息。The Output page is opened, where you can see your Hello World message.

    作业摘要

  8. 关闭“输出”页。Close the Output page.

  9. 单击“所有日志”打开 Runbook 作业的“流”窗格。Click All Logs to open the Streams pane for the runbook job. 在输出流中应该只会看到 Hello WorldYou should only see Hello World in the output stream. 请注意,“流”窗格可以显示 Runbook 作业的其他流,例如,详细流和错误流(如果 Runbook 向其写入内容)。Note that the Streams pane can show other streams for a runbook job, such as verbose and error streams, if the runbook writes to them.

    作业摘要

  10. 关闭“流”窗格和“作业”窗格以返回到 MyFirstRunbook 页面。Close the Streams pane and the Job pane to return to the MyFirstRunbook page.

  11. 在“资源”下单击“作业”以打开此 Runbook 的“作业”页面。 Click Jobs under Resources to open the Jobs page for this runbook. 此页列出你的 Runbook 创建的所有作业。This page lists all the jobs created by your runbook. 由于只运行了一次作业,因此你应当只会看到一个作业。You should only see one job listed, since you have run the job only once.

作业

  1. 单击作业名称,打开在启动 Runbook 时出现过的同一个“作业”窗格。Click the job name to open the same Job pane that you viewed when you started the runbook. 使用此窗格查看为 Runbook 创建的任何作业的详细信息。Use this pane to view the details of any job created for the runbook.

步骤 5 - 添加身份验证来管理 Azure 资源Step 5 - Add authentication to manage Azure resources

已经测试并发布 Runbook,但到目前为止它不执行任何有用的操作。You've tested and published your runbook, but so far it doesn't do anything useful. 需要让其管理 Azure 资源。You want to have it manage Azure resources. 除非它使用订阅凭据进行身份验证,否则不能执行此操作。It can't do that unless it authenticates using the credentials for the subscription. 身份验证使用 Connect-AzureRmAccount cmdlet。Authentication uses the Connect-AzureRmAccount cmdlet.

备注

对于 PowerShell Runbook,Add-AzureRMAccountlogin-AzureRMAccountConnect-AzureRmAccount 的别名。For PowerShell runbooks, Add-AzureRMAccount and login-AzureRMAccount are aliases for Connect-AzureRmAccount.

  1. 导航到 MyFirstRunbook-Workflow 窗格,并通过单击“编辑”打开文本编辑器。Navigate to the MyFirstRunbook-Workflow page and open the textual editor by clicking Edit.

  2. 删除 Write-Output 行。Delete the Write-Output line.

  3. 将光标放在大括号之间的空白行上。Position the cursor on a blank line between the braces.

  4. 键入(或者复制并粘贴)以下代码,对自动化运行方式帐户的身份验证进行处理。Type or copy and paste the following code, which handles the authentication with your Automation Run As account.

    # Ensures you do not inherit an AzureRMContext in your runbook
    Disable-AzureRmContextAutosave -Scope Process
    
    $Conn = Get-AutomationConnection -Name AzureRunAsConnection
    Connect-AzureRmAccount -ServicePrincipal -Tenant $Conn.TenantID `
    -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint -EnvironmentName "AzureChinaCloud"
    
    $AzureContext = Select-AzureRmSubscription -SubscriptionId $Conn.SubscriptionID
    
  5. 单击“测试”窗格,以便测试 Runbook。Click Test pane so that you can test the runbook.

  6. 单击“启动”以启动测试 。Click Start to start the test. 完成后,你会看到类似于以下内容的输出,显示帐户中的基本信息。Once it completes, you should see output similar to the following, displaying basic information from your account. 此操作确认凭据有效。This action confirms that the credential is valid.

    Authenticate

步骤 6 – 添加用于启动虚拟机的代码Step 6 - Add code to start a virtual machine

现在 Runbook 正在向 Azure 订阅进行身份验证,你可以管理资源。Now that your runbook is authenticating to the Azure subscription, you can manage resources. 让我们添加一项命令,用于启动虚拟机。Let's add a command to start a virtual machine. 可以选取你的 Azure 订阅中的任何 VM,而现在,你需要将该名称硬编码到 Runbook 中。You can pick any VM in your Azure subscription, and for now you're hardcoding that name in the runbook. 如果要跨多个订阅管理资源,需要使用 -AzureRmContext 参数以及 Get-AzureRmContext cmdlet。If you're managing resources across multiple subscriptions, you need to use the -AzureRmContext parameter with the Get-AzureRmContext cmdlet.

  1. 提供要启动的 VM 的名称和其资源组名称,方法是输入对 Start-AzureRmVM cmdlet 的调用,如下所示。Provide the name and resource group name of the VM to start by entering a call to the Start-AzureRmVM cmdlet as shown below.

    workflow MyFirstRunbook-Workflow
    {
    # Ensures that you do not inherit an AzureRMContext in your runbook
    Disable-AzureRmContextAutosave -Scope Process
    
    $Conn = Get-AutomationConnection -Name AzureRunAsConnection
    Connect-AzureRmAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint -EnvironmentName "AzureChinaCloud"
    
    $AzureContext = Select-AzureRmSubscription -SubscriptionId $Conn.SubscriptionID
    
    Start-AzureRmVM -Name 'VMName' -ResourceGroupName 'ResourceGroupName' -AzureRmContext $AzureContext
    }
    
  2. 保存 Runbook,并单击“测试”窗格,以便可以测试 Runbook。Save the runbook and then click Test pane so that you can test it.

  3. 单击“启动”以启动测试 。Click Start to start the test. 在测试完成后,检查 VM 是否已启动。Once it completes, check that the VM has been started.

步骤 7 - 将输入参数添加到 RunbookStep 7 - Add an input parameter to the runbook

你的 runbook 当前会启动你在 runbook 中硬编码的 VM。Your runbook currently starts the VM that you have hardcoded in the runbook. 如果可以在启动 Runbook 时指定 VM,它会更有用。It will be more useful if you can specify the VM when the runbook is started. 让我们向 Runbook 中添加输入参数,以提供该功能。Let's add input parameters to the runbook to provide that functionality.

  1. VMNameResourceGroupName 参数的变量添加到 Runbook,并将这些变量与 Start-AzureRmVM cmdlet 一起使用,如下所示。Add variables for the VMName and ResourceGroupName parameters to the runbook, and use the variables with the Start-AzureRmVM cmdlet as shown below.

    workflow MyFirstRunbook-Workflow
    {
     Param(
      [string]$VMName,
      [string]$ResourceGroupName
     )
    # Ensures you do not inherit an AzureRMContext in your runbook
    Disable-AzureRmContextAutosave -Scope Process
    
    $Conn = Get-AutomationConnection -Name AzureRunAsConnection
    Connect-AzureRmAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint -EnvironmentName "AzureChinaCloud"
    Start-AzureRmVM -Name $VMName -ResourceGroupName $ResourceGroupName
    }
    
  2. 保存 Runbook 并打开“测试”窗格。Save the runbook and open the Test pane. 现在可以为测试中使用的两个输入变量提供值。You can now provide values for the two input variables that are in the test.

  3. 关闭“测试”窗格。Close the Test pane.

  4. 单击“发布”以发布 Runbook 的新版本 。Click Publish to publish the new version of the runbook.

  5. 停止已启动的 VM。Stop the VM that you have started.

  6. 单击“启动”以启动 Runbook ResourceGroupNameClick Start to start the runbook.

  7. 键入要启动的 VM 的 VMNAMERESOURCEGROUPNAME 值。Type in the values for VMNAME and RESOURCEGROUPNAME for the VM that you're going to start.

    启动 Runbook

  8. 在 Runbook 完成后,验证 VM 是否已启动。When the runbook completes, verify that the VM has started.

后续步骤Next steps