C#使用Azure资源管理器(ARM)删除Azure虚拟机时获取结果状态

时间:2016-12-12 05:36:55

标签: c# azure azure-resource-manager

我希望使用Azure资源管理器(ARM)和.NET C#获得azure vm部署的结果,以识别其成功或失败。

我找到了以下样本。

https://docs.microsoft.com/en-us/azure/virtual-machines/virtual-machines-windows-csharp-template

在本文中,当deploing,"返回等待"声明被使用。

public static async Task<DeploymentExtended> CreateTemplateDeploymentAsync(
  TokenCredentials credential,
  string groupName,
  string deploymentName,
  string subscriptionId){
Console.WriteLine("Creating the template deployment...");
var deployment = new Deployment();
deployment.Properties = new DeploymentProperties

{
 Mode = DeploymentMode.Incremental,
 Template = File.ReadAllText("..\\..\\VirtualMachineTemplate.json"),
 Parameters = File.ReadAllText("..\\..\\Parameters.json")
};
var resourceManagementClient = new ResourceManagementClient(credential) 
  { SubscriptionId = subscriptionId };
 return await resourceManagementClient.Deployments.CreateOrUpdateAsync(
 groupName,
 deploymentName,
 deployment);
 }

我该如何处理结果? 我想根据结果分配程序。

1 个答案:

答案 0 :(得分:0)

我们可以使用Properties.ProvisioningState获取部署状态。但是当它部署VM失败时,可能会抛出异常,所以我们需要用代码捕获异常。

1.Code demo:

 var token = GetAccessTokenAsync();
 var credential = new TokenCredentials(token.Result.AccessToken);
 string provisoningStatus = "Failed";
 try
   {
     var result =CreateTemplateDeploymentAsync(credential, "tom", "MyWindowsVM", "you subscription Id")
                   .Result;
                provisoningStatus = result.Properties.ProvisioningState;
   }
 catch (Exception)
  {

     //ToDo
  }
  if (provisoningStatus.Equals("Failed"))
  {
         //TODo
  }

}
  1. 成功创建虚拟机
  2. enter image description here

    1. 从Azure门户检查
    2. enter image description here

      如果失败而没有捕获异常

      enter image description here