使用 PowerShell 设置 VMware VM 到 Azure 的灾难恢复Set up disaster recovery of VMware VMs to Azure with PowerShell

本文介绍如何使用 Azure PowerShell 将 VMware 虚拟机复制和故障转移到 AzureIn this article, you see how to replicate and failover VMware virtual machines to Azure using Azure PowerShell.

学习如何:You learn how to:

  • 创建恢复服务保管库并设置保管库上下文。Create a Recovery Services vault and set the vault context.
  • 在保管库中验证服务器注册。Validate server registration in the vault.
  • 设置复制,包括复制策略。Set up replication, including a replication policy. 添加 vCenter Server,并发现 VM。Add your vCenter server and discover VMs.
  • 添加 vCenter Server 并发现Add a vCenter server and discover
  • 创建存储帐户以保存复制日志或数据,并复制 VM。Create storage accounts to hold replication logs or data, and replicate the VMs.
  • 执行故障转移。Perform a failover. 配置故障转移设置,执行复制虚拟机的设置。Configure failover settings, perform a settings for replicating virtual machines.

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

必备条件Prerequisites

开始之前:Before you start:

登录到 AzureLog into Azure

使用 Connect-AzAccount cmdlet 登录到 Azure 订阅:Log into your Azure subscription using the Connect-AzAccount cmdlet:

Connect-AzAccount -Environment AzureChinaCloud

选择要将 VMware 虚拟机复制到的 Azure 订阅。Select the Azure subscription you want to replicate your VMware virtual machines to. 使用 Get-AzSubscription cmdlet 获取你有权访问的 Azure 订阅的列表。Use the Get-AzSubscription cmdlet to get the list of Azure subscriptions you have access to. 使用 Select-AzSubscription cmdlet 选择要使用的 Azure 订阅。Select the Azure subscription to work with using the Select-AzSubscription cmdlet.

Select-AzSubscription -SubscriptionName "ASR Test Subscription"

设置恢复服务保管库Set up a Recovery Services vault

  1. 创建要在其中创建恢复服务保管库的资源组。Create a resource group in which to create the Recovery Services vault. 在以下示例中,资源组名为 VMwareDRtoAzurePS,它是在中国东部区域创建的。In the example below, the resource group is named VMwareDRtoAzurePS and is created in the China East region.

    New-AzResourceGroup -Name "VMwareDRtoAzurePS" -Location "China East"
    
    ResourceGroupName : VMwareDRtoAzurePS
    Location          : chinaeast
    ProvisioningState : Succeeded
    Tags              :
    ResourceId        : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/VMwareDRtoAzurePS
    
  2. 创建恢复服务保管库。Create a Recovery services vault. 在以下示例中,恢复服务保管库名为 VMwareDRToAzurePs,它是在中国东部区域创建的,并位于上一步骤创建的资源组中。In the example below, the Recovery services vault is named VMwareDRToAzurePs, and is created in the China East region and in the resource group created in the previous step.

    New-AzRecoveryServicesVault -Name "VMwareDRToAzurePs" -Location "China East" -ResourceGroupName "VMwareDRToAzurePs"
    
    Name              : VMwareDRToAzurePs
    ID                : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/VMwareDRToAzurePs/providers/Microsoft.RecoveryServices/vaults/VMwareDRToAzurePs
    Type              : Microsoft.RecoveryServices/vaults
    Location          : chinaeast
    ResourceGroupName : VMwareDRToAzurePs
    SubscriptionId    : xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
    Properties        : Microsoft.Azure.Commands.RecoveryServices.ARSVaultProperties
    
  3. 下载保管库注册密钥。Download the vault registration key for the vault. 保管库注册密钥用于将本地配置服务器注册到此保管库。The vault registration key is used to register the on-premises Configuration Server to this vault. 注册是配置服务器软件安装过程的一部分。Registration is part of the Configuration Server software installation process.

    #Get the vault object by name and resource group and save it to the $vault PowerShell variable 
    $vault = Get-AzRecoveryServicesVault -Name "VMwareDRToAzurePS" -ResourceGroupName "VMwareDRToAzurePS"
    
    #Download vault registration key to the path C:\Work
    Get-AzRecoveryServicesVaultSettingsFile -SiteRecovery -Vault $Vault -Path "C:\Work\"
    
    FilePath
    --------
    C:\Work\VMwareDRToAzurePs_2017-11-23T19-52-34.VaultCredentials
    
  4. 使用下载的保管库注册密钥并遵循下列文章中的步骤,完成配置服务器的安装和注册。Use the downloaded vault registration key and follow the steps in the articles given below to complete installation and registration of the Configuration Server.

