Search code examples
c#azureazure-storage-account

Is it possible to regenerate Storage account keys using C#?


I want regenerate Storage account key using C# code and replace old keys in key vault with regenerated key . Please help me.


Solution

  • With Microsoft.Azure.Management.Fluent and Microsoft.Azure.Management.ResourceManager.Fluent packages, below is my code to regenerate the key.

            string clientSecret = "client secret";
            string clientId = "client id";
    
            var azureCredentials = new AzureCredentials(new ServicePrincipalLoginInformation
            {
                ClientId = clientId,
                ClientSecret = clientSecret
            }, tenantId, AzureEnvironment.AzureGlobalCloud);
    
            var azure = Azure
            .Configure()
            .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
            .Authenticate(azureCredentials)
            .WithDefaultSubscription();
    
            var keyName = "key1";
    
            var storageAccount = azure.StorageAccounts.GetByResourceGroup("resource group name", "storage account name");
    
            var key = storageAccount.RegenerateKey(keyName);
            Console.WriteLine(key.FirstOrDefault()?.Value);