简体   繁体   中英

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.

I found following sample.

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

In this article, when deploing, "return await" statement is used.

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 . But when it deploy VM failed, may throw exception, so we need to catch the exception with code.

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. Create a VM successfully

在此输入图像描述

  1. Check from the Azure Portal

在此输入图像描述

If it is failed without catching exception

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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