教程:创建 Python RunbookTutorial: Create a Python runbook

本教程介绍了如何在 Azure 自动化中创建 Python RunbookThis tutorial walks you through the creation of a Python runbook in Azure Automation. 在 Python 2 下编译 Python runbook。Python runbooks compile under Python 2. 可以在 Azure 门户中使用文本编辑器直接编辑 Runbook 的代码。You can directly edit the code of the runbook using the text editor in the Azure portal.

  • 创建简单的 Python RunbookCreate a simple Python 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


不支持使用 Webhook 来启动 Python Runbook。Using a webhook to start a Python runbook is not supported.


要完成本教程,需要以下各项:To complete this tutorial, you need the following:

  • Azure 订阅。Azure subscription. 如果还没有 Azure 订阅,可注册一个试用版订阅If you don't have one yet, you can sign up for a Trial Subscription.
  • 自动化帐户 ,用来保存 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。You stop and start this machine so it should not be a production VM.

创建新的 RunbookCreate a new runbook

首先创建一个输出文本 Hello World 的简单 Runbook。You 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 that are automatically included in a new Automation account. 还应具有在 “先决条件”中提到的凭证资产。You should also have the Credential asset that's mentioned in the prerequisites.

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

  3. 选择“添加 Runbook”,创建一个新的 Runbook。Select Add a runbook to create a new runbook.

  4. 将该 Runbook 命名为 MyFirstRunbook-Python。Give the runbook the name MyFirstRunbook-Python.

  5. 选择“Python 2”作为“Runbook 类型”。 Select Python 2 for Runbook type.

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

将代码添加到 RunbookAdd code to the runbook

现在添加一个简单的命令来输出文本 Hello WorldNow you add a simple command to print the text Hello World.

print("Hello World!")

单击“保存”保存 runbook。Click Save to save the runbook.

测试 RunbookTest the runbook

在发布 Runbook 使其可在生产中使用之前,需对其进行测试以确保其能正常工作。Before you publish the runbook to make it available in production, you want to test it to make sure that it works properly. 测试 Runbook 时,可以运行其“草稿”版本并以交互方式查看其输出。When you test a runbook, you run its Draft version and view its output interactively.

  1. 单击“测试窗格” 打开测试窗格。Click Test pane to open the Test pane.

  2. 单击“启动”以启动测试 。Click Start to start the test. 这应该是唯一的已启用选项。This should be the only enabled option.

  3. 将创建一个 Runbook 作业 并显示其状态。A runbook job is created and its status displayed. 作业状态一开始为“排队”,表示正在等待云中的 Runbook 辅助角色变为可用状态。The job status starts as Queued, indicating that it is waiting for a runbook worker in the cloud to come available. 在某个辅助角色认领此作业后,作业状态将变为“正在启动”,然后当 Runbook 开始实际运行时,此状态将变为“正在运行”。It moves to Starting when a worker claims the job, and then Running when the runbook actually starts running.

  4. Runbook 作业完成后,会显示其输出。When the runbook job completes, its output is displayed. 在此示例中,应会看到 Hello WorldIn this case, you should see Hello World.

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

发布和启动 RunbookPublish and start the runbook

