Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically get Azure storage account properties

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

This is my code:

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

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.

like image 745
N.avraham Avatar asked Oct 30 '22 06:10

N.avraham


1 Answers

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:enter image description here

like image 168
Brando Zhang Avatar answered Nov 09 '22 16:11

Brando Zhang