Azure  

How to retrieve configuration settings from Azure App Configuration using .NET Client Library?

In this article, let’s create a .NET console application to retrieve configuration settings from Azure App Configuration using the .NET client library. Azure CLI is used to create an Azure app configuration resource and to store configuration settings. Configuration values are retrieved using ConfigurationBuilder. After this exercise, one will be able to organize the settings with hierarchical keys and application authentication to access Microsoft cloud-based configuration data.

The following tasks are performed:

  • Create Azure App Configuration resources using the Azure CLI.

  • Assign role to Microsoft Entra (Azure AD) user

  • Add configuration information using Azure CLI.

  • Retrieve configuration details using the .NET Client Library.

  • Sign in to Azure and run the application.

  • Clean up resources.

Create an Azure App Configuration resource using Azure CLI

The first basic task is to create and prepare Azure app configuration resources. Azure CLI (Azure Cloud Shell) is used to create the required resources. Azure CLI is a free Bash shell that can be run directly within the Azure portal. That is preinstalled and configured within the account. Perform the steps below one by one to achieve this. These steps are almost the same except for a few changes, as mentioned in the previous article How to Create and Retrieve Secrets from Azure Key Vault using Azure CLI?

Use Azure CLI (Azure Cloud Shell)

It is a free Bash shell which can be run directly within the Azure portal. It is preinstalled and configured within an account.

  • Click Cloud Shell button on the menu bar at the top right side of the Azure portal.

    Cloud Shell button
  • It will launch an interactive shell which can be used to run the steps outlined in this article. Select a Bash environment. To use code editor In cloud shell toolbar go to Settings menu and then select Go to Classic version.

    Cloud Shell Bash

Create resource group

Resource group is a logical container used to hold related resources. In it include the resources which you want to manage as a group. App configuration resource belongs to this resource group. Create it using az group create command.

az group create \ 
     --name myResourceGroup1 \ 
     --location eastus2 

eastus2 is location code instead of it one can use their nearest region location.

Register Namespaces

Microsoft.AppConfiguration namespace is required to registered for the application. az provider register command is used to register namespaces as like below. This command will take few minutes to complete the registration process.

az provider register --namespace Microsoft.AppConfiguration

Create Azure App Configuration resource

az appconfig create command is used as mentioned below to create an Azure app configuration resource. It will take few minutes to complete the process.

az appconfig create 
     --location eastus2 \ 
     --name appConfigName1 \
     --resource-group myResourceGroup1\ 
     --sku Free

Assign role to Microsoft Entra (Azure AD) user

It is important to assign roles to Microsoft Entra (Azure AD) user name. Roles will define what access and permissions a user has within an organization’s Microsoft cloud environment. Roles determine what resources and actions a user can perform. “App Configuration Data Reader” role is to be assigned to Microsoft Entra user. It gives permissions to retrieve configuration settings to user account. One by one perform below steps in Azure CLI.

Retrieve userPrincipalName

First, retrieve userPrincipalName from account as mentioned in following command. It retrieves the information about currently authenticated user including their UPN and represents that who the role will be assigned to.

userPrincipal=$(az rest 
     --method GET 
     --url https://graph.microsoft.com/v1.0/me \
     --headers 'Content-Type=application/json' \
     --query userPrincipalName 
     --output tsv)

Retrieve resource ID

Second, get the resource ID of key vault using below command. This will be used in next step to set scope for role assignment. Resource ID sets scope for role assignment to specific key vault.

resourceID=$(az appconfig show \
     --resource-group myResourceGroup1 \
     --name appConfigName1\ 
     --query id \
     --output tsv)

Create and assign App Configuration Data Reader role

Finally, create and assign App Configuration Data Reader role using az role assignment create command. This will give permissions to manage next routines. userPrincipal and resourceID variables are created in first and second steps which are used in this command to retrieve actual value at command execution time.

az role assignment create \
     --assignee $userPrincipal\
     --role "App Configuration Data Reader" \
     --scope $resourceID

Now, required basic resources are deployed and ready to use in console application.

Add configuration information using Azure CLI

Let’s add connection sting into App configuration using Azure CLI and than retrieve it using .NET SDK. az appconfig kv set command is used to create or update the key-value pair in Azure App Configuration store. Following example sets configuration value for the development environment.

az appconfig kv set \
     --name appConfigName1 \
     --key Dev:conStruction \
     --value "Under Construction"\
     --yes

Output: Command execution will return some JSON and last line will contain the value in plain text.

"value": "Under Construction"

Here, specified part Dev:conStruction represents the hierarchical key name. It is also known as namespaced key.

  • Dev: First part serves as prefix to organize configuration settings for environment such as Development, Staging, or Production.

  • : (colon): Second part acts as delimiter to create a hierarchical structure in key name. This is common practice for organizing the application setting.

  • conStruction: Third part represents particular configuration setting name within Dev hierarchy.