设置保管库上下文Set the vault context

使用 Set-ASRVaultContext cmdlet 设置保管库上下文。Set the vault context using the Set-ASRVaultContext cmdlet. 设置后,PowerShell 会话中的后续 Azure Site Recovery 操作将在所选保管库的上下文中执行。Once set, subsequent Azure Site Recovery operations in the PowerShell session are performed in the context of the selected vault.

提示

Azure Site Recovery PowerShell 模块(Az.RecoveryServices 模块)附带了大多数 cmdlet 的易用别名。The Azure Site Recovery PowerShell module (Az.RecoveryServices module) comes with easy to use aliases for most cmdlets. 模块中的 cmdlet 采用 <Operation>-AzRecoveryServicesAsr<Object> 形式,并具有采用 <Operation>-ASR<Object> 形式的等效别名** **。The cmdlets in the module take the form <Operation>-AzRecoveryServicesAsr<Object> and have equivalent aliases that take the form <Operation>-ASR<Object>. 可以替换 cmdlet 别名以便于使用。You can replace the cmdlet aliases for ease of use.

在以下示例中,使用来自 $vault 变量的保管库详细信息指定 PowerShell 会话的保管库上下文。In the example below, the vault details from the $vault variable is used to specify the vault context for the PowerShell session.

```azurepowershell
Set-ASRVaultContext -Vault $vault
```
```
ResourceName      ResourceGroupName ResourceNamespace          ResourceType
------------ ----------------- ----------------- -----------
VMwareDRToAzurePs VMwareDRToAzurePs Microsoft.RecoveryServices vaults
```

除了使用 Set-ASRVaultContext cmdlet 之外,还可以使用 Import-AzRecoveryServicesAsrVaultSettingsFile cmdlet 设置保管库上下文。As an alternative to the Set-ASRVaultContext cmdlet, one can also use the Import-AzRecoveryServicesAsrVaultSettingsFile cmdlet to set the vault context. 将保管库注册密钥文件所在位置的路径指定为 Import-AzRecoveryServicesAsrVaultSettingsFile cmdlet 的路径参数。Specify the path at which the vault registration key file is located as the -path parameter to the Import-AzRecoveryServicesAsrVaultSettingsFile cmdlet. 例如:For example:

```azurepowershell
Get-AzRecoveryServicesVaultSettingsFile -SiteRecovery -Vault $Vault -Path "C:\Work\"
Import-AzRecoveryServicesAsrVaultSettingsFile -Path "C:\Work\VMwareDRToAzurePs_2017-11-23T19-52-34.VaultCredentials"
```

本文的后续部分假定已设置 Azure Site Recovery 操作的保管库上下文。Subsequent sections of this article assume that the vault context for Azure Site Recovery operations has been set.

验证保管库注册Validate vault registration

