简体   繁体   English

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

[英]C# Getting result status when deploing Azure Virtual Machine using Azure Resource Manager(ARM)

I'd like to get result of azure vm deployment using Azure Resource Manager(ARM) with .NET C# to recognize its success or fail. 我想使用Azure资源管理器(ARM)和.NET C#获得azure vm部署的结果,以识别其成功或失败。

I found following sample. 我找到了以下样本。

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

In this article, when deploing, "return await" statement is used. 在本文中,当使用deploing时,使用“return await”语句。

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);
 }

How can I handle the result? 我该如何处理结果? I want to devide program according to the result. 我想根据结果分配程序。

We can get the deployment status using the Properties.ProvisioningState . 我们可以使用Properties.ProvisioningState获取部署状态。 But when it deploy VM failed, may throw exception, so we need to catch the exception with code. 但是当它部署VM失败时,可能会抛出异常,所以我们需要用代码捕获异常。

1.Code demo : 1.代码演示:

 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. Create a VM successfully 成功创建VM

在此输入图像描述

  1. Check from the Azure Portal 从Azure门户检查

在此输入图像描述

If it is failed without catching exception 如果失败而没有捕获异常

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM