使用 Azure PowerShell 为 Azure 虚拟机设置灾难恢复Set up disaster recovery for Azure virtual machines using Azure PowerShell

本文介绍了如何使用 Azure PowerShell 来设置和测试 Azure 虚拟机的灾难恢复。In this article, you see how to set up and test disaster recovery for Azure virtual machines using Azure PowerShell.

学习如何:You learn how to:

  • 创建恢复服务保管库。Create a Recovery Services vault.
  • 设置 PowerShell 会话的保管库上下文。Set the vault context for the PowerShell session.
  • 准备保管库以开始复制 Azure 虚拟机。Prepare the vault to start replicating Azure virtual machines.
  • 创建网络映射。Create network mappings.
  • 创建要将虚拟机复制到的存储帐户。Create storage accounts to replicate virtual machines to.
  • 将 Azure 虚拟机复制到恢复区域以实现灾难恢复。Replicate Azure virtual machines to a recovery region for disaster recovery.
  • 执行测试故障转移,进行验证,然后清理测试故障转移。Perform a test failover, validate, and cleanup test failover.
  • 故障转移到恢复区域。Fail over to the recovery region.

备注

并非所有可以通过门户使用的方案功能都能通过 Azure PowerShell 使用。Not all scenario capabilities available through the portal may be available through Azure PowerShell. 目前不支持通过 Azure PowerShell 使用的部分方案功能包括:Some of the scenario capabilities not currently supported through Azure PowerShell are:

  • 在无需显式指定虚拟机每个磁盘的情况下指定要复制虚拟机中所有磁盘的功能。The ability to specify that all disks in a virtual machine should be replicated without having to explicitly specify each disk of the virtual machine.

备注

本文已经过更新,以便使用 Azure Az PowerShell 模块。This article has been updated to use the Azure Az PowerShell module. 若要与 Azure 交互,建议使用的 PowerShell 模块是 Az PowerShell 模块。The Az PowerShell module is the recommended PowerShell module for interacting with Azure. 若要开始使用 Az PowerShell 模块,请参阅安装 Azure PowerShellTo get started with the Az PowerShell module, see Install Azure PowerShell. 若要了解如何迁移到 Az PowerShell 模块,请参阅 将 Azure PowerShell 从 AzureRM 迁移到 AzTo learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.

必备条件Prerequisites

开始之前:Before you start:

登录到 Azure 订阅Sign in to your Azure subscription

使用 Connect-AzAccount -Environment AzureChinaCloud cmdlet 登录到你的 Azure 订阅。Sign in to your Azure subscription with the Connect-AzAccount -Environment AzureChinaCloud cmdlet.

Connect-AzAccount -Environment AzureChinaCloud

选择 Azure 订阅。Select your Azure subscription. 使用 Get-AzSubscription cmdlet 获取你有权访问的 Azure 订阅的列表。Use the Get-AzSubscription cmdlet to get the list of Azure subscriptions you have access to. 使用 Set-AzContext cmdlet 选择要使用的 Azure 订阅。Select the Azure subscription to work with using the Set-AzContext cmdlet.

Set-AzContext -SubscriptionId "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

获取要复制的虚拟机的详细信息Get details of the virtual machine to be replicated

在本文中,会将“中国东部”区域中的某个虚拟机复制到“中国北部”区域并在其中进行恢复。In this article, a virtual machine in the China East region is replicated to and recovered in the China North region. 要复制的虚拟机具有 OS 磁盘和单个数据磁盘。The virtual machine being replicated has an OS disk and a single data disk. 本示例中使用的虚拟机名称为 AzureDemoVMThe name of the virtual machine used in the example is AzureDemoVM.

# Get details of the virtual machine
$VM = Get-AzVM -ResourceGroupName "A2AdemoRG" -Name "AzureDemoVM"

Write-Output $VM
ResourceGroupName  : A2AdemoRG
Id                 : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/A2AdemoRG/providers/Microsoft.Compute/virtualMachines/AzureDemoVM
VmId               : 1b864902-c7ea-499a-ad0f-65da2930b81b
Name               : AzureDemoVM
Type               : Microsoft.Compute/virtualMachines
Location           : chinaeast
Tags               : {}
DiagnosticsProfile : {BootDiagnostics}
HardwareProfile    : {VmSize}
NetworkProfile     : {NetworkInterfaces}
OSProfile          : {ComputerName, AdminUsername, WindowsConfiguration, Secrets}
ProvisioningState  : Succeeded
StorageProfile     : {ImageReference, OsDisk, DataDisks}

获取虚拟机磁盘的磁盘详细信息。Get disk details for the virtual machine's disks. 稍后在开始复制虚拟机时,将使用磁盘详细信息。Disk details will be used later when starting replication for the virtual machine.