对于此示例,我们具备以下先决条件:For this example, we have the following:

  • 配置服务器 (ConfigurationServer) 已注册到此保管库。A configuration server (ConfigurationServer) has been registered to this vault.
  • 其他进程服务器 (ScaleOut-ProcessServer) 已注册到 ConfigurationServer An additional process server (ScaleOut-ProcessServer) has been registered to ConfigurationServer
  • 配置服务器上已设置了帐户(vCenter_accountWindowsAccountLinuxAccount)。Accounts (vCenter_account, WindowsAccount, LinuxAccount) have been set up on the Configuration server. 这些帐户用于添加 vCenter Server 以发现虚拟机,以及在要复制的 Windows 和 Linux 服务器上推送安装移动服务软件。These accounts are used to add the vCenter server, to discover virtual machines, and to push-install the mobility service software on Windows and Linux servers that are to be replicated.
  1. 已注册的配置服务器由 Site Recovery 中的结构对象表示。Registered configuration servers are represented by a fabric object in Site Recovery. 获取保管库中结构对象的列表,并标识配置服务器。Get the list of fabric objects in the vault and identify the configuration server.

    # Verify that the Configuration server is successfully registered to the vault
    $ASRFabrics = Get-AzRecoveryServicesAsrFabric
    $ASRFabrics.count
    
    1
    
    #Print details of the Configuration Server
    $ASRFabrics[0]
    
    Name                  : 2c33d710a5ee6af753413e97f01e314fc75938ea4e9ac7bafbf4a31f6804460d
    FriendlyName          : ConfigurationServer
    ID                    : /Subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/VMwareDRToAzurePs/providers/Microsoft.RecoveryServices/vaults/VMwareDRToAzurePs/replicationFabrics
                            /2c33d710a5ee6af753413e97f01e314fc75938ea4e9ac7bafbf4a31f6804460d
    Type                  : Microsoft.RecoveryServices/vaults/replicationFabrics
    FabricType            : VMware
    SiteIdentifier        : ef7a1580-f356-4a00-aa30-7bf80f952510
    FabricSpecificDetails : Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.ASRVMWareSpecificDetails
    
  2. 标识可用于复制计算机的进程服务器。Identify the process servers that can be used to replicate machines.

    $ProcessServers = $ASRFabrics[0].FabricSpecificDetails.ProcessServers
    for($i=0; $i -lt $ProcessServers.count; $i++) {
     "{0,-5} {1}" -f $i, $ProcessServers[$i].FriendlyName
    }
    
    0     ScaleOut-ProcessServer
    1     ConfigurationServer
    

    在以上输出中,$ProcessServers [0] 对应于 ScaleOut ProcessServer****$ProcessServers [1]** 对应于 ConfigurationServer 上的进程服务器角色From the output above $ProcessServers[0] corresponds to ScaleOut-ProcessServer and $ProcessServers[1] corresponds to the Process Server role on ConfigurationServer

  3. 标识在配置服务器设置的帐户。Identify accounts that have been set up on the Configuration Server.

    $AccountHandles = $ASRFabrics[0].FabricSpecificDetails.RunAsAccounts
    #Print the account details
    $AccountHandles
    
    AccountId AccountName
    --------- -----------
    1         vCenter_account
    2         WindowsAccount
    3         LinuxAccount
    

    在以上输出中,$AccountHandles [0] 对应于帐户 vCenter_account$AccountHandles [1] 对应于帐户 WindowsAccount$AccountHandles [2] 对应于帐户 LinuxAccountFrom the output above $AccountHandles[0] corresponds to the account vCenter_account, $AccountHandles[1] to account WindowsAccount, and $AccountHandles[2] to account LinuxAccount

创建复制策略Create a replication policy

在此步骤中,将创建两个复制策略。In this step, two replication policies are created. 一个策略用于将 VMware 虚拟机复制到 Azure,另一个用于将在 Azure 中运行的故障转移虚拟机复制回本地 VMware 站点。One policy to replicate VMware virtual machines to Azure, and the other to replicate failed over virtual machines running in Azure back to the on-premises VMware site.

备注

