The Nuget package you would want to use is Azure.ResourceManager.Storage
. Once you create/get an instance of StorageAccount
, you would need to call RegenerateKeyAsync
method to regenrate a key.
Here's the sample code for the same. Please note that you will also need to install Azure.Identity
Nuget package.
using System;
using System.Threading.Tasks;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Storage;
using Azure.ResourceManager.Storage.Models;
namespace SO69882633
{
class Program
{
private const string subscriptionId = "23456789-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
private const string resourceGroupName = "resource-group-name";
private const string storageAccountName = "storageaccountname";
private const string keyToRegenerate = "key2";//Key to regenerate. Could be either "key1" or "key2"
static async Task Main(string[] args)
{
var credentials = new DefaultAzureCredential();
ArmClient armClient = new ArmClient(new DefaultAzureCredential());
string storageAccountResourceId =
$"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}";
StorageAccount storageAccount = armClient.GetStorageAccount(storageAccountResourceId);
var keys = await storageAccount.GetKeysAsync();
foreach (var key in keys.Value.Keys)
{
Console.WriteLine($"{key.KeyName}: {key.Value}");
}
Console.WriteLine("===========================");
StorageAccountRegenerateKeyParameters parameters = new StorageAccountRegenerateKeyParameters(keyToRegenerate);
var result = await storageAccount.RegenerateKeyAsync(parameters);
Console.WriteLine($"\"{keyToRegenerate}\" key regenerated successfully.");
Console.WriteLine("Listing keys again (just to make sure ;-))...");
keys = await storageAccount.GetKeysAsync();
foreach (var key in keys.Value.Keys)
{
Console.WriteLine($"{key.KeyName}: {key.Value}");
}
Console.WriteLine("===========================");
}
}
}