$OSDiskVhdURI = $VM.StorageProfile.OsDisk.Vhd
$DataDisk1VhdURI = $VM.StorageProfile.DataDisks[0].Vhd

创建恢复服务保管库Create a Recovery Services vault

创建要在其中创建恢复服务保管库的资源组。Create a resource group in which to create the Recovery Services vault.

重要

  • 恢复服务保管库和要保护的虚拟机必须位于不同的 Azure 位置。The Recovery services vault and the virtual machines being protected, must be in different Azure locations.
  • 恢复服务保管库的资源组和要保护的虚拟机必须位于不同的 Azure 位置。The resource group of the Recovery services vault, and the virtual machines being protected, must be in different Azure locations.
  • 恢复服务保管库及其所属的资源组可以位于相同的 Azure 位置。The Recovery services vault, and the resource group to which it belongs, can be in the same Azure location.

在本文的示例中,要保护的虚拟机位于“中国东部”区域。In the example in this article, the virtual machine being protected is in the China East region. 为灾难恢复选择的恢复区域为“中国北部”区域。The recovery region selected for disaster recovery is the China North region. 恢复服务保管库及其资源组都位于恢复区域(中国北部)。The recovery services vault, and the resource group of the vault, are both in the recovery region, China North.

#Create a resource group for the recovery services vault in the recovery Azure region
New-AzResourceGroup -Name "a2ademorecoveryrg" -Location "China North"
ResourceGroupName : a2ademorecoveryrg
Location          : chinanorth
ProvisioningState : Succeeded
Tags              :
ResourceId        : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/a2ademorecoveryrg

创建恢复服务保管库。Create a Recovery services vault. 在本示例中,将在“中国北部”区域中创建名为 a2aDemoRecoveryVault 的恢复服务保管库。In this example, a Recovery Services vault named a2aDemoRecoveryVault is created in the China North region.

#Create a new Recovery services vault in the recovery region
$vault = New-AzRecoveryServicesVault -Name "a2aDemoRecoveryVault" -ResourceGroupName "a2ademorecoveryrg" -Location "China North"

Write-Output $vault
Name              : a2aDemoRecoveryVault
ID                : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/a2ademorecoveryrg/providers/Microsoft.RecoveryServices/vaults/a2aDemoRecoveryVault
Type              : Microsoft.RecoveryServices/vaults
Location          : chinanorth
ResourceGroupName : a2ademorecoveryrg
SubscriptionId    : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Properties        : Microsoft.Azure.Commands.RecoveryServices.ARSVaultProperties

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

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

#Setting the vault context.
Set-AzRecoveryServicesAsrVaultContext -Vault $vault
ResourceName         ResourceGroupName ResourceNamespace          ResourceType
------------         ----------------- -----------------          -----------
a2aDemoRecoveryVault a2ademorecoveryrg Microsoft.RecoveryServices Vaults     
#Delete the downloaded vault settings file
Remove-Item -Path $Vaultsettingsfile.FilePath

对于 Azure 到 Azure 迁移,可以将保管库上下文设置为新创建的保管库:For an Azure-to-Azure migration, you can set the vault context to the newly created vault:

#Set the vault context for the PowerShell session.
Set-AzRecoveryServicesAsrVaultContext -Vault $vault

准备保管库以开始复制 Azure 虚拟机Prepare the vault to start replicating Azure virtual machines

创建用于表示主要(源)区域的 Site Recovery 结构对象Create a Site Recovery fabric object to represent the primary (source) region

保管库中的结构对象表示 Azure 区域。The fabric object in the vault represents an Azure region. 创建主要结构对象,以表示要在保管库中保护的虚拟机所属的 Azure 区域。The primary fabric object is created to represent the Azure region that virtual machines being protected to the vault belong to. 在本文的示例中,要保护的虚拟机位于“中国东部”区域。In the example in this article, the virtual machine being protected is in the China East region.

  • 每个区域只能创建一个结构对象。Only one fabric object can be created per region.
  • 如果之前已在 Azure 门户中为 VM 启用了 Site Recovery 复制,则 Site Recovery 会自动创建结构对象。If you've previously enabled Site Recovery replication for a VM in the Azure portal, Site Recovery creates a fabric object automatically. 如果区域存在结构对象,则无法创建新结构对象。If a fabric object exists for a region, you can't create a new one.

在开始之前,应明白 Site Recovery 操作以异步方式执行。Before you start, understand that 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. 使用作业跟踪对象获得最新的状态作业 (Get-AzRecoveryServicesAsrJob) 和监视操作状态。Use the job tracking object to get the latest status for the job (Get-AzRecoveryServicesAsrJob), and to monitor the status of the operation.

#Create Primary ASR fabric
$TempASRJob = New-AzRecoveryServicesAsrFabric -Azure -Location 'China East'  -Name "A2Ademo-ChinaEast"

