Search code examples
azure-webjobsazure-webjobssdk

WebJobs storage with Managed Identity


By default WebJobs requires to specify Azure Storage account using AzureWebJobsStorage connection string.

But I already have access to my storage with Managed Identity:

AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://storage.azure.com/");
StorageCredentials storageCredentials = new StorageCredentials(new TokenCredential(accessToken));
CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(storageCredentials, "mystorageaccount", "core.windows.net", true);

Can I configure WebJobs to use this cloudStorageAccount instead of AzureWebJobsStorage connection string?


Solution

  • Can I configure WebJobs to use this cloudStorageAccount instead of AzureWebJobsStorage connection string?

    Yes, you could use cloudStorageAccount to get blob account and do some operation on blobs. However, you still need to provide AzureWebJobsDashboard and AzureWebJobsStorage when you use Webjob. Because they are not only connectionstring, they are also the log path.

    In my test, I set AzureWebJobsStorage value with storage1 connection and in code I get storage2 account and it works.

    AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
    string accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://storage.azure.com/").Result;
    StorageCredentials storageCredentials = new StorageCredentials(new TokenCredential(accessToken));
    CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(storageCredentials, "storage2", "core.windows.net", true);
    CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
    CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("mycontainer");
    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference("hello.txt");
    cloudBlockBlob.UploadTextAsync("aaaaaaaa").Wait();
    

    For more details about assign role and get access token you could refer to this article.