0

我有一个 Azure 存储帐户。它有许多相关联的访问密钥。从 Azure Web GUI 可以“轮换”这些密钥。

GUI 中的密钥轮换

也可以使用 (我相信) 从命令行旋转它们az storage account keys renew

我想从 C# 代码中旋转这些键。我很难找到让我这样做的正确对象。

我知道像Azure.Storage.BlobsMicrosoft.Azure.Cosmos.Table这样的 NuGet 包。这些家族之一的任何 NuGet 包中是否有任何类具有让我轮换/更新/重新生成这些存储帐户访问密钥的功能?

提前致谢!

4

1 回答 1

1

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("===========================");
        }
    }
}
于 2021-11-08T12:10:24.000 回答