将 Azure 自动化 Runbook 添加到恢复计划Add Azure Automation runbooks to recovery plans

本文将介绍 Azure Site Recovery 如何与 Azure 自动化集成,以便扩展恢复计划。In this article, we describe how Azure Site Recovery integrates with Azure Automation to help you extend your recovery plans. 恢复计划可以安排恢复受 Site Recovery 保护的 VM。Recovery plans can orchestrate recovery of VMs that are protected with Site Recovery. 恢复计划支持复制到辅助云和复制到 Azure。Recovery plans work both for replication to a secondary cloud, and for replication to Azure. 恢复计划还有助于实现恢复的一致准确性可重复性自动化Recovery plans also help make the recovery consistently accurate, repeatable, and automated. 如果从 VM 故障转移到 Azure,与 Azure 自动化集成可以扩展恢复计划。If you fail over your VMs to Azure, integration with Azure Automation extends your recovery plans. 可用于执行 Runbook,从而提供功能强大的自动化任务。You can use it to execute runbooks, which offer powerful automation tasks.

如果刚开始接触 Azure 自动化,可以注册并下载示例脚本。If you are new to Azure Automation, you can sign up and download sample scripts. 有关详细信息,以及若要了解如何使用恢复计划来安排恢复到 Azure,请参阅 Azure Site RecoveryFor more information, and to learn how to orchestrate recovery to Azure by using recovery plans, see Azure Site Recovery.

本文介绍如何将 Azure 自动化 Runbook 集成到恢复计划中。In this article, we describe how you can integrate Azure Automation runbooks into your recovery plans. 我们使用示例,自动执行以前需要手动干预的基本任务。We use examples to automate basic tasks that previously required manual intervention. 本文还介绍如何将多步骤恢复过程转换为一键式恢复操作。We also describe how to convert a multi-step recovery to a single-click recovery action.

自定义恢复计划Customize the recovery plan

  1. 转到“Site Recovery” 恢复计划资源边栏选项卡。Go to the Site Recovery recovery plan resource blade. 对于此示例,恢复计划包含两个要恢复的 VM。For this example, the recovery plan has two VMs added to it, for recovery. 若要开始添加 Runbook,请单击“自定义” 选项卡。To begin adding a runbook, click the Customize tab.

    单击“自定义”按钮

  2. 右键单击“组 1: 启动”,再选择“添加后操作” 。Right-click Group 1: Start, and then select Add post action.

    右键单击“组 1: 启动”并添加后操作

  3. 单击“选择脚本” 。Click Choose a script.

  4. 在“更新操作” 边栏选项卡中,将脚本命名为“Hello World” 。On the Update action blade, name the script Hello World.

    “更新操作”边栏选项卡

  5. 输入自动化帐户名称。Enter an Automation account name.

    备注

    自动化帐户可位于任意 Azure 区域。The Automation account can be in any Azure region. 自动化帐户必须位于 Azure Site Recovery 保管库所在的订阅中。The Automation account must be in the same subscription as the Azure Site Recovery vault.

  6. 在自动化帐户中,选择一个 Runbook。In your Automation account, select a runbook. 此 Runbook 是在恢复第一组后执行恢复计划期间运行的脚本。This runbook is the script that runs during the execution of the recovery plan, after the recovery of the first group.

  7. 选择“确定” ,保存脚本。To save the script, click OK. 此时,脚本将添加到“组 1: 后步骤”。The script is added to Group 1: Post-steps.

    “组 1: 启动”后操作