创建的 Runbook 仍处于“草稿”模式。The runbook that you created is still in Draft mode. 需要首先发布此 Runbook 才能在生产中运行它。You need to 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,应该会看到“创作状态”为“已发布” 。If you scroll left to view the runbook on the Runbooks page, you should see an Authoring Status of Published.

  3. 向右滚动查看“MyFirstRunbook-Python”窗格。Scroll back to the right to view the pane for MyFirstRunbook-Python.

    可以通过顶部的选项来启动 Runbook、查看 Runbook,或计划在将来的某个时间启动它。The options across the top allow you to start the runbook, view the runbook, or schedule it to start at some time in the future.

  4. 单击“启动”,在“启动 Runbook”边栏选项卡打开后单击“确定”。Click Start and then click OK when the Start Runbook blade opens.

  5. 此时会为你创建的 Runbook 作业打开一个“作业”窗格。A Job pane is opened for the runbook job that you created. 可以关闭此窗格,但我们将使其保持打开状态,以便查看作业的进度。You can close this pane, but let's leave it open so that you can watch the job's progress.

  6. 作业状态显示在“作业摘要”中并且与测试该 Runbook 时看到的状态相匹配。The job status is shown in Job Summary and matches the statuses that you saw when you tested the runbook.

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

  8. 关闭“输出”窗格。Close the Output pane.

  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 向其中写入内容)。However, this pane can show other streams for a runbook job, such as Verbose and Error, if the runbook writes to them.

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

  11. 单击“作业”以打开此 Runbook 的“作业”页。Click Jobs to open the Jobs page for this runbook. 此页列出此 Runbook 创建的所有作业。This page lists all jobs created by this runbook. 由于只运行该作业一次,应该只会看到一个列出的作业。You should only see one job listed since you only ran the job once.

  12. 可以单击此作业,打开在启动 Runbook 时查看过的“作业”窗格。You can click this job to open the same Job pane that you viewed when you started the runbook. 你可以随时返回到此窗格,并查看为特定 Runbook 创建的任何作业的详细信息。This pane allows you to go back in time and view the details of any job that was created for a particular runbook.

添加身份验证来管理 Azure 资源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. 因此,脚本必须使用你的自动化帐户的凭据进行身份验证。To do this, the script has to authenticate using the credentials from your Automation account. 如需帮助,可以使用 Azure 自动化实用工具包更轻松地进行身份验证以及与 Azure 资源交互。To help you, you can use the Azure Automation utility package to make it easier to authenticate and interact with Azure resources.


必须使用服务主体功能来创建自动化帐户,以便使用运行方式证书。The Automation account must have been created with the service principal feature for there to be a Run As certificate. 如果你的自动化帐户不是使用服务主体创建的,则可根据使用用于 Python 的 Azure 管理库进行身份验证中的说明进行身份验证。If your Automation account was not created with the service principal, you can authenticate as described in Authenticate with the Azure Management Libraries for Python.

  1. 通过单击 MyFirstRunbook-Python 窗格上的“编辑”打开文本编辑器。Open the textual editor by clicking Edit on the MyFirstRunbook-Python pane.

  2. 添加以下代码以对 Azure 进行身份验证:Add the following code to authenticate to Azure:

    import os
    from azure.mgmt.compute import ComputeManagementClient
    import azure.mgmt.resource
    import automationassets
    def get_automation_runas_credential(runas_connection):
        from OpenSSL import crypto
        import binascii
        from msrestazure import azure_active_directory
        import adal
        # Get the Azure Automation RunAs service principal certificate
        cert = automationassets.get_automation_certificate("AzureRunAsCertificate")
        pks12_cert = crypto.load_pkcs12(cert)
        pem_pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM,pks12_cert.get_privatekey())
        # Get run as connection information for the Azure Automation service principal
        application_id = runas_connection["ApplicationId"]
        thumbprint = runas_connection["CertificateThumbprint"]
        tenant_id = runas_connection["TenantId"]
        # Authenticate with service principal certificate
        resource ="https://management.core.chinacloudapi.cn/"
        authority_url = ("https://login.partner.microsoftonline.cn/"+tenant_id)
        context = adal.AuthenticationContext(authority_url)
        return azure_active_directory.AdalAuthentication(
        lambda: context.acquire_token_with_client_certificate(
    # Authenticate to Azure using the Azure Automation RunAs service principal
    runas_connection = automationassets.get_automation_connection("AzureRunAsConnection")
    azure_credential = get_automation_runas_credential(runas_connection)

添加代码以创建 Python Compute 客户端并启动 VMAdd code to create Python Compute client and start the VM

若要使用 Azure VM,请创建 Python 的 Azure Compute 客户端实例。To work with Azure VMs, create an instance of the Azure Compute client for Python.

使用此计算客户端启动 VM。Use the compute client to start the VM. 将以下代码添加到 Runbook:Add the following code to the runbook:

# Initialize the compute management client with the RunAs credential and specify the subscription to work against.
compute_client = ComputeManagementClient(

print('\nStart VM')
async_vm_start = compute_client.virtual_machines.start(
    "MyResourceGroup", "TestVM")

其中 MyResourceGroup 是包含 VM 的资源组的名称,TestVM 是要启动的 VM 的名称。Where MyResourceGroup is the name of the resource group that contains the VM, and TestVM is the name of the VM that you want to start.

再次测试并运行 Runbook,以便看到它启动 VM。Test and run the runbook again to see that it starts the VM.

使用输入参数Use input parameters

对于资源组名称和 VM 名称,Runbook 当前使用硬编码的值。The runbook currently uses hard-coded values for the names of the resource group and the VM. 现在我们来添加用于从输入参数获取这些值的代码。Now let's add code that gets these values from input parameters.

使用 sys.argv 变量获取参数值。You use the sys.argv variable to get the parameter values. 将以下代码添加到 Runbook,使其紧随其他 import 语句之后:Add the following code to the runbook immediately after the other import statements:

import sys

resource_group_name = str(sys.argv[1])
vm_name = str(sys.argv[2])

它将导入 sys 模块,并创建两个变量以用于保存资源组名称和 VM 名称。This imports the sys module, and creates two variables to hold the Resource Group and VM names. 请注意,参数列表的元素 sys.argv[0] 是脚本的名称,不是用户的输入。Notice that the element of the argument list, sys.argv[0], is the name of the script, and is not input by the user.

现在可以修改 Runbook 的最后两行,以使用输入参数值,而不使用硬编码的值:Now you can modify the last two lines of the runbook to use the input parameter values instead of using hard-coded values:

async_vm_start = compute_client.virtual_machines.start(
    resource_group_name, vm_name)

启动 Python Runbook 时(无论是在“测试”窗格中启动,还是将其作为已发布的 Runbook 启动),可以在“启动 Runbook”页的“参数”下输入参数的值。When you start a Python runbook (either on the Test pane or as a published runbook), you can enter the values for parameters in the Start Runbook page under Parameters.

开始在第一个框中输入值时,会出现第二个框,依此类推,这样就可以根据需要输入任意数量的参数值。After you start entering a value in the first box, a second appears, and so on, so that you can enter as many parameter values as necessary.

这些值可在 sys.argv 数组中供脚本使用,就像在你刚才添加的代码中那样。The values are available to the script in the sys.argv array as in the code you just added.

输入资源组的名称作为第一个参数的值,输入 VM 的名称作为第二个参数的值。Enter the name of your resource group as the value for the first parameter, and the name of the VM to start as the value of the second parameter.


单击“确定”启动 Runbook。Click OK to start the runbook. Runbook 运行,并启动指定的 VM。The runbook runs and starts the VM that you specified.

Python 中的错误处理Error Handling in Python

还可以使用以下约定从 Python Runbook 中检索各种流,包括“警告”、“错误”和“调试”流。You can also use the following conventions to retrieve various streams from your Python runbooks, including WARNING, ERROR, and DEBUG streams.

print("Hello World output")
print("ERROR: - Hello world error")
print("WARNING: - Hello world warning")
print("DEBUG: - Hello world debug")
print("VERBOSE: - Hello world verbose")

以下示例显示了在 try...except 块中使用的此约定。The following example shows this convention used in a try...except block.

    raise Exception('one', 'two')
except Exception as detail:
    print 'ERROR: Handling run-time error:', detail


Azure 自动化不支持 sys.stderrAzure Automation does not support sys.stderr.

后续步骤Next steps