Created
November 21, 2019 12:50
-
-
Save mivano/18e5c7ef95664801ca0ffe7e65e7883c to your computer and use it in GitHub Desktop.
Get cosmosdb connectionstring in Azure Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
builder.Services.PostConfigure<CosmosDBOptions>(options => | |
{ | |
if (string.IsNullOrWhiteSpace(managedIdentity)) | |
{ | |
// When local, read it from the config. Most likely from the not checked in local.settings.json file | |
options.ConnectionString = configuration.GetValue<string>(CosmosDbConfig.ConnectionStringSetting); | |
} | |
else | |
{ | |
// If we do have a managed identity, we can fetch the keys from Azure | |
var task = azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/"); | |
string token = task.Result; | |
var subscriptionId = configuration.GetValue<string>("cosmosDb:subscriptionId"); | |
var tenantId = configuration.GetValue<string>("cosmosDb:tenantId"); | |
var cosmosDbName = configuration.GetValue<string>("cosmosDb:dbName"); | |
var resourceGroup = configuration.GetValue<string>("cosmosDb:resourceGroup"); | |
var tokenCredentials = new TokenCredentials(token); | |
var azureCredentials = new AzureCredentials( | |
tokenCredentials, | |
tokenCredentials, | |
tenantId, | |
AzureEnvironment.AzureGlobalCloud); | |
var client = RestClient | |
.Configure() | |
.WithEnvironment(AzureEnvironment.AzureGlobalCloud) | |
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) | |
.WithCredentials(azureCredentials) | |
.Build(); | |
var azure = Azure | |
.Authenticate(client, tenantId) | |
.WithSubscription(subscriptionId); | |
var cosmosDbAccounts = azure.CosmosDBAccounts; | |
var readWriteKeys = cosmosDbAccounts.ListKeysAsync(resourceGroup, cosmosDbName); | |
var keys = readWriteKeys.Result; | |
options.ConnectionString = | |
$"AccountEndpoint=https://{cosmosDbName}.documents.azure.com:443/;AccountKey={keys.PrimaryMasterKey};"; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment