以编程方式获取Azure存储帐户属性 [英] Programmatically get Azure storage account properties

查看:61
本文介绍了以编程方式获取Azure存储帐户属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#Web应用程序中编写了一种从Azure存储帐户中删除旧Blob的方法.

I wrote in my C# web application a method that deletes old blobs from Azure storage account.

这是我的代码:

public void CleanupIotHubExpiredBlobs()
{
   const string StorageAccountName = "storageName";
   const string StorageAccountKey = "XXXXXXXXXX";
   const string StorageContainerName = "outputblob";
   string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", StorageAccountName, StorageAccountKey);

   // Retrieve storage account from connection string.
   CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
   // Create the blob client.
   CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
   // select container in which to look for old blobs.
   CloudBlobContainer container = blobClient.GetContainerReference(StorageContainerName);

   // set up Blob access condition option which will filter all the blobs which are not modified for X (this.m_CleanupExpirationNumOfDays) amount of days
   IEnumerable<IListBlobItem> blobs = container.ListBlobs("", true);

  foreach (IListBlobItem blob in blobs)
  {
    CloudBlockBlob cloudBlob = blob as CloudBlockBlob;
    Console.WriteLine(cloudBlob.Properties);
    cloudBlob.DeleteIfExists(DeleteSnapshotsOption.None, AccessCondition.GenerateIfNotModifiedSinceCondition(DateTime.Now.AddDays(-1 * 0.04)), null, null);
  }

   LogMessageToFile("Remove old blobs from storage account");
}

如您所见,为了实现该方法,该方法必须接收StorageAccountName和StorageAccountKey参数.

as you can see, In order to achieve that The method has to receive StorageAccountName and StorageAccountKey parameters.

一种方法是通过在配置文件中配置这些参数以供应用程序使用,但这意味着用户必须将这两个参数手动插入到配置文件中.

One way to do that is by configuring these parameters in a config file for the app to use, But this means the user has to manually insert these two parameters to the config file.

我的问题是: 有没有办法以编程方式在我的代码中检索这些参数中的至少一个,以便至少用户将只需要插入一个参数,而不是两个?我的目标是使用户的生活更轻松.

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.

推荐答案

我的问题是:是否可以通过编程方式在我的代码中至少检索这些参数之一,以便至少用户只需插入一个参数,而不插入两个参数?我的目标是使用户的生活更轻松.

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.

根据您的描述,建议您使用 azure rest api 使用帐户名获取存储帐户密钥.

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

此外,我们还可以使用rest api列出所有资源组的存储帐户名称,但是仍然需要将资源组名称作为参数发送到Azure管理url.

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.

您可以按照以下网址将请求发送到Azure管理:

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:

注意:使用这种方法,首先需要创建一个Azure Active Directory应用程序和服务主体.生成服务主体后,您可以获得应用程序ID,访问密钥和人才ID.更多详细信息,您可以参考此

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.

代码:

    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);
    }

结果:

这篇关于以编程方式获取Azure存储帐户属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