Retrieve configuration details using .NET Client Library

Next step is to set-up the .NET console application to retrieve configuration information using .NET Client Library. Perform the following steps one by one using Cloud Shell to achieve this.

.NET Project Setup

Set up one console application to add and fetch secrets using .NET Client Library.

  • Create project directory and change to that directory. First create a directory for the project using below command and move to that directory.

mkdir appconfig1
cd appconfig1
  • Create .NET console application to add and fetch secrets through it. dotnet new console command is used to create a .NET console app.

dotnet new console
  • Install Packages - run dotnet add package command to add Azure.Identity and Microsoft.Extensions.Configuration.AzureAppConfiguration packages in project to use the SDK. Microsoft.Extensions.Configuration.AzureAppConfiguration is .NET provider library which is used to retrieve the configuration settings from Azure App Configuration through .NET application.

dotnet add package Azure.Identity
dotnet add package Microsoft.Extensions.Configuration.AzureAppConfiguration

Application Code

Add the below code into the project and replace template code in Program.cs file by using editor in Cloud Shell. Here by with this article a complete code of Program.cs file is attached.

  • Application editing - open Program.cs file to edit it in the Azure CLI using code command.

code Program.cs
  • Code replacing - replace existing code of Program.cs with the below code.

using Azure.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;

//Set endpoint for Azure App configuration

//Replace APP_CONFIG_NAME with actual app configuration service name
string endPoint = "https://APP_CONFIG_NAME.azconfig.io";

//Authentication method configuration
DefaultAzureCredentialOptions credentialOptions = new()
{
     ExcludeEnvironmentCredential = true,
     ExcludeManagedIdentityCredential = true
};

//Create configuration builder
var configurationBuilder = new ConfigurationBuilder();

//Add Azure app configuration
configurationBuilder.AddAzureAppConfiguration(options =>
{
     options.Connect(new Uri(endPoint), new DefaultAzureCredential(credentialOptions));
});

//Build configuration object
try
{
     var configBuild = configurationBuilder.Build();
     
     //Get and print configuration value using key
     Console.WriteLine(configBuild["Dev:conStruction"]);
     Console.ReadLine();
}
catch (Exception ex)
{
     Console.WriteLine($"Error message: {ex.Message}");
     Console.ReadLine();
}

Here,

  • Replace APP_CONFIG_NAME with actual app configuration service name.

  • ConfigurationBuilder is used to Create configuration builder and to add Azure app configuration.

  • Build() method get the configuration value using key.

  • Save & Close - Press ctrl + s to save your changes and continue.

Sign into Azure and Run application

Now application is ready to run. In Azure CLI one by one execute the below commands to run the app and verify the result outputs.

  • Sign in - az login command used for sign in. Sign into Azure is mandatory even though cloud shell session already may authenticated.

az login
  • Run application - dotnet run command used to start console application. Application will display value of connectionString.

dotnet run
  • Output - It shows value of connection string which is assigned to the Dev:conStruction setting in above section i.e. Under Construction

Clean up resources

After finish the exercise it’s recommended to delete cloud resources are being created to avoid the unnecessary resource usage and any future costs. Deleting a resource group will delete all resources contained within it. Perform following steps one by one in to Azure Portal to achieve this:

  • Navigate to resource group which is being created here and view it’s contents.

  • Delete resource group selection from the toolbar.

  • Choose resource group name and then follow next directions to delete resource group and all the resources it contains.

One can also clean up resources using Azure CLI as following:

Delete role assignment - az role assignment delete command is used to remove role assignment.

az role assignment delete \
     --role "App Configuration Data Reader" \
     --scope $resourceID

Delete app configuration store - az appconfig delete command is used to remove app configuration store.

az appconfig delete \
     --name appConfigName1\
     --resource-group myResourceGroup1 

Delete resource group - az group delete command is used to remove resource group, container registry, and container images.

az group delete \
     --name myResourceGroup1

Summary

Here, a complete process flow is described to retrieve configuration settings from Azure App Configuration using .NET Client Library. A role is assigned to Microsoft Entra (Azure AD) user name. ConfigurationBuilder is used to retrieved configuration values. Hierarchical keys are set and application authenticated to access Microsoft cloud based configuration data. Finally, resources are cleaned up. A complete code of Program.cs file is attached with this article . Following it the list of key commands used in this article:

  • Create resource group: az group create

  • Register Namespaces: az provider register

  • Create Azure App Configuration resource: az appconfig create

  • Create and assign App Configuration Data Reader role: az role assignment create

  • Add configuration information: az appconfig kv set

  • Create .NET console application: dotnet new console

  • Add packages: dotnet add package

  • Run application: dotnet run

  • Delete role assignment: az role assignment delete

  • Delete app configuration store: az appconfig delete

  • Delete resource group: az group delete