通过使用 Azure PowerShell 更改 VM 的可用性集

适用于:✔️ Linux VM ✔️ Windows VM

以下步骤说明如何通过使用 Azure PowerShell 来更改虚拟机 (VM) 的可用性集。 只有在创建 VM 时,才能将 VM 添加到可用性集。 若要更改可用性集,需要删除并重新创建 VM。

本文最后一次使用 Az PowerShell 模块版本 1.2.0 在 2019 年 2 月 12 日进行了测试。

警告

这只是一个示例。 在某些情况下,需要针对特定部署更新它。

请确保将磁盘设置为 detach,以此为删除选项。 如果已设置为 delete,请先更新 VM,然后再删除 VM。

如果 VM 已连接到负载均衡器,则需要更新脚本以处理这种情况。

完成此过程后,某些扩展可能还需要重新安装。

如果 VM 使用混合权益,则需要更新该示例,以在新的 VM 上启用混合权益。

先决条件

更改可用性集

以下脚本提供一个示例,该示例收集所需的信息、删除原始 VM,并在新可用性集中重新创建 VM:

  # Set variables
      $resourceGroup = "myResourceGroup"
      $vmName = "myVM"
      $newAvailSetName = "myAvailabilitySet"

  # Get the details of the VM to be moved to the availability set
      $originalVM = Get-AzVM `
        -ResourceGroupName $resourceGroup `
        -Name $vmName

  # Create a new availability set if it doesn't exist
      $availSet = Get-AzAvailabilitySet `
        -ResourceGroupName $resourceGroup `
        -Name $newAvailSetName `
        -ErrorAction Ignore
      if (-Not $availSet) {
      $availSet = New-AzAvailabilitySet `
        -Location $originalVM.Location `
        -Name $newAvailSetName `
        -ResourceGroupName $resourceGroup `
        -PlatformFaultDomainCount 2 `
        -PlatformUpdateDomainCount 2 `
        -Sku Aligned
      }

  # Remove the original VM
      Remove-AzVM -ResourceGroupName $resourceGroup -Name $vmName

  # Create the basic configuration for the replacement VM.
      $newVM = New-AzVMConfig `
        -VMName $originalVM.Name `
        -VMSize $originalVM.HardwareProfile.VmSize `
        -AvailabilitySetId $availSet.Id
  
  # For a Linux VM, change the last parameter from -Windows to -Linux
      Set-AzVMOSDisk `
        -VM $newVM -CreateOption Attach `
        -ManagedDiskId $originalVM.StorageProfile.OsDisk.ManagedDisk.Id `
        -Name $originalVM.StorageProfile.OsDisk.Name `
        -Windows

  # Add data disks
      foreach ($disk in $originalVM.StorageProfile.DataDisks) { 
      Add-AzVMDataDisk -VM $newVM `
        -Name $disk.Name `
        -ManagedDiskId $disk.ManagedDisk.Id `
        -Caching $disk.Caching `
        -Lun $disk.Lun `
        -DiskSizeInGB $disk.DiskSizeGB `
        -CreateOption Attach
      }
      
  # Add NICs and keep the same NICs as primary; keep the private IP too, if it exists
      foreach ($nic in $originalVM.NetworkProfile.NetworkInterfaces) {	
      if ($nic.Primary -eq "True")
      {
              Add-AzVMNetworkInterface `
                -VM $newVM `
                -Id $nic.Id -Primary
                }
            else
                {
                  Add-AzVMNetworkInterface `
                  -VM $newVM `
                  -Id $nic.Id 
                  }
        }

  # Re-create the VM
      New-AzVM `
        -ResourceGroupName $resourceGroup `
        -Location $originalVM.Location `
        -VM $newVM `
        -DisableBginfoExtension