添加脚本时的注意事项Considerations for adding a script

  • 若要删除步骤更新脚本,请右键单击脚本。For options to delete a step or update the script, right-click the script.

  • 从本地计算机故障转移到 Azure 期间,可以在 Azure 上运行脚本。A script can run on Azure during failover from an on-premises machine to Azure. 从 Azure 故障回复到本地计算机期间,它还可以在关闭前,在 Azure 上作为主站点脚本运行。It also can run on Azure as a primary-site script before shutdown, during failback from Azure to an on-premises machine.

  • 脚本在运行时,会注入恢复计划上下文。When a script runs, it injects a recovery plan context. 下面的示例展示了上下文变量:The following example shows a context variable:

    {"RecoveryPlanName":"hrweb-recovery",
    
    "FailoverType":"Test",
    
    "FailoverDirection":"PrimaryToSecondary",
    
    "GroupId":"1",
    
    "VmMap":{"7a1069c6-c1d6-49c5-8c5d-33bfce8dd183":
    
            { "SubscriptionId":"7a1111111-c1d6-49c5-8c5d-111ce8dd183",
    
            "ResourceGroupName":"ContosoRG",
    
            "CloudServiceName":"pod02hrweb-Shanghai-test",
    
            "RoleName":"Fabrikam-Hrweb-frontend-test",
    
            "RecoveryPointId":"TimeStamp"}
    
            }
    
    }
    

    下表列出了上下文中每个变量的名称和说明。The following table lists the name and description of each variable in the context.

    变量名称Variable name 说明Description
    RecoveryPlanNameRecoveryPlanName 正在运行的计划的名称。The name of the plan being run. 此变量有助于用户根据恢复计划名称执行不同的操作。This variable helps you take different actions based on the recovery plan name. 还可以重用脚本。You also can reuse the script.
    FailoverTypeFailoverType 指定故障转移是测试、计划内还是计划外。Specifies whether the failover is a test, planned, or unplanned.
    FailoverDirectionFailoverDirection 指定是恢复到主站点,还是恢复到辅助站点。Specifies whether recovery is to a primary or secondary site.
    GroupIDGroupID 计划运行时,在恢复计划内标识组编号。Identifies the group number in the recovery plan when the plan is running.
    VmMapVmMap 组中所有 VM 的数组。An array of all VMs in the group.
    VMMap 键VMMap key 每个 VM 的唯一键 (GUID)。A unique key (GUID) for each VM. 与 VM 的 Azure Virtual Machine Manager (VMM) ID(若有)相同。It's the same as the Azure Virtual Machine Manager (VMM) ID of the VM, where applicable.
    SubscriptionIdSubscriptionId 其中创建了 VM 的 Azure 订阅的 ID。The Azure subscription ID in which the VM was created.
    RoleNameRoleName 正在恢复的 Azure VM 的名称。The name of the Azure VM that's being recovered.
    CloudServiceNameCloudServiceName 以其名义创建了 VM 的 Azure 云服务名称。The Azure cloud service name under which the VM was created.
    ResourceGroupNameResourceGroupName 以其名义创建了 VM 的 Azure 资源组名称。The Azure resource group name under which the VM was created.
    RecoveryPointIdRecoveryPointId VM 的恢复时间戳。The timestamp for when the VM is recovered.
  • 确保自动化帐户包含以下模块:Ensure that the Automation account has the following modules:

    • AzureRM.profileAzureRM.profile
    • AzureRM.ResourcesAzureRM.Resources
    • AzureRM.AutomationAzureRM.Automation
    • AzureRM.NetworkAzureRM.Network
    • AzureRM.ComputeAzureRM.Compute

所有模块的版本都应兼容。All modules should be of compatible versions. 若要确保所有模块都兼容,只需使用所有模块的最新版本即可。An easy way to ensure that all modules are compatible is to use the latest versions of all the modules.

循环访问 VMMap 中的所有 VMAccess all VMs of the VMMap in a loop

运行以下代码,循环访问 Microsoft VMMap 中的所有 VM:Use the following code to loop across all VMs of the Microsoft VMMap:

$VMinfo = $RecoveryPlanContext.VmMap | Get-Member | Where-Object MemberType -EQ NoteProperty | select -ExpandProperty Name
$vmMap = $RecoveryPlanContext.VmMap
 foreach($VMID in $VMinfo)
 {
     $VM = $vmMap.$VMID                
     if( !(($VM -eq $Null) -Or ($VM.ResourceGroupName -eq $Null) -Or ($VM.RoleName -eq $Null))) {
         #this check is to ensure that we skip when some data is not available else it will fail
         Write-output "Resource group name ", $VM.ResourceGroupName
         Write-output "Rolename " = $VM.RoleName
     }
 }

备注

如果脚本是用于启动组的前操作,那么资源组名称和角色名称值为空。The resource group name and role name values are empty when the script is a pre-action to a boot group. 只有当此组的 VM 成功进行故障转移后,才会填充这些值。The values are populated only if the VM of that group succeeds in failover. 脚本是用于启动组的后操作。The script is a post-action of the boot group.

在多个恢复计划中使用相同的自动化 RunbookUse the same Automation runbook in multiple recovery plans

可以使用外部变量,在多个恢复计划中使用同一个脚本。You can use a single script in multiple recovery plans by using external variables. 可以使用 Azure 自动化变量,存储可在执行恢复计划时传递的参数。You can use Azure Automation variables to store parameters that you can pass for a recovery plan execution. 通过将恢复计划名称作为前缀添加到变量,可以为每个恢复计划单独创建变量。By adding the recovery plan name as a prefix to the variable, you can create individual variables for each recovery plan. 然后,将变量用作参数。Then, use the variables as parameters. 可以在不更改脚本的情况下更改参数,但仍会改变脚本的工作方式。You can change a parameter without changing the script, but still change the way the script works.

在 Runbook 脚本中使用简单字符串变量Use a simple string variable in a runbook script

在以下示例中,脚本使用网络安全组 (NSG) 的输入,并将其应用于恢复计划的 VM。In this example, a script takes the input of a Network Security Group (NSG) and applies it to the VMs of a recovery plan.

为了让脚本能够检测出正在运行的恢复计划,可以使用恢复计划上下文:For the script to detect which recovery plan is running, use the recovery plan context:

workflow AddPublicIPAndNSG {
    param (
          [parameter(Mandatory=$false)]
          [Object]$RecoveryPlanContext
    )

    $RPName = $RecoveryPlanContext.RecoveryPlanName

若要应用现有 NSG,必须知道 NSG 名称和 NSG 资源组名称。To apply an existing NSG, you must know the NSG name and the NSG resource group name. 将这些变量用作恢复计划脚本的输入。Use these variables as inputs for recovery plan scripts. 为此,请在自动化帐户资产中创建两个变量。To do this, create two variables in the Automation account assets. 添加要为其创建参数的恢复计划的名称,作为变量名称的前缀。Add the name of the recovery plan that you are creating the parameters for as a prefix to the variable name.

  1. 创建一个用于存储 NSG 名称的变量。Create a variable to store the NSG name. 使用恢复计划的名称,将前缀添加到变量名称中。Add a prefix to the variable name by using the name of the recovery plan.

    创建 NSG 名称变量

  2. 创建用于存储 NSG 资源组名称的变量。Create a variable to store the NSG's resource group name. 使用恢复计划的名称,将前缀添加到变量名称中。Add a prefix to the variable name by using the name of the recovery plan.

    创建 NSG 资源组名称

  3. 在脚本中,使用以下参考代码获取变量值:In the script, use the following reference code to get the variable values:

    $NSGValue = $RecoveryPlanContext.RecoveryPlanName + "-NSG"
    $NSGRGValue = $RecoveryPlanContext.RecoveryPlanName + "-NSGRG"
    
    $NSGnameVar = Get-AutomationVariable -Name $NSGValue
    $RGnameVar = Get-AutomationVariable -Name $NSGRGValue
    
  4. 在 Runbook 中使用这些变量,将 NSG 应用到已故障转移的 VM 的网络接口:Use the variables in the runbook to apply the NSG to the network interface of the failed-over VM:

     InlineScript {
     if (($Using:NSGname -ne $Null) -And ($Using:NSGRGname -ne $Null)) {
            $NSG = Get-AzureRmNetworkSecurityGroup -Name $Using:NSGname -ResourceGroupName $Using:NSGRGname
            Write-output $NSG.Id
            #Apply the NSG to a network interface
            #$vnet = Get-AzureRmVirtualNetwork -ResourceGroupName TestRG -Name TestVNet
            #Set-AzureRmVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name FrontEnd `
            #  -AddressPrefix 192.168.1.0/24 -NetworkSecurityGroup $NSG
        }
    }
    

对于每个恢复计划,请创建独立变量,以便能够重用脚本。For each recovery plan, create independent variables so that you can reuse the script. 使用恢复计划名称添加前缀。Add a prefix by using the recovery plan name. 有关此方案的端到端完整脚本,请参阅在 Site Recovery 恢复计划的测试故障转移期间向 VM 添加公共 IP 和 NSGFor a complete, end-to-end script for this scenario, see Add a public IP and NSG to VMs during test failover of a Site Recovery recovery plan.

使用复杂变量存储更多信息Use a complex variable to store more information

假设情况为,需要使用一个脚本在特定 VM 上启用公共 IP。Consider a scenario in which you want a single script to turn on a public IP on specific VMs. 在另一种情况下,需要在不同的 VM 上(而不是在所有 VM 上)应用其他 NSG。In another scenario, you might want to apply different NSGs on different VMs (not on all VMs). 可以创建可对任何恢复计划重用的脚本。You can make a script that is reusable for any recovery plan. 每个恢复计划包含的 VM 数量不定。Each recovery plan can have a variable number of VMs. 例如,SharePoint 恢复有两个前端。For example, a SharePoint recovery has two front ends. 基本业务线 (LOB) 应用程序只有一个前端。A basic line-of-business (LOB) application has only one front end. 无法为每个恢复计划单独创建变量。You cannot create separate variables for each recovery plan.

在下面的示例中,我们采用一种新方法,在 Azure 自动化帐户资产中创建复杂变量In the following example, we use a new technique and create a complex variable in the Azure Automation account assets. 为此,可以指定多个值。You do this by specifying multiple values. 必须使用 Azure PowerShell 完成以下步骤:You must use Azure PowerShell to complete the following steps:

  1. 在 PowerShell 中,登录 Azure 订阅:In PowerShell, sign in to your Azure subscription:

    Connect-AzureRmAccount -Environment AzureChinaCloud
    $sub = Get-AzureRmSubscription -Name <SubscriptionName>
    $sub | Select-AzureRmSubscription
    
  2. 若要存储参数,请使用恢复计划名称创建复杂变量:To store the parameters, create the complex variable by using the name of the recovery plan:

    $VMDetails = @{"VMGUID"=@{"ResourceGroupName"="RGNameOfNSG";"NSGName"="NameOfNSG"};"VMGUID2"=@{"ResourceGroupName"="RGNameOfNSG";"NSGName"="NameOfNSG"}}
    New-AzureRmAutomationVariable -ResourceGroupName <RG of Automation Account> -AutomationAccountName <AA Name> -Name <RecoveryPlanName> -Value $VMDetails -Encrypted $false
    
  3. 在此复杂变量中,VMDetails 是受保护 VM 的 VM ID。In this complex variable, VMDetails is the VM ID for the protected VM. 若要获取 VM ID,请在 Azure 门户中查看 VM 属性。To get the VM ID, in the Azure portal, view the VM properties. 下面的屏幕截图展示了一个存储两个 VM 详细信息的变量:The following screenshot shows a variable that stores the details of two VMs:

    将 VM ID 用作 GUID

  4. 在 Runbook 中使用此变量。Use this variable in your runbook. 如果在恢复计划上下文中找到了指定的 VM GUID,请在 VM 上应用 NSG:If the indicated VM GUID is found in the recovery plan context, apply the NSG on the VM:

    $VMDetailsObj = Get-AutomationVariable -Name $RecoveryPlanContext.RecoveryPlanName
    
  5. 在 Runbook 中,循环访问恢复计划上下文的 VM。In your runbook, loop through the VMs of the recovery plan context. 检查 $VMDetailsObj 中是否有 VM。Check whether the VM exists in $VMDetailsObj. 如果有,请访问变量属性,以应用 NSG:If it exists, access the properties of the variable to apply the NSG:

    $VMinfo = $RecoveryPlanContext.VmMap | Get-Member | Where-Object MemberType -EQ NoteProperty | select -ExpandProperty Name
    $vmMap = $RecoveryPlanContext.VmMap
    
    foreach($VMID in $VMinfo) {
        Write-output $VMDetailsObj.value.$VMID
    
        if ($VMDetailsObj.value.$VMID -ne $Null) { #If the VM exists in the context, this will not b Null
            $VM = $vmMap.$VMID
            # Access the properties of the variable
            $NSGname = $VMDetailsObj.value.$VMID.'NSGName'
            $NSGRGname = $VMDetailsObj.value.$VMID.'NSGResourceGroupName'
    
            # Add code to apply the NSG properties to the VM
        }
    }
    

可以对不同的恢复计划使用同一脚本。You can use the same script for different recovery plans. 通过存储不同变量中与恢复计划对应的值,输入不同的参数。Enter different parameters by storing the value that corresponds to a recovery plan in different variables.

示例脚本Sample scripts

单击“部署到 Azure” 按钮,将示例脚本部署到自动化帐户。To deploy sample scripts to your Automation account, click the Deploy to Azure button.

备注

必须修改从 GitHub 存储库“azure-quickstart-templates”下载或参考的模板,以适应 Azure 中国云环境。Templates you downloaded or referenced from the GitHub Repo "azure-quickstart-templates" must be modified in order to fit in the Azure China Cloud Environment. 例如,替换某些终结点(将“blob.core.windows.net”替换为“blob.core.chinacloudapi.cn”,将“cloudapp.azure.com”替换为“cloudapp.chinacloudapi.cn”);必要时更改某些不受支持的位置、VM 映像、VM 大小、SKU 以及资源提供程序的 API 版本。For example, replace some endpoints -- "blob.core.windows.net" by "blob.core.chinacloudapi.cn", "cloudapp.azure.com" by "cloudapp.chinacloudapi.cn"; change some unsupported Location, VM images, VM sizes, SKU and resource-provider's API Version when necessary.

在本文中,选择 Azure 门户中的“编辑模板” ,并将 allowedValues 列表替换为 automationRegion 属性中的以下参数。In this article, select Edit Template in Azure portal and replace the allowedValues list with following parameters in automationRegion properties. [ChinaEast, ChinaEast2, ChinaNorth2]

“部署到 Azure”Deploy to Azure

其他资源Additional resources

后续步骤Next steps

详细了解如何运行故障转移。Learn more about running failovers.