Programmatically get Azure storage account properties

守給你的承諾、 提交于 2019-12-06 01:54:16

My question is: is there a way to programmatically retrieve at least one of these parameters in my code, so that at least the user will have to insert only one parameters and not two? my goal is to make the user's life easier.

According to your description, I suggest you could use azure rest api to get the storage account key by using account name.

Besides, we could also use rest api to list all the rescourse group's storage account name, but it still need to send the rescourse group name as parameter to the azure management url.

You could send the request to the azure management as below url:

POST: https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resrouceGroupName}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}/listKeys?api-version=2016-01-01
Authorization: Bearer {token}

More details, you could refer to below codes:

Notice: Using this way, you need firstly create an Azure Active Directory application and service principal. After you generate the service principal, you could get the applicationid,access key and talentid. More details, you could refer to this article.

Code:

    string tenantId = " ";
    string clientId = " ";
    string clientSecret = " ";
    string subscription = " ";
    string resourcegroup = "BrandoSecondTest";
    string accountname = "brandofirststorage";
    string authContextURL = "https://login.windows.net/" + tenantId;
    var authenticationContext = new AuthenticationContext(authContextURL);
    var credential = new ClientCredential(clientId, clientSecret);
    var result = authenticationContext.AcquireTokenAsync(resource: "https://management.azure.com/", clientCredential: credential).Result;
    if (result == null)
    {
        throw new InvalidOperationException("Failed to obtain the JWT token");
    }
    string token = result.AccessToken;
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Storage/storageAccounts/{2}/listKeys?api-version=2016-01-01", subscription, resourcegroup, accountname));
    request.Method = "POST";
    request.Headers["Authorization"] = "Bearer " + token;
    request.ContentType = "application/json";
    request.ContentLength = 0;


    //Get the response
    var httpResponse = (HttpWebResponse)request.GetResponse();

    using (System.IO.StreamReader r = new System.IO.StreamReader(httpResponse.GetResponseStream()))
    {
        string jsonResponse = r.ReadToEnd();

        Console.WriteLine(jsonResponse);
    }

Result:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!