# Track Job status to check for completion
while (($TempASRJob.State -eq "InProgress") -or ($TempASRJob.State -eq "NotStarted")){
        #If the job hasn't completed, sleep for 10 seconds before checking the job status again
        sleep 10;
        $TempASRJob = Get-AzRecoveryServicesAsrJob -Job $TempASRJob
}

#Check if the Job completed successfully. The updated job state of a successfully completed job should be "Succeeded"
Write-Output $TempASRJob.State

$PrimaryFabric = Get-AzRecoveryServicesAsrFabric -Name "A2Ademo-ChinaEast"

如果在同一个保管库中保护来自多个 Azure 区域的虚拟机,请为每个源 Azure 区域创建一个结构对象。If virtual machines from multiple Azure regions are being protected to the same vault, create one fabric object for each source Azure region.

创建用于表示恢复区域的 Site Recovery 结构对象Create a Site Recovery fabric object to represent the recovery region

恢复结构对象表示 Azure 恢复位置。The recovery fabric object represents the recovery Azure location. 如果发生故障转移,虚拟机将复制并恢复到该恢复结构表示的恢复区域。If there's a failover, virtual machines are replicated and recovered to the recovery region represented by the recovery fabric. 本示例使用的 Azure 恢复区域是“中国北部”。The recovery Azure region used in this example is China North.

#Create Recovery ASR fabric
$TempASRJob = New-AzRecoveryServicesAsrFabric -Azure -Location 'China North'  -Name "A2Ademo-ChinaNorth"

# Track Job status to check for completion
while (($TempASRJob.State -eq "InProgress") -or ($TempASRJob.State -eq "NotStarted")){
        sleep 10;
        $TempASRJob = Get-AzRecoveryServicesAsrJob -Job $TempASRJob
}

#Check if the Job completed successfully. The updated job state of a successfully completed job should be "Succeeded"
Write-Output $TempASRJob.State

$RecoveryFabric = Get-AzRecoveryServicesAsrFabric -Name "A2Ademo-ChinaNorth"

在主要结构中创建 Site Recovery 保护容器Create a Site Recovery protection container in the primary fabric

保护容器是用于在一个结构中分组复制项的容器。The protection container is a container used to group replicated items within a fabric.

#Create a Protection container in the primary Azure region (within the Primary fabric)
$TempASRJob = New-AzRecoveryServicesAsrProtectionContainer -InputObject $PrimaryFabric -Name "A2AChinaEastProtectionContainer"

#Track Job status to check for completion
while (($TempASRJob.State -eq "InProgress") -or ($TempASRJob.State -eq "NotStarted")){
        sleep 10;
        $TempASRJob = Get-AzRecoveryServicesAsrJob -Job $TempASRJob
}

Write-Output $TempASRJob.State

$PrimaryProtContainer = Get-AzRecoveryServicesAsrProtectionContainer -Fabric $PrimaryFabric -Name "A2AChinaEastProtectionContainer"

在恢复结构中创建 Site Recovery 保护容器Create a Site Recovery protection container in the recovery fabric

#Create a Protection container in the recovery Azure region (within the Recovery fabric)
$TempASRJob = New-AzRecoveryServicesAsrProtectionContainer -InputObject $RecoveryFabric -Name "A2AChinaNorthProtectionContainer"

#Track Job status to check for completion
while (($TempASRJob.State -eq "InProgress") -or ($TempASRJob.State -eq "NotStarted")){
        sleep 10;
        $TempASRJob = Get-AzRecoveryServicesAsrJob -Job $TempASRJob
}

#Check if the Job completed successfully. The updated job state of a successfully completed job should be "Succeeded"

Write-Output $TempASRJob.State

$RecoveryProtContainer = Get-AzRecoveryServicesAsrProtectionContainer -Fabric $RecoveryFabric -Name "A2AChinaNorthProtectionContainer"

创建复制策略Create a replication policy

#Create replication policy
$TempASRJob = New-AzRecoveryServicesAsrPolicy -AzureToAzure -Name "A2APolicy" -RecoveryPointRetentionInHours 24 -ApplicationConsistentSnapshotFrequencyInHours 4

#Track Job status to check for completion
while (($TempASRJob.State -eq "InProgress") -or ($TempASRJob.State -eq "NotStarted")){
        sleep 10;
        $TempASRJob = Get-AzRecoveryServicesAsrJob -Job $TempASRJob
}

#Check if the Job completed successfully. The updated job state of a successfully completed job should be "Succeeded"
Write-Output $TempASRJob.State

$ReplicationPolicy = Get-AzRecoveryServicesAsrPolicy -Name "A2APolicy"

在主要保护容器与恢复保护容器之间创建保护容器映射Create a protection container mapping between the primary and recovery protection container

