How to programmatically create Azure Storage account – .NET SDK

Azure provides Management APIs to manage Azure subscriptions programmatically. Management APIs are available in many languages including PowerShell cmdlets and Java SDK.

In order to create a acting agent to manage the Azure (our application code is an agent) we do have to authenticate to Azure using a certificate or Azure Active Directory. Refer to this article on how to create a certificate authentication with Azure. This article describes how to create a certificate, associate it with the Azure subscription and how to programmatically retrieve the X.509 certificate from the local machine.

The below code shows the continuation on how to create Azure Storage programmatically. In order to do this add the references of Azure Management Libraries to your project.

image

Now we have the right references in place, now we have to create the certificate cloud credentials in order to invoke the Azure Management Client classes. We need two parameters to create the certificate cloud credentials.

  1. Azure Subscription ID
  2. Azure Authentication certificate (steps to obtain this are described in this link)

So based on the above article we have established the trust between Azure and our agent. And we have the certificate in .NET. Let’s assume our certificate variable is “certificate”.

Now create the CertificateCloudCredentials object using the subscription ID and X.509 certificate.

   1: string subscriptionId = "your id";

   2: CertificateCloudCredentials credentials = new CertificateCloudCredentials(subscriptionId,certificate);

Now we can create the storage account using the blow code.

   1: private static void CreateStorageAccount()

   2: {

   3:     var storageClient = CloudContext.Clients.CreateStorageManagementClient(credentials);

   4:     

   5:     var response = storageClient.StorageAccounts.Create(new StorageAccountCreateParameters()

   6:     {

   7:         Location = LocationNames.EastAsia,

   8:         Name = "storage name",

   9:         Description = "storage from code"

  10:     });

  11:  

  12:     Console.WriteLine(response.StatusCode);

  13: }

 

Here the Create method is a blocking method, but Azure Management Libraries offer async methods as well as CreateAsync. So we can use them with Task<await>. Learn more about asynchronous programming here.