大多数 Azure Site Recovery 操作异步执行。Most Azure Site Recovery operations are executed asynchronously. 启动操作时,将提交 Azure Site Recovery 作业,并返回跟踪对象的作业。When you initiate an operation, an Azure Site Recovery job is submitted and a job tracking object is returned. 此作业跟踪对象可以用于监视操作的状态。This job tracking object can be used to monitor the status of the operation.

  1. 创建名为 ReplicationPolicy 的复制策略,使用的指定属性将 VMware 虚拟机复制到 Azure。Create a replication policy named ReplicationPolicy to replicate VMware virtual machines to Azure with the specified properties.

    $Job_PolicyCreate = New-AzRecoveryServicesAsrPolicy -VMwareToAzure -Name "ReplicationPolicy" -RecoveryPointRetentionInHours 24 -ApplicationConsistentSnapshotFrequencyInHours 4 -RPOWarningThresholdInMinutes 60
    
    # Track Job status to check for completion
    while (($Job_PolicyCreate.State -eq "InProgress") -or ($Job_PolicyCreate.State -eq "NotStarted")){ 
            sleep 10; 
            $Job_PolicyCreate = Get-ASRJob -Job $Job_PolicyCreate
    }
    
    #Display job status
    $Job_PolicyCreate
    
    Name             : 8d18e2d9-479f-430d-b76b-6bc7eb2d0b3e
    ID               : /Subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/VMwareDRToAzurePs/providers/Microsoft.RecoveryServices/vaults/VMwareDRToAzurePs/replicationJobs/8d18e2d
                       9-479f-430d-b76b-6bc7eb2d0b3e
    Type             :
    JobType          : AddProtectionProfile
    DisplayName      : Create replication policy
    ClientRequestId  : a162b233-55d7-4852-abac-3d595a1faac2 ActivityId: 9895234a-90ea-4c1a-83b5-1f2c6586252a
    State            : Succeeded
    StateDescription : Completed
    StartTime        : 11/24/2017 2:49:24 AM
    EndTime          : 11/24/2017 2:49:23 AM
    TargetObjectId   : ab31026e-4866-5440-969a-8ebcb13a372f
    TargetObjectType : ProtectionProfile
    TargetObjectName : ReplicationPolicy
    AllowedActions   :
    Tasks            : {Prerequisites check for creating the replication policy, Creating the replication policy}
    Errors           : {}
    
  2. 创建用于从 Azure 故障回复到本地 VMware 站点的复制策略。Create a replication policy to use for failback from Azure to the on-premises VMware site.

    $Job_FailbackPolicyCreate = New-AzRecoveryServicesAsrPolicy -AzureToVMware -Name "ReplicationPolicy-Failback" -RecoveryPointRetentionInHours 24 -ApplicationConsistentSnapshotFrequencyInHours 4 -RPOWarningThresholdInMinutes 60
    

    使用 $Job_FailbackPolicyCreate 中的作业详细信息,以跟踪操作直到完成。Use the job details in $Job_FailbackPolicyCreate to track the operation to completion.

    • 创建保护容器映射,以便通过配置服务器映射复制策略。Create a protection container mapping to map replication policies with the Configuration Server.
    #Get the protection container corresponding to the Configuration Server
    $ProtectionContainer = Get-AzRecoveryServicesAsrProtectionContainer -Fabric $ASRFabrics[0]
    
    #Get the replication policies to map by name.
    $ReplicationPolicy = Get-AzRecoveryServicesAsrPolicy -Name "ReplicationPolicy"
    $FailbackReplicationPolicy = Get-AzRecoveryServicesAsrPolicy -Name "ReplicationPolicy-Failback"
    
    # Associate the replication policies to the protection container corresponding to the Configuration Server.
    
    $Job_AssociatePolicy = New-AzRecoveryServicesAsrProtectionContainerMapping -Name "PolicyAssociation1" -PrimaryProtectionContainer $ProtectionContainer -Policy $ReplicationPolicy
    
    # Check the job status
    while (($Job_AssociatePolicy.State -eq "InProgress") -or ($Job_AssociatePolicy.State -eq "NotStarted")){
        sleep 10;
        $Job_AssociatePolicy = Get-ASRJob -Job $Job_AssociatePolicy
    }
    $Job_AssociatePolicy.State
    
    <# In the protection container mapping used for failback (replicating failed over virtual machines
        running in Azure, to the primary VMware site.) the protection container corresponding to the
        Configuration server acts as both the Primary protection container and the recovery protection
        container
    #>
    $Job_AssociateFailbackPolicy = New-AzRecoveryServicesAsrProtectionContainerMapping -Name "FailbackPolicyAssociation" -PrimaryProtectionContainer $ProtectionContainer -RecoveryProtectionContainer $ProtectionContainer -Policy $FailbackReplicationPolicy
    
    # Check the job status
    while (($Job_AssociateFailbackPolicy.State -eq "InProgress") -or ($Job_AssociateFailbackPolicy.State -eq "NotStarted")){
        sleep 10;
        $Job_AssociateFailbackPolicy = Get-ASRJob -Job $Job_AssociateFailbackPolicy
    }
    $Job_AssociateFailbackPolicy.State
    
    

添加 vCenter 服务器,并发现 VMAdd a vCenter server and discover VMs

按 IP 地址或主机名添加 vCenter 服务器。Add a vCenter Server by IP address or hostname. -port 参数指定 vCenter 服务器上要连接到的端口, -Name 参数指定要用于 vCenter 服务器的友好名称, -Account 参数指定配置服务器上用于发现由 vCenter 服务器托管的虚拟机的帐户句柄。The -port parameter specifies the port on the vCenter server to connect to, -Name parameter specifies a friendly name to use for the vCenter server, and the -Account parameter specifies the account handle on the Configuration server to use to discover virtual machines managed by the vCenter server.

# The $AccountHandles[0] variable holds details of vCenter_account

$Job_AddvCenterServer = New-AzRecoveryServicesAsrvCenter -Fabric $ASRFabrics[0] -Name "MyvCenterServer" -IpOrHostName "10.150.24.63" -Account $AccountHandles[0] -Port 443

#Wait for the job to complete and ensure it completed successfully

while (($Job_AddvCenterServer.State -eq "InProgress") -or ($Job_AddvCenterServer.State -eq "NotStarted")) {
        sleep 30;
        $Job_AddvCenterServer = Get-ASRJob -Job $Job_AddvCenterServer
}
$Job_AddvCenterServer
Name             : 0f76f937-f9cf-4e0e-bf27-10c9d1c252a4
ID               : /Subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/VMwareDRToAzurePs/providers/Microsoft.RecoveryServices/vaults/VMwareDRToAzurePs/replicationJobs/0f76f93
                   7-f9cf-4e0e-bf27-10c9d1c252a4