保护容器映射将主要保护容器映射到恢复保护容器和复制策略。A protection container mapping maps the primary protection container with a recovery protection container and a replication policy. 针对在保护容器对之间复制虚拟机时所用的每个复制策略各创建一个映射。Create one mapping for each replication policy that you'll use to replicate virtual machines between a protection container pair.

#Create Protection container mapping between the Primary and Recovery Protection Containers with the Replication policy
$TempASRJob = New-AzRecoveryServicesAsrProtectionContainerMapping -Name "A2APrimaryToRecovery" -Policy $ReplicationPolicy -PrimaryProtectionContainer $PrimaryProtContainer -RecoveryProtectionContainer $RecoveryProtContainer

#Track Job status to check for completion
while (($TempASRJob.State -eq "InProgress") -or ($TempASRJob.State -eq "NotStarted")){
        sleep 10;
        $TempASRJob = Get-AzRecoveryServicesAsrJob -Job $TempASRJob
}

#Check if the Job completed successfully. The updated job state of a successfully completed job should be "Succeeded"
Write-Output $TempASRJob.State

$EcnToNcnPCMapping = Get-AzRecoveryServicesAsrProtectionContainerMapping -ProtectionContainer $PrimaryProtContainer -Name "A2APrimaryToRecovery"

创建用于故障回复(故障转移后的反向复制)的保护容器映射Create a protection container mapping for failback (reverse replication after a failover)

在故障转移后,准备好将故障转移的虚拟机恢复到原始 Azure 区域时,执行故障回复。After a failover, when you're ready to bring the failed over virtual machine back to the original Azure region, you do a failback. 为了进行故障回复,故障转移的虚拟机将从故障转移的区域反向复制到原始区域。To fail back, the failed over virtual machine is reverse replicated from the failed over region to the original region. 反向复制时,原始区域和恢复区域的角色将会切换。For reverse replication the roles of the original region and the recovery region switch. 原始区域现在变成新的恢复区域,而最初的恢复区域现在会变成主要区域。The original region now becomes the new recovery region, and what was originally the recovery region now becomes the primary region. 反向复制的保护容器映射表示原始和恢复区域的已切换角色。The protection container mapping for reverse replication represents the switched roles of the original and recovery regions.

#Create Protection container mapping (for fail back) between the Recovery and Primary Protection Containers with the Replication policy
$TempASRJob = New-AzRecoveryServicesAsrProtectionContainerMapping -Name "A2ARecoveryToPrimary" -Policy $ReplicationPolicy -PrimaryProtectionContainer $RecoveryProtContainer -RecoveryProtectionContainer $PrimaryProtContainer

#Track Job status to check for completion
while (($TempASRJob.State -eq "InProgress") -or ($TempASRJob.State -eq "NotStarted")){
        sleep 10;
        $TempASRJob = Get-AzRecoveryServicesAsrJob -Job $TempASRJob
}

#Check if the Job completed successfully. The updated job state of a successfully completed job should be "Succeeded"
Write-Output $TempASRJob.State

$NcnToEcnPCMapping = Get-AzRecoveryServicesAsrProtectionContainerMapping -ProtectionContainer $RecoveryProtContainer -Name "A2ARecoveryToPrimary"

创建缓存存储帐户和目标存储帐户Create cache storage account and target storage account

缓存存储帐户是复制的虚拟机所在的同一 Azure 区域中的标准存储帐户。A cache storage account is a standard storage account in the same Azure region as the virtual machine being replicated. 缓存存储帐户用于在将更改转移到 Azure 恢复区域之前,暂时保存复制更改。The cache storage account is used to hold replication changes temporarily, before the changes are moved to the recovery Azure region. 可以为虚拟机的不同磁盘指定不同的缓存存储帐户,但这不是必需的。You can choose to, but it's not necessary, to specify different cache storage accounts for the different disks of a virtual machine.

#Create Cache storage account for replication logs in the primary region
$ChinaEastCacheStorageAccount = New-AzStorageAccount -Name "a2acachestorage" -ResourceGroupName "A2AdemoRG" -Location 'China East' -SkuName Standard_LRS -Kind Storage

对于 未使用托管磁盘 的虚拟机,目标存储帐户是虚拟机磁盘复制到的恢复区域中的存储帐户。For virtual machines not using managed disks, the target storage account is the storage account in the recovery region to which disks of the virtual machine are replicated. 目标存储帐户可以是标准存储帐户,也可以是高级存储帐户。The target storage account can be either a standard storage account or a premium storage account. 根据磁盘的数据更改率(IO 写入率)以及 Azure Site Recovery 对存储类型支持的变动限制,来选择所需的存储帐户类型。Select the kind of storage account required based on the data change rate (IO write rate) for the disks and the Azure Site Recovery supported churn limits for the storage type.

#Create Target storage account in the recovery region. In this case a Standard Storage account
$ChinaNorthTargetStorageAccount = New-AzStorageAccount -Name "a2atargetstorage" -ResourceGroupName "a2ademorecoveryrg" -Location 'China North' -SkuName Standard_LRS -Kind Storage

创建网络映射Create network mappings

网络映射将主要区域中的虚拟网络映射到恢复区域中的虚拟网络。A network mapping maps virtual networks in the primary region to virtual networks in the recovery region. 网络映射指定主要虚拟网络中的虚拟机应故障转移到的恢复区域中的 Azure 虚拟网络。The network mapping specifies the Azure virtual network in the recovery region, that a virtual machine in the primary virtual network should fail over to. 一个 Azure 虚拟网络只能映射到恢复区域中的单个 Azure 虚拟网络。One Azure virtual network can be mapped to only a single Azure virtual network in a recovery region.

  • 在恢复区域中创建要故障转移到的 Azure 虚拟网络:Create an Azure virtual network in the recovery region to fail over to:

    #Create a Recovery Network in the recovery region
    $ChinaNorthRecoveryVnet = New-AzVirtualNetwork -Name "a2arecoveryvnet" -ResourceGroupName "a2ademorecoveryrg" -Location 'China North' -AddressPrefix "10.0.0.0/16"
    
    Add-AzVirtualNetworkSubnetConfig -Name "default" -VirtualNetwork $ChinaNorthRecoveryVnet -AddressPrefix "10.0.0.0/20" | Set-AzVirtualNetwork
    
    $ChinaNorthRecoveryNetwork = $ChinaNorthRecoveryVnet.Id
    
  • 检索主要虚拟网络。Retrieve the primary virtual network. 虚拟机连接到的 VNet:The VNet that the virtual machine is connected to:

    #Retrieve the virtual network that the virtual machine is connected to
    
    #Get first network interface card(nic) of the virtual machine
    $SplitNicArmId = $VM.NetworkProfile.NetworkInterfaces[0].Id.split("/")
    
    #Extract resource group name from the ResourceId of the nic
    $NICRG = $SplitNicArmId[4]
    
    #Extract resource name from the ResourceId of the nic
    $NICname = $SplitNicArmId[-1]
    
    #Get network interface details using the extracted resource group name and resource name
    $NIC = Get-AzNetworkInterface -ResourceGroupName $NICRG -Name $NICname
    
    #Get the subnet ID of the subnet that the nic is connected to
    $PrimarySubnet = $NIC.IpConfigurations[0].Subnet
    
    # Extract the resource ID of the Azure virtual network the nic is connected to from the subnet ID
    $ChinaEastPrimaryNetwork = (Split-Path(Split-Path($PrimarySubnet.Id))).Replace("\","/")
    
  • 在主要虚拟网络与恢复虚拟网络之间创建网络映射:Create network mapping between the primary virtual network and the recovery virtual network:

    #Create an ASR network mapping between the primary Azure virtual network and the recovery Azure virtual network
    $TempASRJob = New-AzRecoveryServicesAsrNetworkMapping -AzureToAzure -Name "A2AEcnToNcnNWMapping" -PrimaryFabric $PrimaryFabric -PrimaryAzureNetworkId $ChinaEastPrimaryNetwork -RecoveryFabric $RecoveryFabric -RecoveryAzureNetworkId $ChinaNorthRecoveryNetwork
    
    #Track Job status to check for completion
    while (($TempASRJob.State -eq "InProgress") -or ($TempASRJob.State -eq "NotStarted")){
            sleep 10;
            $TempASRJob = Get-AzRecoveryServicesAsrJob -Job $TempASRJob
    }
    
    #Check if the Job completed successfully. The updated job state of a successfully completed job should be "Succeeded"
    Write-Output $TempASRJob.State
    
  • 为反向复制(故障回复)创建网络映射:Create network mapping for the reverse direction (fail back):

    #Create an ASR network mapping for fail back between the recovery Azure virtual network and the primary Azure virtual network
    $TempASRJob = New-AzRecoveryServicesAsrNetworkMapping -AzureToAzure -Name "A2ANcnToEcnNWMapping" -PrimaryFabric $RecoveryFabric -PrimaryAzureNetworkId $ChinaNorthRecoveryNetwork -RecoveryFabric $PrimaryFabric -RecoveryAzureNetworkId $ChinaEastPrimaryNetwork
    
    #Track Job status to check for completion
    while (($TempASRJob.State -eq "InProgress") -or ($TempASRJob.State -eq "NotStarted")){
            sleep 10;
            $TempASRJob = Get-AzRecoveryServicesAsrJob -Job $TempASRJob
    }
    
    #Check if the Job completed successfully. The updated job state of a successfully completed job should be "Succeeded"
    Write-Output $TempASRJob.State
    

复制 Azure 虚拟机Replicate Azure virtual machine

复制包含 托管磁盘 的 Azure 虚拟机。Replicate the Azure virtual machine with managed disks.

#Get the resource group that the virtual machine must be created in when failed over.
$RecoveryRG = Get-AzResourceGroup -Name "a2ademorecoveryrg" -Location "China North"

#Specify replication properties for each disk of the VM that is to be replicated (create disk replication configuration)

#OsDisk
$OSdiskId = $vm.StorageProfile.OsDisk.ManagedDisk.Id
$RecoveryOSDiskAccountType = $vm.StorageProfile.OsDisk.ManagedDisk.StorageAccountType
$RecoveryReplicaDiskAccountType = $vm.StorageProfile.OsDisk.ManagedDisk.StorageAccountType

$OSDiskReplicationConfig = New-AzRecoveryServicesAsrAzureToAzureDiskReplicationConfig -ManagedDisk -LogStorageAccountId $ChinaEastCacheStorageAccount.Id `
         -DiskId $OSdiskId -RecoveryResourceGroupId  $RecoveryRG.ResourceId -RecoveryReplicaDiskAccountType  $RecoveryReplicaDiskAccountType `
         -RecoveryTargetDiskAccountType $RecoveryOSDiskAccountType

# Data disk
$datadiskId1 = $vm.StorageProfile.DataDisks[0].ManagedDisk.Id
$RecoveryReplicaDiskAccountType = $vm.StorageProfile.DataDisks[0].ManagedDisk.StorageAccountType
$RecoveryTargetDiskAccountType = $vm.StorageProfile.DataDisks[0].ManagedDisk.StorageAccountType

$DataDisk1ReplicationConfig  = New-AzRecoveryServicesAsrAzureToAzureDiskReplicationConfig -ManagedDisk -LogStorageAccountId $ChinaEastCacheStorageAccount.Id `
         -DiskId $datadiskId1 -RecoveryResourceGroupId $RecoveryRG.ResourceId -RecoveryReplicaDiskAccountType $RecoveryReplicaDiskAccountType `
         -RecoveryTargetDiskAccountType $RecoveryTargetDiskAccountType

#Create a list of disk replication configuration objects for the disks of the virtual machine that are to be replicated.
$diskconfigs = @()
$diskconfigs += $OSDiskReplicationConfig, $DataDisk1ReplicationConfig

#Start replication by creating replication protected item. Using a GUID for the name of the replication protected item to ensure uniqueness of name.
$TempASRJob = New-AzRecoveryServicesAsrReplicationProtectedItem -AzureToAzure -AzureVmId $VM.Id -Name (New-Guid).Guid -ProtectionContainerMapping $EcnToNcnPCMapping -AzureToAzureDiskReplicationConfiguration $diskconfigs -RecoveryResourceGroupId $RecoveryRG.ResourceId

复制包含 非托管磁盘 的 Azure 虚拟机。Replicate the Azure virtual machine with unmanaged disks.

#Specify replication properties for each disk of the VM that is to be replicated (create disk replication configuration)

#Disk replication configuration for the OS disk
$OSDiskReplicationConfig = New-AzRecoveryServicesAsrAzureToAzureDiskReplicationConfig -VhdUri $OSDiskVhdURI.Uri -LogStorageAccountId $ChinaEastCacheStorageAccount.Id -RecoveryAzureStorageAccountId $ChinaNorthTargetStorageAccount.Id

#Disk replication configuration for data disk
$DataDisk1ReplicationConfig = New-AzRecoveryServicesAsrAzureToAzureDiskReplicationConfig -VhdUri $DataDisk1VhdURI.Uri -LogStorageAccountId $ChinaEastCacheStorageAccount.Id -RecoveryAzureStorageAccountId $ChinaNorthTargetStorageAccount.Id

#Create a list of disk replication configuration objects for the disks of the virtual machine that are to be replicated.
$diskconfigs = @()
$diskconfigs += $OSDiskReplicationConfig, $DataDisk1ReplicationConfig

#Get the resource group that the virtual machine must be created in when failed over.
$RecoveryRG = Get-AzResourceGroup -Name "a2ademorecoveryrg" -Location "China North"

#Start replication by creating replication protected item. Using a GUID for the name of the replication protected item to ensure uniqueness of name.
$TempASRJob = New-AzRecoveryServicesAsrReplicationProtectedItem -AzureToAzure -AzureVmId $VM.Id -Name (New-Guid).Guid -ProtectionContainerMapping $EcnToNcnPCMapping -AzureToAzureDiskReplicationConfiguration $diskconfigs -RecoveryResourceGroupId $RecoveryRG.ResourceId

#Track Job status to check for completion
while (($TempASRJob.State -eq "InProgress") -or ($TempASRJob.State -eq "NotStarted")){
        sleep 10;
        $TempASRJob = Get-AzRecoveryServicesAsrJob -Job $TempASRJob
}

#Check if the Job completed successfully. The updated job state of a successfully completed job should be "Succeeded"
Write-Output $TempASRJob.State

成功启动复制操作后,虚拟机数据将复制到恢复区域。Once the start replication operation succeeds, virtual machine data is replicated to the recovery region.

复制过程首先在恢复区域中初始植入虚拟机复制磁盘的副本。The replication process starts by initially seeding a copy of the replicating disks of the virtual machine in the recovery region. 此阶段中称为初始复制阶段。This phase is called the initial replication phase.

初始复制完成后,复制过程将前进到差异同步阶段。AFter initial replication completes, replication moves to the differential synchronization phase. 此时,虚拟机受到保护,并可以对其执行测试故障转移操作。At this point, the virtual machine is protected and a test failover operation can be performed on it. 初始复制完成后,表示虚拟机的复制项的复制状态将转换为“受保护”状态。 The replication state of the replicated item representing the virtual machine goes to the Protected state after initial replication completes.

获取虚拟机对应的复制保护项的详细信息,监视该虚拟机的复制状态和复制运行状况。Monitor the replication state and replication health for the virtual machine by getting details of the replication protected item corresponding to it.

Get-AzRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $PrimaryProtContainer | Select FriendlyName, ProtectionState, ReplicationHealth
FriendlyName ProtectionState ReplicationHealth
------------ --------------- -----------------
AzureDemoVM  Protected       Normal

执行测试故障转移,进行验证并清理测试故障转移Do a test failover, validate, and cleanup test failover

在虚拟机复制进入受保护状态后,可以针对该虚拟机(针对虚拟机的复制保护项)执行测试故障转移操作。After replication for the virtual machine has reached a protected state, a test failover operation can be performed on the virtual machine (on the replication protected item of the virtual machine).

#Create a separate network for test failover (not connected to my DR network)
$TFOVnet = New-AzVirtualNetwork -Name "a2aTFOvnet" -ResourceGroupName "a2ademorecoveryrg" -Location 'China North' -AddressPrefix "10.3.0.0/16"

Add-AzVirtualNetworkSubnetConfig -Name "default" -VirtualNetwork $TFOVnet -AddressPrefix "10.3.0.0/20" | Set-AzVirtualNetwork

$TFONetwork= $TFOVnet.Id

执行测试故障转移。Do a test failover.

$ReplicationProtectedItem = Get-AzRecoveryServicesAsrReplicationProtectedItem -FriendlyName "AzureDemoVM" -ProtectionContainer $PrimaryProtContainer

$TFOJob = Start-AzRecoveryServicesAsrTestFailoverJob -ReplicationProtectedItem $ReplicationProtectedItem -AzureVMNetworkId $TFONetwork -Direction PrimaryToRecovery

等待测试故障转移操作完成。Wait for the test failover operation to complete.

Get-AzRecoveryServicesAsrJob -Job $TFOJob
Name             : 3dcb043e-3c6d-4e0e-a42e-8d4245668547
ID               : /Subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/a2ademorecoveryrg/providers/Microsoft.RecoveryServices/vaults/a2aDemoR
                   ecoveryVault/replicationJobs/3dcb043e-3c6d-4e0e-a42e-8d4245668547
Type             : Microsoft.RecoveryServices/vaults/replicationJobs
JobType          : TestFailover
DisplayName      : Test failover
ClientRequestId  : 1ef8515b-b130-4452-a44d-91aaf071931c ActivityId: 907bb2bc-ebe6-4732-8b66-77d0546eaba8
State            : Succeeded
StateDescription : Completed
StartTime        : 4/25/2018 4:29:43 AM
EndTime          : 4/25/2018 4:33:06 AM
TargetObjectId   : ce86206c-bd78-53b4-b004-39b722c1ac3a
TargetObjectType : ProtectionEntity
TargetObjectName : azuredemovm
AllowedActions   :
Tasks            : {Prerequisites check for test failover, Create test virtual machine, Preparing the virtual machine, Start the virtual machine}
Errors           : {}

测试故障转移作业成功完成后,可以连接到测试故障转移虚拟机,并验证测试故障转移。After the test failover job completes successfully, you can connect to the test failed over virtual machine, and validate the test failover.

对测试故障转移虚拟机完成测试后,通过启动清理测试故障转移操作来清理测试副本。Once testing is complete on the test failed over virtual machine, clean up the test copy by starting the cleanup test failover operation. 此操作会删除测试故障转移创建的虚拟机测试副本。This operation deletes the test copy of the virtual machine that was created by the test failover.

$Job_TFOCleanup = Start-AzRecoveryServicesAsrTestFailoverCleanupJob -ReplicationProtectedItem $ReplicationProtectedItem

Get-AzRecoveryServicesAsrJob -Job $Job_TFOCleanup | Select State
State
-----
Succeeded

故障转移到 AzureFail over to Azure

将虚拟机故障转移到特定的恢复点。Fail over the virtual machine to a specific recovery point.

$RecoveryPoints = Get-AzRecoveryServicesAsrRecoveryPoint -ReplicationProtectedItem $ReplicationProtectedItem

#The list of recovery points returned may not be sorted chronologically and will need to be sorted first, in order to be able to find the oldest or the latest recovery points for the virtual machine.
"{0} {1}" -f $RecoveryPoints[0].RecoveryPointType, $RecoveryPoints[-1].RecoveryPointTime
CrashConsistent 4/24/2018 11:10:25 PM
#Start the fail over job
$Job_Failover = Start-AzRecoveryServicesAsrUnplannedFailoverJob -ReplicationProtectedItem $ReplicationProtectedItem -Direction PrimaryToRecovery -RecoveryPoint $RecoveryPoints[-1]

do {
        $Job_Failover = Get-AzRecoveryServicesAsrJob -Job $Job_Failover;
        sleep 30;
} while (($Job_Failover.State -eq "InProgress") -or ($JobFailover.State -eq "NotStarted"))

$Job_Failover.State
Succeeded

当故障转移作业成功时,你可以提交故障转移操作。When the failover job is successful, you can commit the failover operation.

$CommitFailoverJOb = Start-AzRecoveryServicesAsrCommitFailoverJob -ReplicationProtectedItem $ReplicationProtectedItem

Get-AzRecoveryServicesAsrJob -Job $CommitFailoverJOb
Name             : 58afc2b7-5cfe-4da9-83b2-6df358c6e4ff
ID               : /Subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/a2ademorecoveryrg/providers/Microsoft.RecoveryServices/vaults/a2aDemoR
                   ecoveryVault/replicationJobs/58afc2b7-5cfe-4da9-83b2-6df358c6e4ff
Type             : Microsoft.RecoveryServices/vaults/replicationJobs
JobType          : CommitFailover
DisplayName      : Commit
ClientRequestId  : 10a95d6c-359e-4603-b7d9-b7ee3317ce94 ActivityId: 8751ada4-fc42-4238-8de6-a82618408fcf
State            : Succeeded
StateDescription : Completed
StartTime        : 4/25/2018 4:50:58 AM
EndTime          : 4/25/2018 4:51:01 AM
TargetObjectId   : ce86206c-bd78-53b4-b004-39b722c1ac3a
TargetObjectType : ProtectionEntity
TargetObjectName : azuredemovm
AllowedActions   :
Tasks            : {Prerequisite check, Commit}
Errors           : {}

重新保护并故障回复到源区域Reprotect and fail back to the source region

故障转移后,准备好恢复到原始区域时,使用 Update-AzRecoveryServicesAsrProtectionDirection cmdlet 对复制保护的项启动反向复制。After a failover, when you're ready to go back to the original region, start reverse replication for the replication protected item using the Update-AzRecoveryServicesAsrProtectionDirection cmdlet.

#Create Cache storage account for replication logs in the primary region
$ChinaNorthCacheStorageAccount = New-AzStorageAccount -Name "a2acachestoragechinanorth" -ResourceGroupName "A2AdemoRG" -Location 'China North' -SkuName Standard_LRS -Kind Storage
#Use the recovery protection container, new cache storage account in China North and the source region VM resource group
Update-AzRecoveryServicesAsrProtectionDirection -ReplicationProtectedItem $ReplicationProtectedItem -AzureToAzure
-ProtectionContainerMapping $NcnToEcnPCMapping -LogStorageAccountId $ChinaNorthCacheStorageAccount.Id -RecoveryResourceGroupID $sourceVMResourcegroup.ResourceId

在重新保护完成后,可以反向进行故障转移(从中国北部到中国东部)并故障回复到源区域。After reprotection is complete, you can fail over in the reverse direction, China North to China East, and fail back to source region.

禁用复制Disable replication

可以使用 Remove-AzRecoveryServicesAsrReplicationProtectedItem cmdlet 禁用复制。You can disable replication with the Remove-AzRecoveryServicesAsrReplicationProtectedItem cmdlet.

Remove-AzRecoveryServicesAsrReplicationProtectedItem -ReplicationProtectedItem $ReplicationProtectedItem

后续步骤Next steps

查看 Azure Site Recovery PowerShell 参考来了解如何通过 PowerShell 执行其他任务,例如创建恢复计划,以及对恢复计划执行测试性故障转移。View the Azure Site Recovery PowerShell reference to learn how you can do other tasks such as creating recovery plans and testing failover of recovery plans with PowerShell.