使用 C# 更改 Azure VM 角色大小

Change Azure VM role size using c#

我正在尝试使用 C# 管理复制一些 PowerShell 代码以更改现有 Azure VM 的角色大小API (Microsoft.WindowsAzure.Management.Compute)。

这就是我想要完成的:

Get-AzureVM | Where-Object {$_.InstanceSize -ne 'Basic_A0'} | Set-AzureVMSize "Basic_A0" | Update-AzureVM

到目前为止,我的 C# 代码尝试降级特定的 VM,但每当我尝试更新 VM 设置时,我都会遇到一个我不太了解的异常,因为 PowerShell 版本不需要在上安装 ProvisionGuestAgent VM 更改角色大小。

An unhandled exception of type 'Microsoft.WindowsAzure.CloudException' occurred in Microsoft.Threading.Tasks.dll

Additional information: BadRequest: In order to use extension reference, ProvisionGuestAgent must be set during virtual machine provisioning.

public void DowngradeVm(ComputeManagementClient Client, string VmName) {
  var hostedServices = Client.HostedServices.List();
  foreach (var service in hostedServices) {
    if (service.ServiceName != VmName) { continue;  }
    var deployment = Client.Deployments.GetBySlot(service.ServiceName, DeploymentSlot.Production);
    if (deployment != null) {
      if (deployment.Roles.Count > 0) {
        foreach (var role in deployment.Roles) {
          if (role.RoleType == VirtualMachineRoleType.PersistentVMRole.ToString()) {
            if (role.RoleSize != "Basic_A0") {
              // attempt do downgrade VM
              var upd = new VirtualMachineUpdateParameters();
              upd.AvailabilitySetName = role.AvailabilitySetName;
              upd.ConfigurationSets = role.ConfigurationSets;
              upd.DataVirtualHardDisks = role.DataVirtualHardDisks;
              upd.Label = role.Label;
              upd.OSVirtualHardDisk = role.OSVirtualHardDisk;
              upd.ProvisionGuestAgent = role.ProvisionGuestAgent;
              upd.ResourceExtensionReferences = role.ResourceExtensionReferences;
              upd.RoleName = role.RoleName;
              upd.RoleSize = "Basic_A0";
              // Service, Deployment and VM have the same name
              // the next line throws an exception
              Client.VirtualMachines.Update(VmName, VmName, VmName, upd);
            }
          }
        }
      }
    }
  }
}

我找到了解决方案:role.ProvisionGuestAgent 为空(可能是因为该角色不在线),但需要为 true 才能进行更新。

          upd.ProvisionGuestAgent = true;