Type             :
JobType          : DiscoverVCenter
DisplayName      : Add vCenter server
ClientRequestId  : a2af8892-5686-4d64-a528-10445bc2f698 ActivityId: 7ec05aad-002e-4da0-991f-95d0de7a9f3a
State            : Succeeded
StateDescription : Completed
StartTime        : 11/24/2017 2:41:47 AM
EndTime          : 11/24/2017 2:44:37 AM
TargetObjectId   : 10.150.24.63
TargetObjectType : VCenter
TargetObjectName : MyvCenterServer
AllowedActions   :
Tasks            : {Adding vCenter server}
Errors           : {}

创建用于复制的存储帐户Create storage accounts for replication

若要写入到托管磁盘,请使用 Powershell Az.RecoveryServices 模块 2.0.0 及更高版本。To write to managed disk, use Powershell Az.RecoveryServices module 2.0.0 onwards. 它只需要创建日志存储帐户。It only requires creation of a log storage account. 建议使用标准帐户类型和 LRS 冗余,因为使用它只是为了存储临时日志。It is recommended to use a standard account type and LRS redundancy since it is used to store only temporary logs. 请务必在保管库所在的同一个 Azure 区域中创建存储帐户。Ensure that the storage account is created in the same Azure region as the vault.

如果使用低于 2.0.0 的 Az.RecoveryServices 模块版本,请按以下步骤创建存储帐户。If you are using a version of Az.RecoveryServices module older than 2.0.0, use the following steps to create storage accounts. 稍后将使用这些存储帐户复制虚拟机。These storage accounts are used later to replicate virtual machines. 确保在保管库所在 Azure 区域创建存储帐户。Ensure that the storage accounts are created in the same Azure region as the vault. 如果计划使用现有存储帐户进行复制,可以跳过此步骤。You can skip this step if you plan to use an existing storage account for replication.

备注

将本地虚拟机复制到高级存储帐户时,需要指定额外的标准存储帐户(日志存储帐户)。While replicating on-premises virtual machines to a premium storage account, you need to specify an additional standard storage account (log storage account). 在高级存储目标上应用日志之前,日志存储帐户将作为中间存储保留复制日志。The log storage account holds replication logs as an intermediate store until the logs can be applied on the premium storage target.


$PremiumStorageAccount = New-AzStorageAccount -ResourceGroupName "VMwareDRToAzurePs" -Name "premiumstorageaccount1" -Location "China East" -SkuName Premium_LRS

$LogStorageAccount = New-AzStorageAccount -ResourceGroupName "VMwareDRToAzurePs" -Name "logstorageaccount1" -Location "China East" -SkuName Standard_LRS

$ReplicationStdStorageAccount= New-AzStorageAccount -ResourceGroupName "VMwareDRToAzurePs" -Name "replicationstdstorageaccount1" -Location "China East" -SkuName Standard_LRS

复制 VMware VMReplicate VMware VMs

从 vCenter 服务器发现虚拟机需要大约 15 到 20 分钟。It takes about 15-20 minutes for virtual machines to be discovered from the vCenter server. 发现后,将为发现的每个虚拟机在 Azure Site Recovery 中 创建一个可保护项对象。Once discovered, a protectable item object is created in Azure Site Recovery for each discovered virtual machine. 在此步骤中,会将发现的三个虚拟机复制到上一步中创建的 Azure 存储帐户。In this step, three of the discovered virtual machines are replicated to the Azure Storage accounts created in the previous step.

需要添加以下详细信息以保护发现的虚拟机:You will need the following details to protect a discovered virtual machine:

  • 要复制的可保护项。The protectable item to be replicated.
  • 要将虚拟机复制到的存储帐户(前提是复制到存储帐户)。The storage account to replicate the virtual machine to (only if you are replicating to storage account).
  • 需要使用日志存储在高级存储帐户或托管磁盘中保护虚拟机。A log storage is needed to protect virtual machines to a premium storage account or to a managed disk.
  • 用于复制的进程服务器。The Process Server to be used for replication. 检索可用进程服务器的列表,并将其保存在 $ProcessServers[0] (ScaleOut-ProcessServer)$ProcessServers[1] (ConfigurationServer) 变量中。The list of available process servers has been retrieved and saved in the $ProcessServers[0] (ScaleOut-ProcessServer) and $ProcessServers[1] (ConfigurationServer) variables.
  • 用于将移动服务软件推送安装到计算机的帐户。The account to use to push-install the Mobility service software onto the machines. 检索可用帐户的列表,并将其存储在 $AccountHandles 变量中。The list of available accounts has been retrieved and stored in the $AccountHandles variable.
  • 要用于复制的复制策略的保护容器映射。The protection container mapping for the replication policy to be used for replication.
  • 故障转移时必须在其中创建虚拟机的资源组。The resource group in which virtual machines must be created on failover.
  • (可选)要将故障转移虚拟机连接到的 Azure 虚拟网络和子网。Optionally, the Azure virtual network and subnet to which the failed over virtual machine should be connected.

现在使用此表中指定的设置复制以下虚拟机Now replicate the following virtual machines using the settings specified in this table

虚拟机Virtual machine 进程服务器Process Server 存储帐户Storage Account 日志存储帐户Log Storage account 策略Policy 用于移动服务安装的帐户Account for Mobility service installation 目标资源组Target resource group 目标虚拟网络Target virtual network 目标子网Target subnet
CentOSVM1CentOSVM1 ConfigurationServerConfigurationServer 空值N/A logstorageaccount1logstorageaccount1 ReplicationPolicyReplicationPolicy LinuxAccountLinuxAccount VMwareDRToAzurePsVMwareDRToAzurePs ASR-vnetASR-vnet Subnet-1Subnet-1
Win2K12VM1Win2K12VM1 ScaleOut-ProcessServerScaleOut-ProcessServer premiumstorageaccount1premiumstorageaccount1 logstorageaccount1logstorageaccount1 ReplicationPolicyReplicationPolicy WindowsAccountWindowsAccount VMwareDRToAzurePsVMwareDRToAzurePs ASR-vnetASR-vnet Subnet-1Subnet-1
CentOSVM2CentOSVM2 ConfigurationServerConfigurationServer replicationstdstorageaccount1replicationstdstorageaccount1 空值N/A ReplicationPolicyReplicationPolicy LinuxAccountLinuxAccount VMwareDRToAzurePsVMwareDRToAzurePs ASR-vnetASR-vnet Subnet-1Subnet-1

#Get the target resource group to be used
$ResourceGroup = Get-AzResourceGroup -Name "VMwareToAzureDrPs"

#Get the target virtual network to be used
$RecoveryVnet = Get-AzVirtualNetwork -Name "ASR-vnet" -ResourceGroupName "asrrg" 

#Get the protection container mapping for replication policy named ReplicationPolicy
$PolicyMap  = Get-AzRecoveryServicesAsrProtectionContainerMapping -ProtectionContainer $ProtectionContainer | where PolicyFriendlyName -eq "ReplicationPolicy"

#Get the protectable item corresponding to the virtual machine CentOSVM1
$VM1 = Get-AzRecoveryServicesAsrProtectableItem -ProtectionContainer $ProtectionContainer -FriendlyName "CentOSVM1"

# Enable replication for virtual machine CentOSVM1 using the Az.RecoveryServices module 2.0.0 onwards to replicate to managed disks
# The name specified for the replicated item needs to be unique within the protection container. Using a random GUID to ensure uniqueness
$Job_EnableReplication1 = New-AzRecoveryServicesAsrReplicationProtectedItem -VMwareToAzure -ProtectableItem $VM1 -Name (New-Guid).Guid -ProtectionContainerMapping $PolicyMap -ProcessServer $ProcessServers[1] -Account $AccountHandles[2] -RecoveryResourceGroupId $ResourceGroup.ResourceId -logStorageAccountId $LogStorageAccount.Id -RecoveryAzureNetworkId $RecoveryVnet.Id -RecoveryAzureSubnetName "Subnet-1"

# Alternatively, if the virtual machine CentOSVM1 has CMK enabled disks, enable replication using Az module 3.3.0 onwards as below
# $diskID is the Disk Encryption Set ID to be used for all replica managed disks and target managed disks in the target region
$Job_EnableReplication1 = New-AzRecoveryServicesAsrReplicationProtectedItem -VMwareToAzure -ProtectableItem $VM1 -Name (New-Guid).Guid -ProtectionContainerMapping $PolicyMap -ProcessServer $ProcessServers[1] -Account $AccountHandles[2] -RecoveryResourceGroupId $ResourceGroup.ResourceId -logStorageAccountId -DiskEncryptionSetId $diskId $LogStorageAccount.Id -RecoveryAzureNetworkId $RecoveryVnet.Id -RecoveryAzureSubnetName "Subnet-1"

#Get the protectable item corresponding to the virtual machine Win2K12VM1
$VM2 = Get-AzRecoveryServicesAsrProtectableItem -ProtectionContainer $ProtectionContainer -FriendlyName "Win2K12VM1"

# Enable replication for virtual machine Win2K12VM1
$Job_EnableReplication2 = New-AzRecoveryServicesAsrReplicationProtectedItem -VMwareToAzure -ProtectableItem $VM2 -Name (New-Guid).Guid -ProtectionContainerMapping $PolicyMap -RecoveryAzureStorageAccountId $PremiumStorageAccount.Id -LogStorageAccountId $LogStorageAccount.Id -ProcessServer $ProcessServers[0] -Account $AccountHandles[1] -RecoveryResourceGroupId $ResourceGroup.ResourceId -RecoveryAzureNetworkId $RecoveryVnet.Id -RecoveryAzureSubnetName "Subnet-1"

#Get the protectable item corresponding to the virtual machine CentOSVM2
$VM3 = Get-AzRecoveryServicesAsrProtectableItem -ProtectionContainer $ProtectionContainer -FriendlyName "CentOSVM2"

# Enable replication for virtual machine CentOSVM2
$Job_EnableReplication3 = New-AzRecoveryServicesAsrReplicationProtectedItem -VMwareToAzure -ProtectableItem $VM3 -Name (New-Guid).Guid -ProtectionContainerMapping $PolicyMap -RecoveryAzureStorageAccountId $ReplicationStdStorageAccount.Id  -ProcessServer $ProcessServers[1] -Account $AccountHandles[2] -RecoveryResourceGroupId $ResourceGroup.ResourceId -RecoveryAzureNetworkId $RecoveryVnet.Id -RecoveryAzureSubnetName "Subnet-1"

启用复制作业成功完成后,将为虚拟机启动初始复制。Once the enable replication job completes successfully, initial replication is started for the virtual machines. 根据要复制的数据量和可用于复制的带宽,初始复制可能花费一段时间。Initial replication may take a while depending on the amount of data to be replicated and the bandwidth available for replication. 初始复制完成后,虚拟机将进入受保护状态。After initial replication completes, the virtual machine moves to a protected state. 虚拟机进入可保护状态后,可为该虚拟机执行测试故障转移、将其添加到恢复计划等。Once the virtual machine reaches a protected state you can perform a test failover for the virtual machine, add it to recovery plans etc.

可使用 Get-ASRReplicationProtectedItem cmdlet 检查虚拟机的复制状态和复制运行状况。You can check the replication state and replication health of the virtual machine with the Get-ASRReplicationProtectedItem cmdlet.

Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $ProtectionContainer | Select FriendlyName, ProtectionState, ReplicationHealth
FriendlyName ProtectionState                 ReplicationHealth
------------ ---------------                 -----------------
CentOSVM1    Protected                       Normal
CentOSVM2    InitialReplicationInProgress    Normal
Win2K12VM1   Protected                       Normal

配置故障转移设置Configure failover settings

可使用 Set-ASRReplicationProtectedItem cmdlet 更新受保护计算机的故障转移设置。Failover settings for protected machines can be updated using the Set-ASRReplicationProtectedItem cmdlet. 可通过此 cmdlet 更新以下设置:Some of the settings that can be updated through this cmdlet are:

  • 要在故障转移时创建的虚拟机的名称Name of the virtual machine to be created on failover
  • 要在故障转移时创建的虚拟机的 VM 大小VM size of the virtual machine to be created on failover
  • 虚拟机的 NIC 在故障转移时应连接到的 Azure 虚拟网络和子网Azure virtual network and subnet that the NICs of the virtual machine should be connected to on failover
  • 故障转移到托管磁盘Failover to managed disks
  • 应用 Azure 混合使用权益Apply Azure Hybrid Use Benefit
  • 分配目标虚拟网络中在故障转移时要分配给虚拟机的静态 IP 地址。Assign a static IP address from the target virtual network to be assigned to the virtual machine on failover.

在此示例中,我们将更新为虚拟机 Win2K12VM1 进行故障转移时要创建的虚拟机的 VM 大小,并指定在故障转移时使用托管磁盘的虚拟机。In this example, we update the VM size of the virtual machine to be created on failover for the virtual machine Win2K12VM1 and specify that the virtual machine use managed disks on failover.

$ReplicatedVM1 = Get-AzRecoveryServicesAsrReplicationProtectedItem -FriendlyName "Win2K12VM1" -ProtectionContainer $ProtectionContainer

