透過C# 建立 Azure Storage Account

本篇是透過C#來建立Azure Storage Account,而不使用Azure Portal或Azure PowerShell來建立

在用C#來建立Storage Account以前,
需要準備一些資訊為訂閱IDAAD的TenantId應用程式Id應用程式的金鑰
  • 取得訂閱ID

  • 取得AAD的TenantId

  • 取得應用程式Id
在Azure訂閱帳戶建立一個自動化帳戶
 當建立自動化帳戶時,一定選擇建立Azure 執行身分帳戶,這樣才會在AAD註冊應用程式

 

以下連結為建立自動化帳戶流程
https://docs.microsoft.com/zh-cn/azure/automation/automation-quickstart-create-account 
建立完自動化帳戶以後,將會在該AAD註冊應用程式

 

 

  • 取得應用程式金鑰

  • C# 部分
以下需透過NuGet安裝
Microsoft.IdentityModel.Clients.ActiveDirectory
Microsoft.Azure.Management.Storage
Microsoft.Azure.DocumentDB
RestSharp
class Program
    {
        //訂閱ID
        private static string subscriptionId = "請自行填入訂閱Id";
        //AAD的TenantId
        private static string tenantId = "請自行填入TenantId";
        //應用程式Id
        private static string clientId = "請自行填入應用程式Id";
        //應用程式金鑰
        private static string secretKey = "請自行填入應用程式金鑰";
        //Storage Account要建立在哪個資源群組底下
        private static string resourceGroup = "請自行填入資源群組名稱";
        //Storage Account
        private static string storageAccount = "請自行填入欲建立Storage Account Name";
        //驗證的Token
        private static string token = string.Empty;
        static void Main(string[] args)
        {
            try
            {
                //進行驗證
                Authorize();
                //建立Storage Account
                CreateStorageAccount();
                //取得Storage Account Key
                ShowStorageAccountKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();


        }

        /// <summary>
        /// 顯示金鑰
        /// </summary>
        private static void ShowStorageAccountKey()
        {
            KeyArray key = GetAllKey();
            key.keys.ForEach(x => Console.WriteLine($"{x.keyName} = {x.value}"));
            
        }

        /// <summary>
        /// 建立Storage Account
        /// </summary>
        private static void CreateStorageAccount()
        {
            StorageManagementClient StorageManagement = new StorageManagementClient(new Microsoft.Azure.TokenCloudCredentials(subscriptionId, token));
            var re = StorageManagement.StorageAccounts.CreateAsync(resourceGroup, storageAccount, new Microsoft.Azure.Management.Storage.Models.StorageAccountCreateParameters()
            {
                Location = LocationNames.EastAsia,
                AccountType = Microsoft.Azure.Management.Storage.Models.AccountType.StandardLRS
            }, new CancellationToken() { }).Result;
            if (re.Status != Microsoft.Azure.OperationStatus.Succeeded)
            {
                throw new Exception("建立儲存體帳戶失敗");
            }
            Console.WriteLine($"Storage Account : {storageAccount} created");

        }

        /// <summary>
        /// 取得建立的Storage Account金鑰
        /// </summary>
        /// <returns>Storage Account 金鑰</returns>
        private static KeyArray GetAllKey()
        {
            string url = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Storage/storageAccounts/{storageAccount}/listKeys?api-version=2016-01-01";
            IRestClient client = new RestClient("https://management.azure.com");
            IRestRequest req = new RestRequest(url, Method.POST);
            req.AddHeader("Authorization", $"bearer {token}");
            var response = client.Execute(req);
            return JsonConvert.DeserializeObject<KeyArray>(response.Content);
        }

        /// <summary>
        /// 進行授權,取得AccessToken
        /// </summary>
        private static void Authorize()
        {
            var authenticationContext = new AuthenticationContext($"https://login.windows.net/{tenantId}");
            var credential = new ClientCredential(clientId, secretKey);
            var result = authenticationContext.AcquireTokenAsync("https://management.core.windows.net/",
                credential);

            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            token = result.Result.AccessToken;
        }


    }

    public class KeyArray
    {
        public List<KeyInfo> keys { get; set; }
        public class KeyInfo
        {

            public string keyName { get; set; }
            public string value { get; set; }
            public string permissions { get; set; }
        }
    }

執行結果如下

 

參考網址:

https://docs.microsoft.com/zh-tw/azure/automation/automation-offering-get-started#authentication-planning