Set-AzRecoveryServicesAsrReplicationProtectedItem -InputObject $ReplicatedVM1 -Size "Standard_DS11" -UseManagedDisk True
Name             : cafa459c-44a7-45b0-9de9-3d925b0e7db9
ID               : /Subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/VMwareDRToAzurePs/providers/Microsoft.RecoveryServices/vaults/VMwareDRToAzurePs/replicationJobs/cafa459
                   c-44a7-45b0-9de9-3d925b0e7db9
Type             :
JobType          : UpdateVmProperties
DisplayName      : Update the virtual machine
ClientRequestId  : b0b51b2a-f151-4e9a-a98e-064a5b5131f3 ActivityId: ac2ba316-be7b-4c94-a053-5363f683d38f
State            : InProgress
StateDescription : InProgress
StartTime        : 11/24/2017 2:04:26 PM
EndTime          :
TargetObjectId   : 88bc391e-d091-11e7-9484-000c2955bb50
TargetObjectType : ProtectionEntity
TargetObjectName : Win2K12VM1
AllowedActions   :
Tasks            : {Update the virtual machine properties}
Errors           : {}

运行测试故障转移Run a test failover

  1. 按如下所述运行 DR 演练(测试故障转移):Run a DR drill (test failover) as follows:

    #Test failover of Win2K12VM1 to the test virtual network "V2TestNetwork"
    
    #Get details of the test failover virtual network to be used
    TestFailovervnet = Get-AzVirtualNetwork -Name "V2TestNetwork" -ResourceGroupName "asrrg" 
    
    #Start the test failover operation
    $TFOJob = Start-AzRecoveryServicesAsrTestFailoverJob -ReplicationProtectedItem $ReplicatedVM1 -AzureVMNetworkId $TestFailovervnet.Id -Direction PrimaryToRecovery
    
  2. 测试故障转移作业成功完成后,可以注意到在 Azure 中创建了名称包含后缀“-Test” (在本例中即 Win2K12VM1-Test)的虚拟机。Once the test failover job completes successfully, you will notice that a virtual machine suffixed with "-Test" (Win2K12VM1-Test in this case) to its name is created in Azure.

  3. 现可连接到测试故障转移虚拟机,并验证测试故障转移。You can now connect to the test failed over virtual machine, and validate the test failover.

  4. 使用 Start-ASRTestFailoverCleanupJob cmdlet 清理测试故障转移。Clean up the test failover using the Start-ASRTestFailoverCleanupJob cmdlet. 此操作将删除在测试故障转移过程中创建的虚拟机。This operation deletes the virtual machine created as part of the test failover operation.

    $Job_TFOCleanup = Start-AzRecoveryServicesAsrTestFailoverCleanupJob -ReplicationProtectedItem $ReplicatedVM1
    

故障转移到 AzureFail over to Azure

在此步骤中,我们要将虚拟机 Win2K12VM1 故障转移到特定恢复点。In this step, we fail over the virtual machine Win2K12VM1 to a specific recovery point.

  1. 获取要用于故障转移的可用恢复点的列表:Get a list of available recovery points to use for the failover:

    # Get the list of available recovery points for Win2K12VM1
    $RecoveryPoints = Get-AzRecoveryServicesAsrRecoveryPoint -ReplicationProtectedItem $ReplicatedVM1
    "{0} {1}" -f $RecoveryPoints[0].RecoveryPointType, $RecoveryPoints[0].RecoveryPointTime
    
    CrashConsistent 11/24/2017 5:28:25 PM
    
    
    #Start the failover job
    $Job_Failover = Start-AzRecoveryServicesAsrUnplannedFailoverJob -ReplicationProtectedItem $ReplicatedVM1 -Direction PrimaryToRecovery -RecoveryPoint $RecoveryPoints[0]
    do {
        $Job_Failover = Get-ASRJob -Job $Job_Failover;
        sleep 60;
    } while (($Job_Failover.State -eq "InProgress") -or ($JobFailover.State -eq "NotStarted"))
    $Job_Failover.State
    
    Succeeded
    
  2. 故障转移成功后,可提交故障转移操作并设置从 Azure 到本地 VMware 站点的反向复制。Once failed over successfully, you can commit the failover operation, and set up reverse replication from Azure back to the on-premises VMware site.

后续步骤Next steps

了解如何使用 Azure Site Recovery PowerShell 参考自动执行更多任务。Learn how to automate more tasks using the Azure Site Recovery PowerShell reference.