0% found this document useful (0 votes)
177 views

Azure App Configuration

This document provides best practices for using Azure App Configuration including grouping keys using prefixes and labels, stacking configurations, bootstrapping access using managed identities instead of connection strings, and providing access to apps and functions.

Uploaded by

Qw3rty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
177 views

Azure App Configuration

This document provides best practices for using Azure App Configuration including grouping keys using prefixes and labels, stacking configurations, bootstrapping access using managed identities instead of connection strings, and providing access to apps and functions.

Uploaded by

Qw3rty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 213

Contents

Azure App Configuration documentation


Overview
About Azure App Configuration
Best practices
FAQ
Quickstarts
Configuration
ASP.NET Core
.NET Core
.NET Framework
Azure Functions in .NET Core
Java Spring
ARM template
Feature management
ASP.NET Core
.NET Framework
Azure Functions in .NET Core
Java Spring
Tutorials
Enable dynamic configuration
ASP.NET Core
.NET Core
.NET Framework
Azure Functions
Spring Boot
Use feature flags
.NET Core
Spring Boot
Manage feature flags
Use Key Vault references
ASP.NET Core
Spring Boot
CI/CD pipeline integration
Push using Azure Pipelines
Push using GitHub Actions
Build project using exported configuration
Integrate with Kubernetes deployment using Helm
Samples
Azure CLI
Concepts
Keys and values
Point-in-time snapshot
Feature management
Event handling
Security
Encrypt using customer-managed keys
Secure your config store using Private Endpoints
Enable access using Azure Active Directory
Assign an Azure Managed Identity
High availability
Resiliency and disaster recovery
How-to guides
Enable a feature for a subset of users
Use labels for per-environment configuration
Import or export configuration data
Use JSON content-type for key-values
Route events to a custom endpoint
Backup configuration store automatically
Use managed identities to access App Configuration
Reference
Configuration
Azure CLI
.NET Core provider
.NET Framework builder
Azure SDK for .NET
Java Spring provider
Azure SDK for Java
Azure SDK for Python
Azure SDK for JavaScript
REST API
Feature management
.NET Core library
.NET Core filter library
Config store management
REST API
PowerShell
Terraform
Azure Policy built-ins
Resources
Pricing
Videos
Getting started with App Configuration
Feature management
Making centralized configuration easy
Azure App Configuration on Cloud Native Show
Rolling out new features
Provide product feedback
What is Azure App Configuration?
9/22/2020 • 2 minutes to read • Edit Online

Azure App Configuration provides a service to centrally manage application settings and feature flags. Modern
programs, especially programs running in a cloud, generally have many components that are distributed in nature.
Spreading configuration settings across these components can lead to hard-to-troubleshoot errors during an
application deployment. Use App Configuration to store all the settings for your application and secure their
accesses in one place.

Why use App Configuration?


Cloud-based applications often run on multiple virtual machines or containers in multiple regions and use multiple
external services. Creating a robust and scalable application in a distributed environment presents a significant
challenge.
Various programming methodologies help developers deal with the increasing complexity of building applications.
For example, the Twelve-Factor App describes many well-tested architectural patterns and best practices for use
with cloud applications. One key recommendation from this guide is to separate configuration from code. An
application’s configuration settings should be kept external to its executable and read in from its runtime
environment or an external source.
While any application can make use of App Configuration, the following examples are the types of application that
benefit from the use of it:
Microservices based on Azure Kubernetes Service, Azure Service Fabric, or other containerized apps deployed in
one or more geographies
Serverless apps, which include Azure Functions or other event-driven stateless compute apps
Continuous deployment pipeline
App Configuration offers the following benefits:
A fully managed service that can be set up in minutes
Flexible key representations and mappings
Tagging with labels
Point-in-time replay of settings
Dedicated UI for feature flag management
Comparison of two sets of configurations on custom-defined dimensions
Enhanced security through Azure-managed identities
Encryption of sensitive information at rest and in transit
Native integration with popular frameworks
App Configuration complements Azure Key Vault, which is used to store application secrets. App Configuration
makes it easier to implement the following scenarios:
Centralize management and distribution of hierarchical configuration data for different environments and
geographies
Dynamically change application settings without the need to redeploy or restart an application
Control feature availability in real-time

Use App Configuration


The easiest way to add an App Configuration store to your application is through a client library provided by
Microsoft. The following methods are available to connect with your application, depending on your chosen
language and framework

P RO GRA M M IN G L A N GUA GE A N D F RA M EW O RK H O W TO C O N N EC T

.NET Core and ASP.NET Core App Configuration provider for .NET Core

.NET Framework and ASP.NET App Configuration builder for .NET

Java Spring App Configuration client for Spring Cloud

Others App Configuration REST API

Next steps
ASP.NET Core quickstart
.NET Core quickstart
.NET Framework quickstart
Azure Functions quickstart
Java Spring quickstart
ASP.NET Core feature flag quickstart
Spring Boot feature flag quickstart
Azure App Configuration best practices
9/22/2020 • 4 minutes to read • Edit Online

This article discusses common patterns and best practices when you're using Azure App Configuration.

Key groupings
App Configuration provides two options for organizing keys:
Key prefixes
Labels
You can use either one or both options to group your keys.
Key prefixes are the beginning parts of keys. You can logically group a set of keys by using the same prefix in their
names. Prefixes can contain multiple components connected by a delimiter, such as / , similar to a URL path, to
form a namespace. Such hierarchies are useful when you're storing keys for many applications, component
services, and environments in one App Configuration store.
An important thing to keep in mind is that keys are what your application code references to retrieve the values of
the corresponding settings. Keys shouldn't change, or else you'll have to modify your code each time that happens.
Labels are an attribute on keys. They're used to create variants of a key. For example, you can assign labels to
multiple versions of a key. A version might be an iteration, an environment, or some other contextual information.
Your application can request an entirely different set of key values by specifying another label. As a result, all key
references remain unchanged in your code.

Key-value compositions
App Configuration treats all keys stored with it as independent entities. App Configuration doesn't attempt to infer
any relationship between keys or to inherit key values based on their hierarchy. You can aggregate multiple sets of
keys, however, by using labels coupled with proper configuration stacking in your application code.
Let's look at an example. Suppose you have a setting named Asset1 , whose value might vary based on the
development environment. You create a key named "Asset1" with an empty label and a label named
"Development". In the first label, you put the default value for Asset1 , and you put a specific value for
"Development" in the latter.
In your code, you first retrieve the key values without any labels, and then you retrieve the same set of key values a
second time with the "Development" label. When you retrieve the values the second time, the previous values of
the keys are overwritten. The .NET Core configuration system allows you to "stack" multiple sets of configuration
data on top of each other. If a key exists in more than one set, the last set that contains it is used. With a modern
programming framework, such as .NET Core, you get this stacking capability for free if you use a native
configuration provider to access App Configuration. The following code snippet shows how you can implement
stacking in a .NET Core application:
// Augment the ConfigurationBuilder with Azure App Configuration
// Pull the connection string from an environment variable
configBuilder.AddAzureAppConfiguration(options => {
options.Connect(configuration["connection_string"])
.Select(KeyFilter.Any, LabelFilter.Null)
.Select(KeyFilter.Any, "Development");
});

Use labels to enable different configurations for different environments provides a complete example.

App Configuration bootstrap


To access an App Configuration store, you can use its connection string, which is available in the Azure portal.
Because connection strings contain credential information, they're considered secrets. These secrets need to be
stored in Azure Key Vault, and your code must authenticate to Key Vault to retrieve them.
A better option is to use the managed identities feature in Azure Active Directory. With managed identities, you
need only the App Configuration endpoint URL to bootstrap access to your App Configuration store. You can
embed the URL in your application code (for example, in the appsettings.json file). See Integrate with Azure
managed identities for details.

App or function access to App Configuration


You can provide access to App Configuration for web apps or functions by using any of the following methods:
Through the Azure portal, enter the connection string to your App Configuration store in the Application
settings of App Service.
Store the connection string to your App Configuration store in Key Vault and reference it from App Service.
Use Azure managed identities to access the App Configuration store. For more information, see Integrate with
Azure managed identities.
Push configuration from App Configuration to App Service. App Configuration provides an export function (in
Azure portal and the Azure CLI) that sends data directly into App Service. With this method, you don't need to
change the application code at all.

Reduce requests made to App Configuration


Excessive requests to App Configuration can result in throttling or overage charges. To reduce the number of
requests made:
Increase the refresh timeout, especially if your configuration values do not change frequently. Specify a new
refresh timeout using the SetCacheExpiration method.
Watch a single sentinel key, rather than watching individual keys. Refresh all configuration only if the
sentinel key changes. See Use dynamic configuration in an ASP.NET Core app for an example.
Use Azure Event Grid to receive notifications when configuration changes, rather than constantly polling for
any changes. For more information, see Route Azure App Configuration events to a web endpoint

Importing configuration data into App Configuration


App Configuration offers the option to bulk import your configuration settings from your current configuration
files using either the Azure portal or CLI. You can also use the same options to export values from App
Configuration, for example between related stores. If you’d like to set up an ongoing sync with your GitHub repo,
you can use our GitHub Action so that you can continue using your existing source control practices while getting
the benefits of App Configuration.
Multi-region deployment in App Configuration
App Configuration is regional service. For applications with different configurations per region, storing these
configurations in one instance can create a single point of failure. Deploying one App Configuration instances per
region across multiple regions may be a better option. It can help with regional disaster recovery, performance, and
security siloing. Configuring by region also improves latency and uses separated throttling quotas, since throttling
is per instance. To apply disaster recovery mitigation, you can use multiple configuration stores.

Next steps
Keys and values
Azure App Configuration FAQ
9/22/2020 • 5 minutes to read • Edit Online

This article answers frequently asked questions about Azure App Configuration.

How is App Configuration different from Azure Key Vault?


App Configuration helps developers manage application settings and control feature availability. It aims to simplify
many of the tasks of working with complex configuration data.
App Configuration supports:
Hierarchical namespaces
Labeling
Extensive queries
Batch retrieval
Specialized management operations
A feature-management user interface
App Configuration complements Key Vault, and the two should be used side by side in most application
deployments.

Should I store secrets in App Configuration?


Although App Configuration provides hardened security, Key Vault is still the best place for storing application
secrets. Key Vault provides hardware-level encryption, granular access policies, and management operations such
as certificate rotation.
You can create App Configuration values that reference secrets stored in Key Vault. For more information, see Use
Key Vault references in an ASP.NET Core app.

Does App Configuration encrypt my data?


Yes. App Configuration encrypts all key values it holds, and it encrypts network communication. Key names and
labels are used as indexes for retrieving configuration data and aren't encrypted.

How is App Configuration different from Azure App Service settings?


Azure App Service allows you to define app settings for each App Service instance. These settings are passed as
environment variables to the application code. You can associate a setting with a specific deployment slot, if you
want. For more information, see Configure app settings.
In contrast, Azure App Configuration allows you to define settings that can be shared among multiple apps. This
includes apps running in App Service, as well as other platforms. Your application code accesses these settings
through the configuration providers for .NET and Java, through the Azure SDK, or directly via REST APIs.
You can also import and export settings between App Service and App Configuration. This capability allows you to
quickly set up a new App Configuration store based on existing App Service settings. You can also share
configuration with an existing app that relies on App Service settings.

Are there any size limitations on keys and values stored in App
Configuration?
There's a limit of 10 KB for a single key-value item.

How should I store configurations for multiple environments (test,


staging, production, and so on)?
You control who can access App Configuration at a per-store level. Use a separate store for each environment that
requires different permissions. This approach provides the best security isolation.
If you do not need security isolation between environments, you can use labels to differentiate between
configuration values. Use labels to enable different configurations for different environments provides a complete
example.

What are the recommended ways to use App Configuration?


See best practices.

How much does App Configuration cost?


There are two pricing tiers:
Free tier
Standard tier.
If you created a store prior to the introduction of the Standard tier, it automatically moved to the Free tier upon
general availability. You can choose to upgrade to the Standard tier or remain on the Free tier.
You can't downgrade a store from the Standard tier to the Free tier. You can create a new store in the Free tier and
then import configuration data into that store.

Which App Configuration tier should I use?


Both App Configuration tiers offer core functionality, including config settings, feature flags, Key Vault references,
basic management operations, metrics, and logs.
The following are considerations for choosing a tier.
Resources per subscription : A resource consists of a single configuration store. Each subscription is
limited to one configuration store in the free tier. Subscriptions can have an unlimited number of
configuration stores in the standard tier.
Storage per resource : In the free tier, each configuration store is limited to 10 MB of storage. In the
standard tier, each configuration store can use up to 1 GB of storage.
Key histor y : App Configuration stores a history of all changes made to keys. In the free tier, this history is
stored for seven days. In the standard tier, this history is stored for 30 days.
Requests per day : Free tier stores are limited to 1,000 requests per day. Once a store reaches 1,000
requests, it will return HTTP status code 429 for all requests until midnight UTC.
For standard tier stores, the first 200,000 requests each day are included in the daily charge. Additional
requests are billed as overage.
Ser vice level agreement : The standard tier has an SLA of 99.9% availability. The free tier doesn't have an
SLA.
Security features : Both tiers include basic security functionality, including encryption with Microsoft-
managed keys, authentication via HMAC or Azure Active Directory, RBAC support, and managed identity. The
Standard tier offers more advanced security functionality, including Private Link support and encryption with
customer-managed keys.
Cost : Standard tier stores have a daily usage charge. There's also an overage charge for requests past the
daily allocation. There's no cost to use a free tier store.

Can I upgrade a store from the Free tier to the Standard tier? Can I
downgrade a store from the Standard tier to the Free tier?
You can upgrade from the Free tier to the Standard tier at any time.
You can't downgrade a store from the Standard tier to the Free tier. You can create a new store in the Free tier and
then import configuration data into that store.

Are there any limits on the number of requests made to App


Configuration?
Configuration stores in the Free tier are limited to 1,000 requests per day. Configuration stores in the Standard tier
may experience temporary throttling when the request rate exceeds 20,000 requests per hour.
When a store reaches its limit, it will return HTTP status code 429 for all requests made until the time period
expires. The retry-after-ms header in the response gives a suggested wait time (in milliseconds) before retrying
the request.
If your application regularly experiences HTTP status code 429 responses, consider redesigning it to reduce the
number of requests made. For more information, see Reduce requests made to App Configuration

My application receives HTTP status code 429 responses. Why?


You'll receive an HTTP status code 429 response under these circumstances:
Exceeding the daily request limit for a store in the Free tier.
Temporary throttling due to a high request rate for a store in the Standard tier.
Excessive bandwidth usage.
Attempting to create or modify a key when the storage quote is exceeded.
Check the body of the 429 response for the specific reason why the request failed.

How can I receive announcements on new releases and other


information related to App Configuration?
Subscribe to our GitHub announcements repo.

How can I report an issue or give a suggestion?


You can reach us directly on GitHub.

Next steps
About Azure App Configuration
Quickstart: Create an ASP.NET Core app with Azure
App Configuration
9/22/2020 • 7 minutes to read • Edit Online

In this quickstart, you will use Azure App Configuration to centralize storage and management of application
settings for an ASP.NET Core application. ASP.NET Core builds a single key-value-based configuration object using
settings from one or more data sources specified by an application. These data sources are known as
configuration providers. Because App Configuration's .NET Core client is implemented as a configuration provider,
the service appears like another data source.

Prerequisites
Azure subscription - create one for free
.NET Core SDK

TIP
The Azure Cloud Shell is a free interactive shell that you can use to run the command line instructions in this article. It has
common Azure tools preinstalled, including the .NET Core SDK. If you are logged in to your Azure subscription, launch your
Azure Cloud Shell from shell.azure.com. You can learn more about Azure Cloud Shell by reading our documentation

Create an App Configuration store


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and
select Enter.
2. Select App Configuration from the search results, and then select Create .

3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N


SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the
same time by deleting the resource
group. For more information, see
Use resource groups to manage
your Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted.
For the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.

4. Select Create . The deployment might take a few minutes.


5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.
6. Select Configuration Explorer > Create > Key-value to add the following key-value pairs:

K EY VA L UE

TestApp:Settings:BackgroundColor White

TestApp:Settings:FontSize 24

TestApp:Settings:FontColor Black

TestApp:Settings:Message Data from Azure App Configuration

Leave Label and Content Type empty for now. Select Apply .

Create an ASP.NET Core web app


Use the .NET Core command-line interface (CLI) to create a new ASP.NET Core MVC web app project. The Azure
Cloud Shell provides these tools for you. They are also available across the Windows, macOS, and Linux
platforms.
1. Create a new folder for your project. For this quickstart, name it TestAppConfig.
2. In the new folder, run the following command to create a new ASP.NET Core MVC web app project:

dotnet new mvc --no-https

Add Secret Manager


To use Secret Manager, add a UserSecretsId element to your .csproj file.
1. Open the .csproj file.
2. Add a UserSecretsId element as shown here. You can use the same GUID, or you can replace this value
with your own.

IMPORTANT
CreateHostBuilder replaces CreateWebHostBuilder in .NET Core 3.0. Select the correct syntax based on your
environment.

.NET Core 2.x


.NET Core 3.x
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<UserSecretsId>79a3edd0-2092-40a2-a04d-dcb46d5ca9ed</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2"
PrivateAssets="All" />
</ItemGroup>

</Project>

3. Save the .csproj file.


The Secret Manager tool stores sensitive data for development work outside of your project tree. This approach
helps prevent the accidental sharing of app secrets within source code.

TIP
To learn more about Secret Manager, please see Safe storage of app secrets in development in ASP.NET Core

Connect to an App Configuration store


1. Add a reference to the Microsoft.Azure.AppConfiguration.AspNetCore NuGet package by running the
following command:

dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore

2. Run the following command to restore packages for your project:

dotnet restore

3. Add a secret named ConnectionStrings:AppConfig to Secret Manager.


This secret contains the connection string to access your App Configuration store. Replace the value in the
following command with the connection string for your App Configuration store. You can find the
connection string under Access Keys in the Azure portal.
This command must be executed in the same directory as the .csproj file.

dotnet user-secrets set ConnectionStrings:AppConfig <your_connection_string>

IMPORTANT
Some shells will truncate the connection string unless it is enclosed in quotes. Ensure that the output of the
dotnet user-secrets command shows the entire connection string. If it doesn't, rerun the command, enclosing
the connection string in quotes.

Secret Manager is used only to test the web app locally. When the app is deployed to Azure App Service,
for example, you use the Connection Strings application setting in App Service instead of Secret
Manager to store the connection string.
Access this secret using the configuration API. A colon (:) works in the configuration name with the
configuration API on all supported platforms. See Configuration by environment.
4. Open Program.cs, and add a reference to the .NET Core App Configuration provider.

using Microsoft.Extensions.Configuration.AzureAppConfiguration;

5. Update the CreateWebHostBuildermethod to use App Configuration by calling the


config.AddAzureAppConfiguration() method.

IMPORTANT
CreateHostBuilder replaces CreateWebHostBuilder in .NET Core 3.0. Select the correct syntax based on your
environment.

.NET Core 2.x


.NET Core 3.x

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(settings["ConnectionStrings:AppConfig"]);
})
.UseStartup<Startup>();

6. Navigate to /Views/Home and open Index.cshtml. Replace its content with the following code:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<style>
body {
background-color: @Configuration["TestApp:Settings:BackgroundColor"]
}
h1 {
color: @Configuration["TestApp:Settings:FontColor"];
font-size: @Configuration["TestApp:Settings:FontSize"]px;
}
</style>

<h1>@Configuration["TestApp:Settings:Message"]</h1>

7. Navigate to /Views/Shared and open _Layout.cshtml. Replace its content with the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - hello_world</title>

<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />


<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<div class="container body-content">
@RenderBody()
</div>

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>

@RenderSection("Scripts", required: false)


</body>
</html>

Build and run the app locally


1. To build the app using the .NET Core CLI, navigate to the root directory of your application and run the
following command in the command shell:

dotnet build

2. After the build successfully completes, run the following command to run the web app locally:

dotnet run

3. If you're working on your local machine, use a browser to navigate to http://localhost:5000 . This is the
default URL for the web app hosted locally.
If you're working in the Azure Cloud Shell, select the Web Preview button followed by Configure.

When prompted to configure the port for preview, enter '5000' and select Open and browse. The web page will
read "Data from Azure App Configuration."
Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside
a resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this quickstart, you created a new App Configuration store and used it with an ASP.NET Core web app via the
App Configuration provider. To learn how to configure your ASP.NET Core app to dynamically refresh
configuration settings, continue to the next tutorial.
Enable dynamic configuration
Quickstart: Create a .NET Core app with App
Configuration
9/22/2020 • 4 minutes to read • Edit Online

In this quickstart, you incorporate Azure App Configuration into a .NET Core console app to centralize storage and
management of application settings separate from your code.

Prerequisites
Azure subscription - create one for free
.NET Core SDK - also available in the Azure Cloud Shell.

Create an App Configuration store


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and
select Enter.

2. Select App Configuration from the search results, and then select Create .
3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the
same time by deleting the resource
group. For more information, see Use
resource groups to manage your
Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted. For
the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.
4. Select Create . The deployment might take a few minutes.
5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.
6. Select Configuration Explorer > Create > Key-value to add the following key-value pairs:

K EY VA L UE

TestApp:Settings:Message Data from Azure App Configuration

Leave Label and Content Type empty for now.


7. Select Apply .

Create a .NET Core console app


You use the .NET Core command-line interface (CLI) to create a new .NET Core console app project. The advantage
of using the .NET Core CLI over Visual Studio is that it's available across the Windows, macOS, and Linux platforms.
Alternatively, use the preinstalled tools available in the Azure Cloud Shell.
1. Create a new folder for your project.
2. In the new folder, run the following command to create a new .NET Core console app project:

dotnet new console

Connect to an App Configuration store


1. Add a reference to the Microsoft.Extensions.Configuration.AzureAppConfiguration NuGet package by
running the following command:

dotnet add package Microsoft.Extensions.Configuration.AzureAppConfiguration

2. Run the following command to restore packages for your project:


dotnet restore

3. Open Program.cs, and add a reference to the .NET Core App Configuration provider.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;

4. Update the Main method to use App Configuration by calling the builder.AddAzureAppConfiguration()
method.

static void Main(string[] args)


{
var builder = new ConfigurationBuilder();
builder.AddAzureAppConfiguration(Environment.GetEnvironmentVariable("ConnectionString"));

var config = builder.Build();


Console.WriteLine(config["TestApp:Settings:Message"] ?? "Hello world!");
}

Build and run the app locally


1. Set an environment variable named ConnectionString , and set it to the access key to your App
Configuration store. At the command line, run the following command:

setx ConnectionString "connection-string-of-your-app-configuration-store"

If you use Windows PowerShell, run the following command:

$Env:ConnectionString = "connection-string-of-your-app-configuration-store"

If you use macOS or Linux, run the following command:

export ConnectionString='connection-string-of-your-app-configuration-store'

Restart the command prompt to allow the change to take effect. Print out the value of the environment
variable to validate that it is set properly.
2. Run the following command to build the console app:

dotnet build

3. After the build successfully completes, run the following command to run the app locally:

dotnet run

Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.
IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this quickstart, you created a new App Configuration store and used it with a .NET Core console app via the App
Configuration provider. To learn how to configure your .NET Core app to dynamically refresh configuration
settings, continue to the next tutorial.
Enable dynamic configuration
Quickstart: Create a .NET Framework app with Azure
App Configuration
9/22/2020 • 4 minutes to read • Edit Online

In this quickstart, you incorporate Azure App Configuration into a .NET Framework-based console app to centralize
storage and management of application settings separate from your code.

Prerequisites
Azure subscription - create one for free
Visual Studio 2019
.NET Framework 4.7.2

Create an App Configuration store


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and
select Enter.

2. Select App Configuration from the search results, and then select Create .
3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the
same time by deleting the resource
group. For more information, see Use
resource groups to manage your
Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted. For
the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.
4. Select Create . The deployment might take a few minutes.
5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.
6. Select Configuration Explorer > Create > Key-value to add the following key-value pairs:

K EY VA L UE

TestApp:Settings:Message Data from Azure App Configuration

Leave Label and Content Type empty for now.


7. Select Apply .

Create a .NET console app


1. Start Visual Studio, and select File > New > Project .
2. In Create a new project , filter on the Console project type and click on Console App (.NET
Framework) . Select Next .
3. In Configure your new project , enter a project name. Under Framework , select .NET Framework 4.7.1
or higher. Select Create .

Connect to an App Configuration store


1. Right-click your project, and select Manage NuGet Packages . On the Browse tab, search and add the
following NuGet packages to your project.

Microsoft.Configuration.ConfigurationBuilders.AzureAppConfiguration 1.0.0 or later


Microsoft.Configuration.ConfigurationBuilders.Environment 2.0.0 or later
System.Configuration.ConfigurationManager version 4.6.0 or later

2. Update the App.config file of your project as follows:


<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection,
System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
restartOnExternalChanges="false" requirePermission="false" />
</configSections>

<configBuilders>
<builders>
<add name="MyConfigStore" mode="Greedy" connectionString="${ConnectionString}"
type="Microsoft.Configuration.ConfigurationBuilders.AzureAppConfigurationBuilder,
Microsoft.Configuration.ConfigurationBuilders.AzureAppConfiguration" />
<add name="Environment" mode="Greedy"
type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.Environment" />
</builders>
</configBuilders>

<appSettings configBuilders="Environment,MyConfigStore">
<add key="AppName" value="Console App Demo" />
<add key="ConnectionString" value ="Set via an environment variable - for example, dev, test,
staging, or production connection string." />
</appSettings>

The connection string of your App Configuration store is read from the environment variable
ConnectionString . Add the Environment configuration builder before the MyConfigStore in the
configBuilders property of the appSettings section.

3. Open Program.cs, and update the Main method to use App Configuration by calling ConfigurationManager .

static void Main(string[] args)


{
string message = System.Configuration.ConfigurationManager.AppSettings["TestApp:Settings:Message"];

Console.WriteLine(message);
}

Build and run the app locally


1. Set an environment variable named ConnectionString to the connection string of your App Configuration
store. If you use the Windows command prompt, run the following command:

setx ConnectionString "connection-string-of-your-app-configuration-store"

If you use Windows PowerShell, run the following command:

$Env:ConnectionString = "connection-string-of-your-app-configuration-store"

2. Restart Visual Studio to allow the change to take effect. Press Ctrl + F5 to build and run the console app.

Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.
IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this quickstart, you created a new App Configuration store and used it with a .NET Framework console app. The
value AppSettings of ConfigurationManager won't change after the application is started. The App Configuration
.NET Standard configuration provider library, however can also be used in a .NET Framework app. To learn how to
enable your .NET Framework app to dynamically refresh configuration settings, continue to the next tutorial.
Enable dynamic configuration
Quickstart: Create an Azure Functions app with
Azure App Configuration
9/22/2020 • 6 minutes to read • Edit Online

In this quickstart, you incorporate the Azure App Configuration service into an Azure Functions app to centralize
storage and management of all your application settings separate from your code.

Prerequisites
Azure subscription - create one for free
Visual Studio 2019 with the Azure development workload.
Azure Functions tools

Create an App Configuration store


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and
select Enter.

2. Select App Configuration from the search results, and then select Create .
3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the
same time by deleting the resource
group. For more information, see Use
resource groups to manage your
Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted. For
the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.
4. Select Create . The deployment might take a few minutes.
5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.
6. Select Configuration Explorer > + Create > Key-value to add the following key-value pairs:

K EY VA L UE

TestApp:Settings:Message Data from Azure App Configuration

Leave Label and Content Type empty for now.


7. Select Apply .

Create a Functions app


The Azure Functions project template in Visual Studio creates a project that you can publish to a function app in
Azure. You can use a function app to group functions as a logical unit for easier management, deployment, scaling,
and sharing of resources.
1. From the Visual Studio menu, select File > New > Project .
2. In Create a new project , enter functions in the search box, choose the Azure Functions template, and
then select Next .
3. In Configure your new project , enter a Project name for your project, and then select Create . The
function app name must be valid as a C# namespace, so don't use underscores, hyphens, or any other
nonalphanumeric characters.
4. For the Create a new Azure Functions application settings, use the values in the following table:

SET T IN G VA L UE DESC RIP T IO N


SET T IN G VA L UE DESC RIP T IO N

Functions runtime Azure Functions v3 This value creates a function project


(.NET Core) that uses the version 3.x runtime of
Azure Functions, which supports
.NET Core 3.x. Azure Functions 1.x
supports the .NET Framework. For
more information, see Azure
Functions runtime versions overview.

Function template HTTP trigger This value creates a function


triggered by an HTTP request.

Storage account Storage emulator Because an Azure Function requires a


(AzureWebJobsStorage) storage account, one is assigned or
created when you publish your
project to Azure. An HTTP trigger
doesn't use an Azure Storage account
connection string; all other trigger
types require a valid Azure Storage
account connection string.

Authorization level Anonymous The created function can be triggered


by any client without providing a key.
This authorization setting makes it
easy to test your new function. For
more information about keys and
authorization, see Authorization keys
and HTTP and webhook bindings.

Make sure you set the Authorization level to Anonymous . If you choose the default level of Function ,
you're required to present the function key in requests to access your function endpoint.
5. Select Create to create the function project and HTTP trigger function.
Connect to an App Configuration store
1. Right-click your project, and select Manage NuGet Packages . On the Browse tab, search for and add the
Microsoft.Extensions.Configuration.AzureAppConfiguration NuGet package to your project. If you can't find
it, select the Include prerelease check box.
2. Open Function1.cs, and add the namespaces of the .NET Core configuration and the App Configuration
configuration provider.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;

3. Add a static property named Configuration to create a singleton instance of IConfiguration . Then add a
static constructor to connect to App Configuration by calling AddAzureAppConfiguration() . This will load
configuration once at the application startup. The same configuration instance will be used for all Functions
calls later.

private static IConfiguration Configuration { set; get; }

static Function1()
{
var builder = new ConfigurationBuilder();
builder.AddAzureAppConfiguration(Environment.GetEnvironmentVariable("ConnectionString"));
Configuration = builder.Build();
}

4. Update the Run method to read values from the configuration.

public static async Task<IActionResult> Run(


[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger
log)
{
log.LogInformation("C# HTTP trigger function processed a request.");

string keyName = "TestApp:Settings:Message";


string message = Configuration[keyName];

return message != null


? (ActionResult)new OkObjectResult(message)
: new BadRequestObjectResult($"Please create a key-value with the key '{keyName}' in App
Configuration.");
}

Test the function locally


1. Set an environment variable named ConnectionString , and set it to the access key to your App
Configuration store. If you use the Windows command prompt, run the following command and restart the
command prompt to allow the change to take effect:

setx ConnectionString "connection-string-of-your-app-configuration-store"

If you use Windows PowerShell, run the following command:

$Env:ConnectionString = "connection-string-of-your-app-configuration-store"
If you use macOS or Linux, run the following command:

export ConnectionString='connection-string-of-your-app-configuration-store'

2. Press F5 to test your function. If prompted, accept the request from Visual Studio to download and install
Azure Functions Core (CLI) tools. You might also need to enable a firewall exception so that the tools can
handle HTTP requests.
3. Copy the URL of your function from the Azure Functions runtime output.

4. Paste the URL for the HTTP request into your browser's address bar. The following image shows the
response in the browser to the local GET request returned by the function.

Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this quickstart, you created a new App Configuration store and used it with an Azure Functions app via the App
Configuration provider. To learn how to configure your Azure Functions app to dynamically refresh configuration
settings, continue to the next tutorial.
Enable dynamic configuration
Quickstart: Create a Java Spring app with Azure App
Configuration
9/22/2020 • 5 minutes to read • Edit Online

In this quickstart, you incorporate Azure App Configuration into a Java Spring app to centralize storage and
management of application settings separate from your code.

Prerequisites
Azure subscription - create one for free
A supported Java Development Kit (JDK) with version 8.
Apache Maven version 3.0 or above.

Create an App Configuration store


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and
select Enter.

2. Select App Configuration from the search results, and then select Create .
3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the
same time by deleting the resource
group. For more information, see Use
resource groups to manage your
Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted. For
the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.
4. Select Create . The deployment might take a few minutes.
5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.
6. Select Configuration Explorer > + Create > Key-value to add the following key-value pairs:

K EY VA L UE

/application/config.message Hello

Leave Label and Content Type empty for now.


7. Select Apply .

Create a Spring Boot app


Use the Spring Initializr to create a new Spring Boot project.
1. Browse to https://start.spring.io/.
2. Specify the following options:
Generate a Maven project with Java .
Specify a Spring Boot version that's equal to or greater than 2.0.
Specify the Group and Ar tifact names for your application.
Add the Spring Web dependency.
3. After you specify the previous options, select Generate Project . When prompted, download the project to
a path on your local computer.

Connect to an App Configuration store


1. After you extract the files on your local system, your simple Spring Boot application is ready for editing.
Locate the pom.xml file in the root directory of your app.
2. Open the pom.xml file in a text editor, and add the Spring Cloud Azure Config starter to the list of
<dependencies> :
Spring Cloud 1.1.x

<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-appconfiguration-config</artifactId>
<version>1.1.5</version>
</dependency>

Spring Cloud 1.2.x

<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-appconfiguration-config</artifactId>
<version>1.2.7</version>
</dependency>

3. Create a new Java file named MessageProperties.java in the package directory of your app. Add the
following lines:

package com.example.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "config")
public class MessageProperties {
private String message;

public String getMessage() {


return message;
}

public void setMessage(String message) {


this.message = message;
}
}

4. Create a new Java file named HelloController.java in the package directory of your app. Add the following
lines:

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
private final MessageProperties properties;

public HelloController(MessageProperties properties) {


this.properties = properties;
}

@GetMapping
public String getMessage() {
return "Message: " + properties.getMessage();
}
}

5. Open the main application Java file, and add @EnableConfigurationProperties to enable this feature.
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties(MessageProperties.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

6. Create a new file named bootstrap.properties under the resources directory of your app, and add the
following lines to the file. Replace the sample values with the appropriate properties for your App
Configuration store.

spring.cloud.azure.appconfiguration.stores[0].connection-string= ${APP_CONFIGURATION_CONNECTION_STRING}

7. Set an environment variable named APP_CONFIGURATION_CONNECTION_STRING , and set it to the


access key to your App Configuration store. At the command line, run the following command and restart
the command prompt to allow the change to take effect:

setx APP_CONFIGURATION_CONNECTION_STRING "connection-string-of-your-app-configuration-store"

If you use Windows PowerShell, run the following command:

$Env:APP_CONFIGURATION_CONNECTION_STRING = "connection-string-of-your-app-configuration-store"

If you use macOS or Linux, run the following command:

export APP_CONFIGURATION_CONNECTION_STRING='connection-string-of-your-app-configuration-store'

Build and run the app locally


1. Build your Spring Boot application with Maven and run it, for example:

mvn clean package


mvn spring-boot:run

2. After your application is running, use curl to test your application, for example:

curl -X GET http://localhost:8080/

You see the message that you entered in the App Configuration store.

Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.
IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this quickstart, you created a new App Configuration store and used it with a Java Spring app. For more
information, see Spring on Azure. To learn how to enable your Java Spring app to dynamically refresh
configuration settings, continue to the next tutorial.
Enable dynamic configuration
Quickstart: Automated VM deployment with App
Configuration and Resource Manager template (ARM
template)
9/22/2020 • 6 minutes to read • Edit Online

Learn how to use Azure Resource Manager templates and Azure PowerShell to deploy an Azure App Configuration
store, how to add key-values into the store, and how to use the key-values in the store to deploy an Azure resource,
like an Azure virtual machine in this example.
An ARM template is a JavaScript Object Notation (JSON) file that defines the infrastructure and configuration for
your project. The template uses declarative syntax, which lets you state what you intend to deploy without having to
write the sequence of programming commands to create it.
If your environment meets the prerequisites and you're familiar with using ARM templates, select the Deploy to
Azure button. The template will open in the Azure portal.

Prerequisites
If you don't have an Azure subscription, create a free account before you begin.

Review the templates


The templates used in this quickstart are from Azure Quickstart Templates. The first template creates an App
Configuration store:
{
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"configStoreName": {
"type": "string",
"metadata": {
"description": "Specifies the name of the app configuration store."
}
},
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]",
"metadata": {
"description": "Specifies the Azure location where the app configuration store should be created."
}
},
"skuName": {
"type": "string",
"defaultValue": "standard",
"metadata": {
"description": "Specifies the SKU of the app configuration store."
}
}
},
"resources": [
{
"type": "Microsoft.AppConfiguration/configurationStores",
"apiVersion": "2019-10-01",
"name": "[parameters('configStoreName')]",
"location": "[parameters('location')]",
"sku": {
"name": "[parameters('skuName')]"
}
}
]
}

One Azure resource is defined in the template:


Microsoft.AppConfiguration/configurationStores: create an App Configuration store.
The second template creates a virtual machine by using the key-values in the store. Before this step, you need to
add key-values by using the portal or Azure CLI.

{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]",
"metadata": {
"description": "Specify the locations for all resources."
}
},
"adminUsername": {
"type": "string",
"metadata": {
"description": "Specify the virtual machine admin user name."
}
},
"adminPassword": {
"type": "securestring",
"metadata": {
"description": "Specify the virtual machine admin password."
"description": "Specify the virtual machine admin password."
}
},
"domainNameLabel": {
"type": "string",
"metadata": {
"description": "Specify the DNS label for the virtual machine public IP address. It must be lowercase.
It should match the following regular expression, or it will raise an error: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$."
}
},
"vmSize": {
"type": "string",
"defaultValue": "Standard_D2_v3",
"metadata": {
"description": "Specify the size of the VM."
}
},
"storageAccountName": {
"type": "string",
"metadata": {
"description": "Specify the storage account name."
}
},
"appConfigStoreResourceGroup": {
"type": "string",
"metadata": {
"description": "Name of the resource group for the app config store."
}
},
"appConfigStoreName": {
"type": "string",
"metadata": {
"description": "App configuration store name."
}
},
"vmSkuKey": {
"type": "string",
"metadata": {
"description": "Specify the name of the key in the app config store for the VM windows sku."
}
},
"diskSizeKey": {
"type": "string",
"metadata": {
"description": "Specify the name of the key in the app config store for the VM disk size"
}
}
},
"variables": {
"nicName": "myVMNic",
"addressPrefix": "10.0.0.0/16",
"subnetName": "Subnet",
"subnetPrefix": "10.0.0.0/24",
"publicIPAddressName": "myPublicIP",
"vmName": "SimpleWinVM",
"virtualNetworkName": "MyVNET",
"subnetRef": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('virtualNetworkName'),
variables('subnetName'))]",
"appConfigRef": "[resourceId(parameters('appConfigStoreResourceGroup'),
'Microsoft.AppConfiguration/configurationStores', parameters('appConfigStoreName'))]",
"windowsOSVersionParameters": {
"key": "[parameters('vmSkuKey')]",
"label": "template"
},
"diskSizeGBParameters": {
"key": "[parameters('diskSizeKey')]",
"label": "template"
}
},
"resources": [
"resources": [
{
"type": "Microsoft.Storage/storageAccounts",
"apiVersion": "2019-06-01",
"name": "[parameters('storageAccountName')]",
"location": "[parameters('location')]",
"sku": {
"name": "Standard_LRS"
},
"kind": "Storage",
"properties": {
}
},
{
"type": "Microsoft.Network/publicIPAddresses",
"apiVersion": "2020-05-01",
"name": "[variables('publicIPAddressName')]",
"location": "[parameters('location')]",
"properties": {
"publicIPAllocationMethod": "Dynamic",
"dnsSettings": {
"domainNameLabel": "[parameters('domainNameLabel')]"
}
}
},
{
"type": "Microsoft.Network/virtualNetworks",
"apiVersion": "2020-05-01",
"name": "[variables('virtualNetworkName')]",
"location": "[parameters('location')]",
"properties": {
"addressSpace": {
"addressPrefixes": [
"[variables('addressPrefix')]"
]
},
"subnets": [
{
"name": "[variables('subnetName')]",
"properties": {
"addressPrefix": "[variables('subnetPrefix')]"
}
}
]
}
},
{
"type": "Microsoft.Network/networkInterfaces",
"apiVersion": "2020-05-01",
"name": "[variables('nicName')]",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]",
"[resourceId('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
],
"properties": {
"ipConfigurations": [
{
"name": "ipconfig1",
"properties": {
"privateIPAllocationMethod": "Dynamic",
"publicIPAddress": {
"id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
},
"subnet": {
"id": "[variables('subnetRef')]"
}
}
}
]
]
}
},
{
"type": "Microsoft.Compute/virtualMachines",
"apiVersion": "2019-12-01",
"name": "[variables('vmName')]",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Storage/storageAccounts/', parameters('storageAccountName'))]",
"[resourceId('Microsoft.Network/networkInterfaces/', variables('nicName'))]"
],
"properties": {
"hardwareProfile": {
"vmSize": "[parameters('vmSize')]"
},
"osProfile": {
"computerName": "[variables('vmName')]",
"adminUsername": "[parameters('adminUsername')]",
"adminPassword": "[parameters('adminPassword')]"
},
"storageProfile": {
"imageReference": {
"publisher": "MicrosoftWindowsServer",
"offer": "WindowsServer",
"sku": "[listKeyValue(variables('appConfigRef'), '2019-10-01',
variables('windowsOSVersionParameters')).value]",
"version": "latest"
},
"osDisk": {
"createOption": "FromImage"
},
"dataDisks": [
{
"diskSizeGB": "[listKeyValue(variables('appConfigRef'), '2019-10-01',
variables('diskSizeGBParameters')).value]",
"lun": 0,
"createOption": "Empty"
}
]
},
"networkProfile": {
"networkInterfaces": [
{
"id": "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]"
}
]
},
"diagnosticsProfile": {
"bootDiagnostics": {
"enabled": true,
"storageUri": "[reference(resourceId('Microsoft.Storage/storageAccounts/',
parameters('storageAccountName'))).primaryEndpoints.blob]"
}
}
}
}
],
"outputs": {
"hostname": {
"type": "string",
"value": "[reference(variables('publicIPAddressName')).dnsSettings.fqdn]"
}
}
}
Deploy the templates
Create an App Configuration store
1. Select the following image to sign in to Azure and open a template. The template creates an App
Configuration store.

2. Select or enter the following values.


subscription : select the Azure subscription used to create the App Configuration store.
Resource group : select Create new to create a new resource group unless you want to use an existing
resource group.
Region : select a location for the resource group. For example, East US .
Config Store Name : enter a new App Configuration store name.
Location : specify the location of the App Configuration store. Use the default value.
Sku Name : specify the SKU name of the App Configuration store. Use the default value.
3. Select Review + create .
4. Verify that the page shows Validation Passed , and then select Create .
Make a note of the resource group name and the App Configuration store name. You need these values when you
deploy the virtual machine
Add VM configuration key-values
After you have created an App Configuration store, you can use the Azure portal or Azure CLI to add key-values to
the store.
1. Sign in to the Azure portal, and then navigate to the newly created App Configuration store.
2. Select Configuration explorer from the left menu.
3. Select Create to add the following key-value pairs:

K EY VA L UE L A B EL

windowsOsVersion 2019-Datacenter template

diskSizeGB 1023 template

Keep Content Type empty.


To use Azure CLI, see Work with key-values in an Azure App Configuration store.
Deploy VM using stored key-values
Now that you've added key-values to the store, you're ready to deploy a VM using an Azure Resource Manager
template. The template references the windowsOsVersion and diskSizeGB keys you created.

WARNING
ARM templates can't reference keys in an App Configuration store that has Private Link enabled.

1. Select the following image to sign in to Azure and open a template. The template creates a virtual machine
using stored key-values in the App Configuration store.
2. Select or enter the following values.
subscription : select the Azure subscription used to create the virtual machine.
Resource group : either specify the same resource group as the App Configuration store, or select
Create new to create a new resource group.
Region : select a location for the resource group. For example, East US .
Location : specify the location of the virtual machine. use the default value.
Admin Username : specify an administrator username for the virtual machine.
Admin Password : specify an administrator password for the virtual machine.
Domain Name Label : specify a unique domain name.
Storage Account Name : specify a unique name for a storage account associated with the virtual
machine.
App Config Store Resource Group : specify the resource group that contains your App Configuration
store.
App Config Store Name : specify the name of your Azure App Configuration store.
VM Sku Key : specify windowsOsVersion . This is the key value name that you added to the store.
Disk Size Key : specify diskSizeGB . This is the they key value name that you added to the store.
3. Select Review + create .
4. Verify that the page shows Validation Passed , and then select Create .

Review deployed resources


1. Sign in to the Azure portal, and then navigate to the newly created virtual machine.
2. Select Over view from the left menu, and verify the SKU is 2019-Datacenter .
3. Select Disks from the left menu, and verify the size of the data disk is 2013 .

Clean up resources
When no longer needed, delete the resource group, the App Configuration store, VM, and all related resources. If
you're planning to use the App Configuration store or VM in future, you can skip deleting it. If you aren't going to
continue to use this job, delete all resources created by this quickstart by running the following cmdlet:

Remove-AzResourceGroup `
-Name $resourceGroup

Next steps
In this quickstart, you deployed a VM using an Azure Resource Manager template and key-values from Azure App
Configuration.
To learn about creating other applications with Azure App Configuration, continue to the following article:
Quickstart: Create an ASP.NET Core app with Azure App Configuration
Quickstart: Add feature flags to an ASP.NET Core app
9/22/2020 • 8 minutes to read • Edit Online

In this quickstart, you create an end-to-end implementation of feature management in an ASP.NET Core
application using Azure App Configuration. You will use the App Configuration service to centrally store all your
feature flags and control their states.
The .NET Core Feature Management libraries extend the framework with comprehensive feature flag support.
These libraries are built on top of the .NET Core configuration system. They seamlessly integrate with App
Configuration through its .NET Core configuration provider.

Prerequisites
Azure subscription - create one for free
.NET Core SDK.

Create an App Configuration store


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and
select Enter.
2. Select App Configuration from the search results, and then select Create .

3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the
same time by deleting the resource
group. For more information, see Use
resource groups to manage your
Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted. For
the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.
4. Select Create . The deployment might take a few minutes.
5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.
6. Select Feature Manager > +Add to add a feature flag called Beta .

Leave label undefined for now. Select Apply to save the new feature flag.

Create an ASP.NET Core web app


Use the .NET Core command-line interface (CLI) to create a new ASP.NET Core MVC web app project. The
advantage of using the .NET Core CLI instead of Visual Studio is that the .NET Core CLI is available across the
Windows, macOS, and Linux platforms.
1. Create a new folder for your project. For this quickstart, name it TestFeatureFlags.
2. In the new folder, run the following command to create a new ASP.NET Core MVC web app project:

dotnet new mvc --no-https

Add Secret Manager


To use Secret Manager, add a UserSecretsId element to your .csproj file.
1. Open the .csproj file.
2. Add a UserSecretsId element as shown here. You can use the same GUID, or you can replace this value with
your own.

IMPORTANT
CreateHostBuilder replaces CreateWebHostBuilder in .NET Core 3.0. Select the correct syntax based on your
environment.

.NET Core 2.x


.NET Core 3.x

<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<UserSecretsId>79a3edd0-2092-40a2-a04d-dcb46d5ca9ed</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2"
PrivateAssets="All" />
</ItemGroup>

</Project>

3. Save the .csproj file.


The Secret Manager tool stores sensitive data for development work outside of your project tree. This approach
helps prevent the accidental sharing of app secrets within source code.

TIP
To learn more about Secret Manager, please see Safe storage of app secrets in development in ASP.NET Core.

Connect to an App Configuration store


1. Add reference to the Microsoft.Azure.AppConfiguration.AspNetCore and the
Microsoft.FeatureManagement.AspNetCore NuGet packages by running the following commands:

dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore


dotnet add package Microsoft.FeatureManagement.AspNetCore

2. Run the following command to restore packages for your project:

dotnet restore

3. Add a secret named ConnectionStrings:AppConfig to Secret Manager.


This secret contains the connection string to access your App Configuration store. Replace the
<your_connection_string> value in the following command with the connection string for your App
Configuration store. You can find the primary read-only key connection string under Access Keys in the
Azure portal.
This command must be executed in the same directory as the .csproj file.

dotnet user-secrets set ConnectionStrings:AppConfig <your_connection_string>

You use Secret Manager only to test the web app locally. When you deploy the app to Azure App Service, for
example, you use an application setting named Connection Strings in App Service instead of using Secret
Manager to store the connection string.
You can access this secret with the App Configuration API. A colon (:) works in the configuration name with
the App Configuration API on all supported platforms. See Configuration by environment.
4. In Program.cs, update the CreateWebHostBuilder method to use App Configuration by calling the
config.AddAzureAppConfiguration() method.

IMPORTANT
CreateHostBuilder replaces CreateWebHostBuilder in .NET Core 3.0. Select the correct syntax based on your
environment.

.NET Core 2.x


.NET Core 3.x

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options => {
options.Connect(settings["ConnectionStrings:AppConfig"])
.UseFeatureFlags();
});
})
.UseStartup<Startup>();

5. Open Startup.cs, and add references to the .NET Core feature manager:

using Microsoft.FeatureManagement;

6. Update the ConfigureServicesmethod to add feature flag support by calling the


services.AddFeatureManagement() method. Optionally, you can include any filter to be used with feature flags
by calling services.AddFeatureFilter<FilterType>() :
.NET Core 2.x
.NET Core 3.x

public void ConfigureServices(IServiceCollection services)


{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddFeatureManagement();
}

7. Update the Configure method to add a middleware to allow the feature flag values to be refreshed at a
recurring interval while the ASP.NET Core web app continues to receive requests.
.NET Core 2.x
.NET Core 3.x

public void Configure(IApplicationBuilder app, IHostingEnvironment env)


{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAzureAppConfiguration();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

8. Add a MyFeatureFlags.cs file:

namespace TestFeatureFlags
{
public enum MyFeatureFlags
{
Beta
}
}

9. Add BetaController.cs to the Controllers directory:

using Microsoft.AspNetCore.Mvc;
using Microsoft.FeatureManagement;
using Microsoft.FeatureManagement.Mvc;

namespace TestFeatureFlags.Controllers
{
public class BetaController: Controller
{
private readonly IFeatureManager _featureManager;

public BetaController(IFeatureManagerSnapshot featureManager)


{
_featureManager = featureManager;
}

[FeatureGate(MyFeatureFlags.Beta)]
public IActionResult Index()
{
return View();
}
}
}
10. Open _ViewImports.cshtml in the Views directory, and add the feature manager tag helper:

@addTagHelper *, Microsoft.FeatureManagement.AspNetCore

11. Open _Layout.cshtml in the Views\Shared directory, and replace the <nav> bar code under <body> >
<header> with the following code:

<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow


mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-
action="Index">TestFeatureFlags</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-
collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-
action="Index">Home</a>
</li>
<feature name="Beta">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Beta" asp-
action="Index">Beta</a>
</li>
</feature>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-
action="Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>

12. Create a Beta directory under Views and add Index.cshtml to it:

@{
ViewData["Title"] = "Beta Home Page";
}

<h1>
This is the beta website.
</h1>

Build and run the app locally


1. To build the app by using the .NET Core CLI, run the following command in the command shell:

dotnet build

2. After the build successfully completes, run the following command to run the web app locally:

dotnet run
3. Open a browser window, and go to https://localhost:5000 , which is the default URL for the web app
hosted locally. If you're working in the Azure Cloud Shell, select the Web Preview button followed by
Configure. When prompted, select port 5000.

Your browser should display a page similar to the image below.

4. Sign in to the Azure portal. Select All resources , and select the App Configuration store instance that you
created in the quickstart.
5. Select Feature Manager , and change the state of the Beta key to On .
6. Return to the command prompt and cancel the running dotnet process by pressing Ctrl-C . Restart your
application using dotnet run .
7. Refresh the browser page to see the new configuration settings.
Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this quickstart, you created a new App Configuration store and used it to manage features in an ASP.NET Core
web app via the Feature Management libraries.
Learn more about feature management.
Manage feature flags.
Use feature flags in an ASP.NET Core app.
Use dynamic configuration in an ASP.NET Core app
Quickstart: Add feature flags to a .NET Framework
app
9/22/2020 • 4 minutes to read • Edit Online

In this quickstart, you incorporate Azure App Configuration into a .NET Framework app to create an end-to-end
implementation of feature management. You can use the App Configuration service to centrally store all your
feature flags and control their states.
The .NET Feature Management libraries extend the framework with feature flag support. These libraries are built on
top of the .NET configuration system. They integrate with App Configuration through its .NET configuration
provider.

Prerequisites
Azure subscription - create one for free
Visual Studio 2019
.NET Framework 4.8

Create an App Configuration store


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and select
Enter.
2. Select App Configuration from the search results, and then select Create .

3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N


SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the same
time by deleting the resource group.
For more information, see Use
resource groups to manage your
Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted. For
the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.

4. Select Create . The deployment might take a few minutes.


5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.
6. Select Feature Manager > +Add to add a feature flag called Beta .

Leave label undefined for now.

Create a .NET console app


1. Start Visual Studio, and select File > New > Project .
2. In Create a new project , filter on the Console project type and click on Console App (.NET
Framework) . Click Next .
3. In Configure your new project , enter a project name. Under Framework , select .NET Framework 4.8
or higher. Click Create .

Connect to an App Configuration store


1. Right-click your project, and select Manage NuGet Packages . On the Browse tab, search and add the
following NuGet packages to your project. If you can't find them, select the Include prerelease check box.

Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Configuration.AzureAppConfiguration
Microsoft.FeatureManagement

2. Open Program.cs and add the following statements:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
using Microsoft.FeatureManagement;

3. Update the Main method to connect to App Configuration, specifying the UseFeatureFlags option so that
feature flags are retrieved. Then display a message if the Beta feature flag is enabled.
public static async Task Main(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddAzureAppConfiguration(options =>
{
options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
.UseFeatureFlags();
}).Build();

IServiceCollection services = new ServiceCollection();

services.AddSingleton<IConfiguration>(configuration).AddFeatureManagement();

using (ServiceProvider serviceProvider = services.BuildServiceProvider())


{
IFeatureManager featureManager = serviceProvider.GetRequiredService<IFeatureManager>();

if (await featureManager.IsEnabledAsync("Beta"))
{
Console.WriteLine("Welcome to the beta!");
}
}

Console.WriteLine("Hello World!");
}

Build and run the app locally


1. Set an environment variable named ConnectionString to the connection string of your App Configuration
store. If you use the Windows command prompt, run the following command:

setx ConnectionString "connection-string-of-your-app-configuration-store"

If you use Windows PowerShell, run the following command:

$Env:ConnectionString = "connection-string-of-your-app-configuration-store"

2. Restart Visual Studio to allow the change to take effect.


3. Press Ctrl + F5 to build and run the console app.
Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this quickstart, you created a feature flag in App Configuration and used it with a .NET Framework console app.
To learn how to dynamically update feature flags and other configuration values without restarting the application,
continue to the next tutorial.
Enable dynamic configuration
Quickstart: Add feature flags to an Azure Functions
app
9/22/2020 • 7 minutes to read • Edit Online

In this quickstart, you create an implementation of feature management in an Azure Functions app using Azure App
Configuration. You will use the App Configuration service to centrally store all your feature flags and control their
states.
The .NET Feature Management libraries extend the framework with feature flag support. These libraries are built on
top of the .NET configuration system. They integrate with App Configuration through its .NET configuration
provider.

Prerequisites
Azure subscription - create one for free
Visual Studio 2019 with the Azure development workload.
Azure Functions tools

Create an App Configuration store


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and select
Enter.
2. Select App Configuration from the search results, and then select Create .

3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N


SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the same
time by deleting the resource group.
For more information, see Use
resource groups to manage your
Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted. For
the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.

4. Select Create . The deployment might take a few minutes.


5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.
6. Select Feature Manager > +Add to add a feature flag called Beta .

Leave label and Description undefined for now.


7. Select Apply to save the new feature flag.

Create a Functions app


The Azure Functions project template in Visual Studio creates a project that you can publish to a function app in
Azure. You can use a function app to group functions as a logical unit for easier management, deployment, scaling,
and sharing of resources.
1. From the Visual Studio menu, select File > New > Project .
2. In Create a new project , enter functions in the search box, choose the Azure Functions template, and
then select Next .
3. In Configure your new project , enter a Project name for your project, and then select Create . The
function app name must be valid as a C# namespace, so don't use underscores, hyphens, or any other
nonalphanumeric characters.
4. For the Create a new Azure Functions application settings, use the values in the following table:

SET T IN G VA L UE DESC RIP T IO N

Functions runtime Azure Functions v3 This value creates a function project


(.NET Core) that uses the version 3.x runtime of
Azure Functions, which supports .NET
Core 3.x. Azure Functions 1.x
supports the .NET Framework. For
more information, see Azure
Functions runtime versions overview.

Function template HTTP trigger This value creates a function


triggered by an HTTP request.
SET T IN G VA L UE DESC RIP T IO N

Storage account Storage emulator Because an Azure Function requires a


(AzureWebJobsStorage) storage account, one is assigned or
created when you publish your
project to Azure. An HTTP trigger
doesn't use an Azure Storage account
connection string; all other trigger
types require a valid Azure Storage
account connection string.

Authorization level Anonymous The created function can be triggered


by any client without providing a key.
This authorization setting makes it
easy to test your new function. For
more information about keys and
authorization, see Authorization keys
and HTTP and webhook bindings.

Make sure you set the Authorization level to Anonymous . If you choose the default level of Function ,
you're required to present the function key in requests to access your function endpoint.
5. Select Create to create the function project and HTTP trigger function.

Connect to an App Configuration store


1. Right-click your project, and select Manage NuGet Packages . On the Browse tab, search and add the
following NuGet packages to your project. Verify for Microsoft.Extensions.DependencyInjection that you are
on the most recent stable build.

Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Configuration
Microsoft.FeatureManagement
2. Open Function1.cs, and add the namespaces of these packages.

using Microsoft.Extensions.Configuration;
using Microsoft.FeatureManagement;
using Microsoft.Extensions.DependencyInjection;

3. Add the Function1 static constructor below to bootstrap the Azure App Configuration provider. Next add
two static members, a field named ServiceProvider to create a singleton instance of ServiceProvider ,
and a property below Function1 named FeatureManager to create a singleton instance of IFeatureManager .
Then connect to App Configuration in Function1 by calling AddAzureAppConfiguration() . This process will
load the configuration at application startup. The same configuration instance will be used for all Functions
calls later.

// Implements IDisposable, cached for life time of function


private static ServiceProvider ServiceProvider;

static Function1()
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddAzureAppConfiguration(options =>
{
options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
.UseFeatureFlags();
}).Build();

var services = new ServiceCollection();


services.AddSingleton<IConfiguration>(configuration).AddFeatureManagement();

ServiceProvider = services.BuildServiceProvider();
}

private static IFeatureManager FeatureManager => ServiceProvider.GetRequiredService<IFeatureManager>


();

4. Update the Run method to change value of the displayed message depending on the state of the feature
flag.

[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
string message = await FeatureManager.IsEnabledAsync("Beta")
? "The Feature Flag 'Beta' is turned ON"
: "The Feature Flag 'Beta' is turned OFF";

return (ActionResult)new OkObjectResult(message);


}

Test the function locally


1. Set an environment variable named ConnectionString , where the value is the access key you retrieved
earlier in your App Configuration store under Access Keys . If you use the Windows command prompt, run
the following command and restart the command prompt to allow the change to take effect:

setx ConnectionString "connection-string-of-your-app-configuration-store"


If you use Windows PowerShell, run the following command:

$Env:ConnectionString = "connection-string-of-your-app-configuration-store"

If you use macOS or Linux, run the following command:

export ConnectionString='connection-string-of-your-app-configuration-store'

2. Press F5 to test your function. If prompted, accept the request from Visual Studio to download and install
Azure Functions Core (CLI) tools. You might also need to enable a firewall exception so that the tools can
handle HTTP requests.
3. Copy the URL of your function from the Azure Functions runtime output.

4. Paste the URL for the HTTP request into your browser's address bar. The following image shows the
response indicating that the feature flag Beta is disabled.

5. Sign in to the Azure portal. Select All resources , and select the App Configuration store instance that you
created.
6. Select Feature Manager , and change the state of the Beta key to On .
7. Return to your command prompt and cancel the running process by pressing Ctrl-C . Restart your
application by pressing F5.
8. Copy the URL of your function from the Azure Functions runtime output using the same process as in Step 3.
Paste the URL for the HTTP request into your browser's address bar. The browser response should have
changed to indicate the feature flag Beta is turned on, as shown in the image below.

Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this quickstart, you created a feature flag and used it with an Azure Functions app via the App Configuration
provider.
Learn more about feature management.
Manage feature flags.
Use dynamic configuration in an Azure Functions app
Quickstart: Add feature flags to a Spring Boot app
9/22/2020 • 6 minutes to read • Edit Online

In this quickstart, you incorporate Azure App Configuration into a Spring Boot web app to create an end-to-end
implementation of feature management. You can use the App Configuration service to centrally store all your
feature flags and control their states.
The Spring Boot Feature Management libraries extend the framework with comprehensive feature flag support.
These libraries do not have a dependency on any Azure libraries. They seamlessly integrate with App
Configuration through its Spring Boot configuration provider.

Prerequisites
Azure subscription - create one for free
A supported Java Development Kit SDK with version 8.
Apache Maven version 3.0 or above.

Create an App Configuration instance


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and
select Enter.
2. Select App Configuration from the search results, and then select Create .

3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the
same time by deleting the resource
group. For more information, see Use
resource groups to manage your
Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted. For
the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.
4. Select Create . The deployment might take a few minutes.
5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.
6. Select Feature Manager > +Add to add a feature flag called Beta .

Leave label undefined for now.

Create a Spring Boot app


Use the Spring Initializr to create a new Spring Boot project.
1. Browse to https://start.spring.io/.
2. Specify the following options:
Generate a Maven project with Java .
Specify a Spring Boot version that's equal to or greater than 2.0.
Specify the Group and Ar tifact names for your application. This article uses com.example and demo .
Add the Spring Web dependency.
3. After you specify the previous options, select Generate Project . When prompted, download the project to
your local computer.
Add feature management
1. After you extract the files on your local system, your Spring Boot application is ready for editing. Locate
pom.xml in the root directory of your app.
2. Open the pom.xml file in a text editor and add the following to the list of <dependencies> :
Spring Cloud 1.1.x

<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-appconfiguration-config-web</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-feature-management-web</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Spring Cloud 1.2.x

<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-appconfiguration-config-web</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-feature-management-web</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

NOTE
There is a non-web Feature Management Library that doesn't have a dependency on spring-web. Refer to GitHub's
documentation for differences.

Connect to an App Configuration store


1. Navigate to the resources directory of your app and open bootstrap.properties . If the file does not exist,
create it. Add the following line to the file.

spring.cloud.azure.appconfiguration.stores[0].connection-string= ${APP_CONFIGURATION_CONNECTION_STRING}

2. In the App Configuration portal for your config store, select Access keys from the sidebar. Select the Read-
only keys tab. Copy the value of the primary connection string.
3. Add the primary connection string as an environment variable using the variable name
APP_CONFIGURATION_CONNECTION_STRING .
4. Open the main application Java file, and add @EnableConfigurationProperties to enable this feature.

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableConfigurationProperties(MessageProperties.class)
public class DemoApplication {

public static void main(String[] args) {


SpringApplication.run(DemoApplication.class, args);
}
}

5. Create a new Java file named MessageProperties.java in the package directory of your app.

package com.example.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "config")
public class MessageProperties {
private String message;

public String getMessage() {


return message;
}

public void setMessage(String message) {


this.message = message;
}
}

6. Create a new Java file named HelloController.java in the package directory of your app.
package com.example.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import com.microsoft.azure.spring.cloud.feature.manager.FeatureManager;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
@ConfigurationProperties("controller")
public class HelloController {

private FeatureManager featureManager;

public HelloController(FeatureManager featureManager) {


this.featureManager = featureManager;
}

@GetMapping("/welcome")
public String mainWithParam(Model model) {
model.addAttribute("Beta", featureManager.isEnabledAsync("featureManagement.Beta").block());
return "welcome";
}
}

7. Create a new HTML file named welcome.html in the templates directory of your app.
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Feature Management with Spring Cloud Azure</title>

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-


q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>

</head>
<body>
<header>
<!-- Fixed navbar -->
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="#">TestFeatureFlags</a>
<button class="navbar-toggler" aria-expanded="false" aria-controls="navbarCollapse" aria-
label="Toggle navigation" type="button" data-target="#navbarCollapse" data-toggle="collapse">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item" th:if="${Beta}">
<a class="nav-link" href="#">Beta</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Privacy</a>
</li>
</ul>
</div>
</nav>
</header>
<div class="container body-content">
<h1 class="mt-5">Welcome</h1>
<p>Learn more about <a href="https://github.com/microsoft/spring-cloud-
azure/blob/master/spring-cloud-azure-feature-management/README.md">Feature Management with Spring Cloud
Azure</a></p>

</div>
<footer class="footer">
<div class="container">
<span class="text-muted">&copy; 2019 - Projects</span>
</div>

</footer>
</body>
</html>

8. Create a new folder named CSS under static and inside of it a new CSS file named main.css.
html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 60px;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
height: 60px;
line-height: 60px;
background-color: #f5f5f5;
}

body > .container {


padding: 60px 15px 0;
}

.footer > .container {


padding-right: 15px;
padding-left: 15px;
}

code {
font-size: 80%;
}

Build and run the app locally


1. Build your Spring Boot application with Maven and run it.

mvn clean package


mvn spring-boot:run

2. Open a browser window, and go to the URL: http://localhost:8080/welcome .


3. In the App Configuration portal select Feature Manager , and change the state of the Beta key to On :

K EY STAT E

Beta On

4. Refresh the browser page to see the new configuration settings.

Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this quickstart, you created a new App Configuration store and used it to manage features in a Spring Boot web
app via the Feature Management libraries.
Learn more about feature management.
Manage feature flags.
Use feature flags in a Spring Boot Core app.
Tutorial: Use dynamic configuration in an ASP.NET
Core app
9/22/2020 • 7 minutes to read • Edit Online

ASP.NET Core has a pluggable configuration system that can read configuration data from a variety of sources. It
can handle changes dynamically without causing an application to restart. ASP.NET Core supports the binding of
configuration settings to strongly typed .NET classes. It injects them into your code by using the various
IOptions<T> patterns. One of these patterns, specifically IOptionsSnapshot<T> , automatically reloads the
application's configuration when the underlying data changes. You can inject IOptionsSnapshot<T> into controllers
in your application to access the most recent configuration stored in Azure App Configuration.
You also can set up the App Configuration ASP.NET Core client library to refresh a set of configuration settings
dynamically using a middleware. The configuration settings get updated with the configuration store each time as
long as the web app receives requests.
App Configuration automatically caches each setting to avoid too many calls to the configuration store. The refresh
operation waits until the cached value of a setting expires to update that setting, even when its value changes in
the configuration store. The default cache expiration time is 30 seconds. You can override this expiration time, if
necessary.
This tutorial shows how you can implement dynamic configuration updates in your code. It builds on the web app
introduced in the quickstarts. Before you continue, finish Create an ASP.NET Core app with App Configuration first.
You can use any code editor to do the steps in this tutorial. Visual Studio Code is an excellent option that's available
on the Windows, macOS, and Linux platforms.
In this tutorial, you learn how to:
Set up your application to update its configuration in response to changes in an App Configuration store.
Inject the latest configuration in your application's controllers.

Prerequisites
To do this tutorial, install the .NET Core SDK.
If you don't have an Azure subscription, create a free account before you begin.
Before you continue, finish Create an ASP.NET Core app with App Configuration first.

Add a sentinel key


A sentinel key is a special key used to signal when configuration has changed. Your app monitors the sentinel key
for changes. When a change is detected, you refresh all configuration values. This approach reduces the overall
number of requests made by your app to App Configuration, compared to monitoring all keys for changes.
1. In the Azure portal, select Configuration Explorer > Create > Key-value .
2. For Key , enter TestApp:Settings:Sentinel. For Value , enter 1. Leave Label and Content type blank.
3. Select Apply .
NOTE
If you aren't using a sentinel key, you need to manually register every key you want to watch.

Reload data from App Configuration


1. Add a reference to the Microsoft.Azure.AppConfiguration.AspNetCore NuGet package by running the
following command:

dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore

2. Open Program.cs, and update the CreateWebHostBuilder method to add the


config.AddAzureAppConfiguration() method.
.NET Core 2.x
.NET Core 3.x

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();

config.AddAzureAppConfiguration(options =>
{
options.Connect(settings["ConnectionStrings:AppConfig"])
.ConfigureRefresh(refresh =>
{
refresh.Register("TestApp:Settings:Sentinel", refreshAll: true)
.SetCacheExpiration(new TimeSpan(0, 5, 0));
});
});
})
.UseStartup<Startup>();

The ConfigureRefresh method is used to specify the settings used to update the configuration data with the
App Configuration store when a refresh operation is triggered. The refreshAll parameter to the Register
method indicates that all configuration values should be refreshed if the sentinel key changes.
Also, the SetCacheExpiration method overrides the default cache expiration time of 30 seconds, specifying
a time of 5 minutes instead. This reduces the number of requests made to App Configuration.

NOTE
For testing purposes, you may want to lower the cache expiration time.

To actually trigger a refresh operation, you'll need to configure a refresh middleware for the application to
refresh the configuration data when any change occurs. You'll see how to do this in a later step.
3. Add a Settings.cs file that defines and implements a new Settings class.
namespace TestAppConfig
{
public class Settings
{
public string BackgroundColor { get; set; }
public long FontSize { get; set; }
public string FontColor { get; set; }
public string Message { get; set; }
}
}

4. Open Startup.cs, and use IServiceCollection.Configure<T> in the ConfigureServices method to bind


configuration data to the Settings class.
.NET Core 2.x
.NET Core 3.x

public void ConfigureServices(IServiceCollection services)


{
services.Configure<Settings>(Configuration.GetSection("TestApp:Settings"));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

TIP
To learn more about the options pattern when reading configuration values, see Options Patterns in ASP.NET Core.

5. Update the Configure method, adding the UseAzureAppConfiguration middleware to allow the
configuration settings registered for refresh to be updated while the ASP.NET Core web app continues to
receive requests.
.NET Core 2.x
.NET Core 3.x

public void Configure(IApplicationBuilder app, IHostingEnvironment env)


{
app.UseAzureAppConfiguration();

services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

app.UseMvc();
}

The middleware uses the refresh configuration specified in the AddAzureAppConfiguration method in
Program.cs to trigger a refresh for each request received by the ASP.NET Core web app. For each request, a
refresh operation is triggered and the client library checks if the cached value for the registered
configuration setting has expired. If it's expired, it's refreshed.

Use the latest configuration data


1. Open HomeController.cs in the Controllers directory, and add a reference to the
Microsoft.Extensions.Options package.
using Microsoft.Extensions.Options;

2. Update the HomeController class to receive Settings through dependency injection, and make use of its
values.
.NET Core 2.x
.NET Core 3.x

public class HomeController : Controller


{
private readonly Settings _settings;
public HomeController(IOptionsSnapshot<Settings> settings)
{
_settings = settings.Value;
}

public IActionResult Index()


{
ViewData["BackgroundColor"] = _settings.BackgroundColor;
ViewData["FontSize"] = _settings.FontSize;
ViewData["FontColor"] = _settings.FontColor;
ViewData["Message"] = _settings.Message;

return View();
}
}

3. Open Index.cshtml in the Views > Home directory, and replace its content with the following script:

<!DOCTYPE html>
<html lang="en">
<style>
body {
background-color: @ViewData["BackgroundColor"]
}
h1 {
color: @ViewData["FontColor"];
font-size: @ViewData["FontSize"]px;
}
</style>
<head>
<title>Index View</title>
</head>
<body>
<h1>@ViewData["Message"]</h1>
</body>
</html>

Build and run the app locally


1. To build the app by using the .NET Core CLI, run the following command in the command shell:

dotnet build

2. After the build successfully completes, run the following command to run the web app locally:

dotnet run
3. Open a browser window, and go to the URL shown in the dotnet run output.

4. Sign in to the Azure portal. Select All resources , and select the App Configuration store instance that you
created in the quickstart.
5. Select Configuration Explorer , and update the values of the following keys:

K EY VA L UE

TestApp:Settings:BackgroundColor green

TestApp:Settings:FontColor lightGray

TestApp:Settings:Message Data from Azure App Configuration - now with live


updates!

TestApp:Settings:Sentinel 2

6. Refresh the browser page to see the new configuration settings. You may need to refresh more than once
for the changes to be reflected.
Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this tutorial, you enabled your ASP.NET Core web app to dynamically refresh configuration settings from App
Configuration. To learn how to use an Azure-managed identity to streamline the access to App Configuration,
continue to the next tutorial.
Managed identity integration
Tutorial: Use dynamic configuration in a .NET Core
app
9/22/2020 • 4 minutes to read • Edit Online

The App Configuration .NET Core client library supports updating a set of configuration settings on demand
without causing an application to restart. This can be implemented by first getting an instance of
IConfigurationRefresher from the options for the configuration provider and then calling TryRefreshAsync on that
instance anywhere in your code.
In order to keep the settings updated and avoid too many calls to the configuration store, a cache is used for each
setting. Until the cached value of a setting has expired, the refresh operation does not update the value, even when
the value has changed in the configuration store. The default expiration time for each request is 30 seconds, but it
can be overridden if required.
This tutorial shows how you can implement dynamic configuration updates in your code. It builds on the app
introduced in the quickstarts. Before you continue, finish Create a .NET Core app with App Configuration first.
You can use any code editor to do the steps in this tutorial. Visual Studio Code is an excellent option that's available
on the Windows, macOS, and Linux platforms.
In this tutorial, you learn how to:
Set up your .NET Core app to update its configuration in response to changes in an App Configuration store.
Consume the latest configuration in your application.

Prerequisites
To do this tutorial, install the .NET Core SDK.
If you don't have an Azure subscription, create a free account before you begin.

Reload data from App Configuration


Open Program.cs and update the file to add a reference to the System.Threading.Tasks namespace, to specify
refresh configuration in the AddAzureAppConfiguration method, and to trigger manual refresh using the
TryRefreshAsync method.
using System;
using System.Threading.Tasks;

namespace TestConsole
{
class Program
{
private static IConfiguration _configuration = null;
private static IConfigurationRefresher _refresher = null;

static void Main(string[] args)


{
var builder = new ConfigurationBuilder();
builder.AddAzureAppConfiguration(options =>
{
options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
.ConfigureRefresh(refresh =>
{
refresh.Register("TestApp:Settings:Message")
.SetCacheExpiration(TimeSpan.FromSeconds(10));
});

_refresher = options.GetRefresher();
});

_configuration = builder.Build();
PrintMessage().Wait();
}

private static async Task PrintMessage()


{
Console.WriteLine(_configuration["TestApp:Settings:Message"] ?? "Hello world!");

// Wait for the user to press Enter


Console.ReadLine();

await _refresher.TryRefreshAsync();
Console.WriteLine(_configuration["TestApp:Settings:Message"] ?? "Hello world!");
}
}
}

The ConfigureRefresh method is used to specify the settings used to update the configuration data with the App
Configuration store when a refresh operation is triggered. An instance of IConfigurationRefresher can be retrieved
by calling GetRefresher method on the options provided to AddAzureAppConfiguration method, and the
TryRefreshAsync method on this instance could be used to trigger a refresh operation anywhere in your code.

NOTE
The default cache expiration time for a configuration setting is 30 seconds, but can be overridden by calling the
SetCacheExpiration method on the options initializer passed as an argument to the ConfigureRefresh method.

Build and run the app locally


1. Set an environment variable named ConnectionString , and set it to the access key to your App
Configuration store. If you use the Windows command prompt, run the following command and restart the
command prompt to allow the change to take effect:

setx ConnectionString "connection-string-of-your-app-configuration-store"


If you use Windows PowerShell, run the following command:

$Env:ConnectionString = "connection-string-of-your-app-configuration-store"

If you use macOS or Linux, run the following command:

export ConnectionString='connection-string-of-your-app-configuration-store'

2. Run the following command to build the console app:

dotnet build

3. After the build successfully completes, run the following command to run the app locally:

dotnet run

4. Sign in to the Azure portal. Select All resources , and select the App Configuration store instance that you
created in the quickstart.
5. Select Configuration Explorer , and update the values of the following keys:

K EY VA L UE

TestApp:Settings:Message Data from Azure App Configuration - Updated

6. Press the Enter key to trigger a refresh and print the updated value in the Command Prompt or PowerShell
window.
NOTE
Since the cache expiration time was set to 10 seconds using the SetCacheExpiration method while specifying the
configuration for the refresh operation, the value for the configuration setting will only be updated if at least 10
seconds have elapsed since the last refresh for that setting.

Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this tutorial, you enabled your .NET Core app to dynamically refresh configuration settings from App
Configuration. To learn how to use an Azure managed identity to streamline the access to App Configuration,
continue to the next tutorial.
Managed identity integration
Tutorial: Use dynamic configuration in a .NET
Framework app
9/22/2020 • 6 minutes to read • Edit Online

The App Configuration .NET client library supports updating a set of configuration settings on demand without
causing an application to restart. This can be implemented by first getting an instance of IConfigurationRefresher
from the options for the configuration provider and then calling TryRefreshAsync on that instance anywhere in
your code.
In order to keep the settings updated and avoid too many calls to the configuration store, a cache is used for each
setting. Until the cached value of a setting has expired, the refresh operation does not update the value, even when
the value has changed in the configuration store. The default expiration time for each request is 30 seconds, but it
can be overridden if required.
This tutorial shows how you can implement dynamic configuration updates in your code. It builds on the app
introduced in the quickstarts. Before you continue, finish Create a .NET Framework app with App Configuration
first.
In this tutorial, you learn how to:
Set up your .NET Framework app to update its configuration in response to changes in an App Configuration
store.
Inject the latest configuration in your application.

Prerequisites
Azure subscription - create one for free
Visual Studio 2019
.NET Framework 4.7.1 or later

Create an App Configuration store


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and
select Enter.
2. Select App Configuration from the search results, and then select Create .

3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N


SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the
same time by deleting the resource
group. For more information, see Use
resource groups to manage your
Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted. For
the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.

4. Select Create . The deployment might take a few minutes.


5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.
6. Select Configuration Explorer > + Create > Key-value to add the following key-value pairs:

K EY VA L UE

TestApp:Settings:Message Data from Azure App Configuration

Leave Label and Content Type empty for now.


7. Select Apply .

Create a .NET Framework console app


1. Start Visual Studio, and select File > New > Project .
2. In Create a new project , filter on the Console project type and click on Console App (.NET
Framework) . Click Next .
3. In Configure your new project , enter a project name. Under Framework , select .NET Framework 4.7.1
or higher. Click Create .

Reload data from App Configuration


1. Right-click your project, and select Manage NuGet Packages . On the Browse tab, search and add the
Microsoft.Extensions.Configuration.AzureAppConfiguration NuGet package to your project. If you can't find
it, select the Include prerelease check box.
2. Open Program.cs, and add a reference to the .NET Core App Configuration provider.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;

3. Add two variables to store configuration-related objects.

private static IConfiguration _configuration = null;


private static IConfigurationRefresher _refresher = null;

4. Update the Main method to connect to App Configuration with the specified refresh options.
static void Main(string[] args)
{
var builder = new ConfigurationBuilder();
builder.AddAzureAppConfiguration(options =>
{
options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
.ConfigureRefresh(refresh =>
{
refresh.Register("TestApp:Settings:Message")
.SetCacheExpiration(TimeSpan.FromSeconds(10));
});

_refresher = options.GetRefresher();
});

_configuration = builder.Build();
PrintMessage().Wait();
}

The ConfigureRefresh method is used to specify the settings used to update the configuration data with the
App Configuration store when a refresh operation is triggered. An instance of IConfigurationRefresher can
be retrieved by calling GetRefresher method on the options provided to AddAzureAppConfiguration method,
and the TryRefreshAsync method on this instance can be used to trigger a refresh operation anywhere in
your code.

NOTE
The default cache expiration time for a configuration setting is 30 seconds, but can be overridden by calling the
SetCacheExpiration method on the options initializer passed as an argument to the ConfigureRefresh method.

5. Add a method called PrintMessage() that triggers a manual refresh of configuration data from App
Configuration.

private static async Task PrintMessage()


{
Console.WriteLine(_configuration["TestApp:Settings:Message"] ?? "Hello world!");

// Wait for the user to press Enter


Console.ReadLine();

await _refresher.TryRefreshAsync();
Console.WriteLine(_configuration["TestApp:Settings:Message"] ?? "Hello world!");
}

Build and run the app locally


1. Set an environment variable named ConnectionString , and set it to the access key to your App
Configuration store. If you use the Windows command prompt, run the following command and restart the
command prompt to allow the change to take effect:

setx ConnectionString "connection-string-of-your-app-configuration-store"

If you use Windows PowerShell, run the following command:

$Env:ConnectionString = "connection-string-of-your-app-configuration-store"
2. Restart Visual Studio to allow the change to take effect.
3. Press Ctrl + F5 to build and run the console app.

4. Sign in to the Azure portal. Select All resources , and select the App Configuration store instance that you
created in the quickstart.
5. Select Configuration Explorer , and update the values of the following keys:

K EY VA L UE

TestApp:Settings:Message Data from Azure App Configuration - Updated

6. Back in the running application, press the Enter key to trigger a refresh and print the updated value in the
Command Prompt or PowerShell window.
NOTE
Since the cache expiration time was set to 10 seconds using the SetCacheExpiration method while specifying the
configuration for the refresh operation, the value for the configuration setting will only be updated if at least 10
seconds have elapsed since the last refresh for that setting.

Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this tutorial, you enabled your .NET Framework app to dynamically refresh configuration settings from App
Configuration. To learn how to use an Azure managed identity to streamline the access to App Configuration,
continue to the next tutorial.
Managed identity integration
Tutorial: Use dynamic configuration in an Azure
Functions app
9/22/2020 • 3 minutes to read • Edit Online

The App Configuration .NET Standard configuration provider supports caching and refreshing configuration
dynamically driven by application activity. This tutorial shows how you can implement dynamic configuration
updates in your code. It builds on the Azure Functions app introduced in the quickstarts. Before you continue, finish
Create an Azure functions app with Azure App Configuration first.
In this tutorial, you learn how to:
Set up your Azure Functions app to update its configuration in response to changes in an App Configuration
store.
Inject the latest configuration to your Azure Functions calls.

Prerequisites
Azure subscription - create one for free
Visual Studio 2019 with the Azure development workload
Azure Functions tools
Finish quickstart Create an Azure functions app with Azure App Configuration

Reload data from App Configuration


1. Open Function1.cs. In addition to the static property Configuration , add a new static property
ConfigurationRefresher to keep a singleton instance of IConfigurationRefresher that will be used to signal
configuration updates during Functions calls later.

private static IConfiguration Configuration { set; get; }


private static IConfigurationRefresher ConfigurationRefresher { set; get; }

2. Update the constructor and use the ConfigureRefresh method to specify the setting to be refreshed from
the App Configuration store. An instance of IConfigurationRefresher is retrieved using GetRefresher
method. Optionally, we also change the configuration cache expiration time window to 1 minute from the
default 30 seconds.

static Function1()
{
var builder = new ConfigurationBuilder();
builder.AddAzureAppConfiguration(options =>
{
options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
.ConfigureRefresh(refreshOptions =>
refreshOptions.Register("TestApp:Settings:Message")
.SetCacheExpiration(TimeSpan.FromSeconds(60))
);
ConfigurationRefresher = options.GetRefresher();
});
Configuration = builder.Build();
}
3. Update the Run method and signal to refresh the configuration using the TryRefreshAsync method at the
beginning of the Functions call. This will be no-op if the cache expiration time window isn't reached. Remove
the await operator if you prefer the configuration to be refreshed without blocking.

public static async Task<IActionResult> Run(


[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger
log)
{
log.LogInformation("C# HTTP trigger function processed a request.");

await ConfigurationRefresher.TryRefreshAsync();

string keyName = "TestApp:Settings:Message";


string message = Configuration[keyName];

return message != null


? (ActionResult)new OkObjectResult(message)
: new BadRequestObjectResult($"Please create a key-value with the key '{keyName}' in App
Configuration.");
}

Test the function locally


1. Set an environment variable named ConnectionString , and set it to the access key to your app
configuration store. If you use the Windows command prompt, run the following command and restart the
command prompt to allow the change to take effect:

setx ConnectionString "connection-string-of-your-app-configuration-store"

If you use Windows PowerShell, run the following command:

$Env:ConnectionString = "connection-string-of-your-app-configuration-store"

If you use macOS or Linux, run the following command:

export ConnectionString='connection-string-of-your-app-configuration-store'

2. To test your function, press F5. If prompted, accept the request from Visual Studio to download and install
Azure Functions Core (CLI) tools. You might also need to enable a firewall exception so that the tools can
handle HTTP requests.
3. Copy the URL of your function from the Azure Functions runtime output.
4. Paste the URL for the HTTP request into your browser's address bar. The following image shows the
response in the browser to the local GET request returned by the function.

5. Sign in to the Azure portal. Select All resources , and select the App Configuration store instance that you
created in the quickstart.
6. Select Configuration Explorer , and update the values of the following key:

K EY VA L UE

TestApp:Settings:Message Data from Azure App Configuration - Updated

7. Refresh the browser a few times. When the cached setting expires after a minute, the page shows the
response of the Functions call with updated value.

The example code used in this tutorial can be downloaded from App Configuration GitHub repo
Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this tutorial, you enabled your Azure Functions app to dynamically refresh configuration settings from App
Configuration. To learn how to use an Azure managed identity to streamline the access to App Configuration,
continue to the next tutorial.
Managed identity integration
Tutorial: Use dynamic configuration in a Java Spring
app
9/22/2020 • 2 minutes to read • Edit Online

The App Configuration Spring Boot client library supports updating a set of configuration settings on demand,
without causing an application to restart. The client library caches each setting to avoid too many calls to the
configuration store. The refresh operation doesn't update the value until the cached value has expired, even when
the value has changed in the configuration store. The default expiration time for each request is 30 seconds. It can
be overridden if necessary.
You can check for updated settings on demand by calling AppConfigurationRefresh 's refreshConfigurations()
method.
Alternatively, you can use the spring-cloud-azure-appconfiguration-config-web package, which takes a dependency
on spring-web to handle automated refresh.

Use automated refresh


To use automated refresh, start with a Spring Boot app that uses App Configuration, such as the app you create by
following the Spring Boot quickstart for App Configuration.
Then, open the pom.xml file in a text editor, and add a <dependency> for
spring-cloud-azure-appconfiguration-config-web .

Spring Cloud 1.1.x

<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-appconfiguration-config-web</artifactId>
<version>1.1.5</version>
</dependency>

Spring Cloud 1.2.x

<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-appconfiguration-config-web</artifactId>
<version>1.2.7</version>
</dependency>

Run and test the app locally


1. Build your Spring Boot application with Maven and run it.

mvn clean package


mvn spring-boot:run

2. Open a browser window, and go to the URL: http://localhost:8080 . You will see the message associated
with your key.
You can also use curl to test your application, for example:

curl -X GET http://localhost:8080/

3. To test dynamic configuration, open the Azure App Configuration portal associated with your application.
Select Configuration Explorer , and update the value of your displayed key, for example: | Key | Value | |---
|---| | application/config.message | Hello - Updated |
4. Refresh the browser page to see the new message displayed.

Next steps
In this tutorial, you enabled your Spring Boot app to dynamically refresh configuration settings from App
Configuration. To learn how to use an Azure managed identity to streamline the access to App Configuration,
continue to the next tutorial.
Managed identity integration
Tutorial: Use feature flags in an ASP.NET Core app
9/22/2020 • 6 minutes to read • Edit Online

The .NET Core Feature Management libraries provide idiomatic support for implementing feature flags in a .NET or
ASP.NET Core application. These libraries allow you to declaratively add feature flags to your code so that you don't
have to write all the if statements for them manually.
The Feature Management libraries also manage feature flag lifecycles behind the scenes. For example, the libraries
refresh and cache flag states, or guarantee a flag state to be immutable during a request call. In addition, the
ASP.NET Core library offers out-of-the-box integrations, including MVC controller actions, views, routes, and
middleware.
The Add feature flags to an ASP.NET Core app Quickstart shows several ways to add feature flags in an ASP.NET
Core application. This tutorial explains these methods in more detail. For a complete reference, see the ASP.NET
Core feature management documentation.
In this tutorial, you will learn how to:
Add feature flags in key parts of your application to control feature availability.
Integrate with App Configuration when you're using it to manage feature flags.

Set up feature management


Add a reference to the Microsoft.FeatureManagement.AspNetCore and Microsoft.FeatureManagement NuGet packages
to utilize the .NET Core feature manager.
The .NET Core feature manager IFeatureManager gets feature flags from the framework's native configuration
system. As a result, you can define your application's feature flags by using any configuration source that .NET Core
supports, including the local appsettings.json file or environment variables. IFeatureManager relies on .NET Core
dependency injection. You can register the feature management services by using standard conventions:

using Microsoft.FeatureManagement;

public class Startup


{
public void ConfigureServices(IServiceCollection services)
{
services.AddFeatureManagement();
}
}

By default, the feature manager retrieves feature flags from the "FeatureManagement" section of the .NET Core
configuration data. The following example tells the feature manager to read from a different section called
"MyFeatureFlags" instead:
using Microsoft.FeatureManagement;

public class Startup


{
public void ConfigureServices(IServiceCollection services)
{
services.AddFeatureManagement(options =>
{
options.UseConfiguration(Configuration.GetSection("MyFeatureFlags"));
});
}
}

If you use filters in your feature flags, you need to include an additional library and register it. The following
example shows how to use a built-in feature filter called PercentageFilter :

using Microsoft.FeatureManagement;
using Microsoft.FeatureManagement.FeatureFilters;

public class Startup


{
public void ConfigureServices(IServiceCollection services)
{
services.AddFeatureManagement()
.AddFeatureFilter<PercentageFilter>();
}
}

We recommend that you keep feature flags outside the application and manage them separately. Doing so allows
you to modify flag states at any time and have those changes take effect in the application right away. App
Configuration provides a centralized place for organizing and controlling all your feature flags through a dedicated
portal UI. App Configuration also delivers the flags to your application directly through its .NET Core client
libraries.
The easiest way to connect your ASP.NET Core application to App Configuration is through the configuration
provider Microsoft.Azure.AppConfiguration.AspNetCore . Follow these steps to use this NuGet package.
1. Open Program.cs file and add the following code.

using Microsoft.Extensions.Configuration.AzureAppConfiguration;

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) => {
var settings = config.Build();
config.AddAzureAppConfiguration(options => {
options.Connect(settings["ConnectionStrings:AppConfig"])
.UseFeatureFlags();
});
})
.UseStartup<Startup>();

2. Open Startup.cs and update the Configure method to add a middleware to allow the feature flag values to
be refreshed at a recurring interval while the ASP.NET Core web app continues to receive requests.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAzureAppConfiguration();
app.UseMvc();
}

Feature flag values are expected to change over time. By default, the feature flag values are cached for a period of
30 seconds, so a refresh operation triggered when the middleware receives a request would not update the value
until the cached value expires. The following code shows how to change the cache expiration time or polling
interval to 5 minutes in the options.UseFeatureFlags() call.

config.AddAzureAppConfiguration(options => {
options.Connect(settings["ConnectionStrings:AppConfig"])
.UseFeatureFlags(featureFlagOptions => {
featureFlagOptions.CacheExpirationTime = TimeSpan.FromMinutes(5);
});
});

Feature flag declaration


Each feature flag has two parts: a name and a list of one or more filters that are used to evaluate if a feature's state
is on (that is, when its value is True ). A filter defines a use case for when a feature should be turned on.
When a feature flag has multiple filters, the filter list is traversed in order until one of the filters determines the
feature should be enabled. At that point, the feature flag is on, and any remaining filter results are skipped. If no
filter indicates the feature should be enabled, the feature flag is off.
The feature manager supports appsettings.json as a configuration source for feature flags. The following example
shows how to set up feature flags in a JSON file:

"FeatureManagement": {
"FeatureA": true, // Feature flag set to on
"FeatureB": false, // Feature flag set to off
"FeatureC": {
"EnabledFor": [
{
"Name": "Percentage",
"Parameters": {
"Value": 50
}
}
]
}
}

By convention, the FeatureManagement section of this JSON document is used for feature flag settings. The prior
example shows three feature flags with their filters defined in the EnabledFor property:
FeatureA is on.
FeatureB is off.
FeatureC specifies a filter named Percentage with a Parameters property. Percentage is a configurable filter.
In this example, Percentage specifies a 50-percent probability for the FeatureC flag to be on.

Feature flag references


So that you can easily reference feature flags in code, you should define them as enum variables:
public enum MyFeatureFlags
{
FeatureA,
FeatureB,
FeatureC
}

Feature flag checks


The basic pattern of feature management is to first check if a feature flag is set to on. If so, the feature manager
then runs the actions that the feature contains. For example:

IFeatureManager featureManager;
...
if (await featureManager.IsEnabledAsync(nameof(MyFeatureFlags.FeatureA)))
{
// Run the following code
}

Dependency injection
In ASP.NET Core MVC, you can access the feature manager IFeatureManager through dependency injection:

public class HomeController : Controller


{
private readonly IFeatureManager _featureManager;

public HomeController(IFeatureManager featureManager)


{
_featureManager = featureManager;
}
}

Controller actions
In MVC controllers, you use the FeatureGate attribute to control whether a whole controller class or a specific
action is enabled. The following HomeController controller requires FeatureA to be on before any action the
controller class contains can be executed:

using Microsoft.FeatureManagement.Mvc;

[FeatureGate(MyFeatureFlags.FeatureA)]
public class HomeController : Controller
{
...
}

The following Index action requires FeatureA to be on before it can run:


using Microsoft.FeatureManagement.Mvc;

[FeatureGate(MyFeatureFlags.FeatureA)]
public IActionResult Index()
{
return View();
}

When an MVC controller or action is blocked because the controlling feature flag is off, a registered
IDisabledFeaturesHandler interface is called. The default IDisabledFeaturesHandler interface returns a 404 status
code to the client with no response body.

MVC views
In MVC views, you can use a <feature> tag to render content based on whether a feature flag is enabled:

<feature name="FeatureA">
<p>This can only be seen if 'FeatureA' is enabled.</p>
</feature>

To display alternate content when the requirements are not met the negate attribute can be used.

<feature name="FeatureA" negate="true">


<p>This will be shown if 'FeatureA' is disabled.</p>
</feature>

The feature <feature> tag can also be used to show content if any or all features in a list are enabled.

<feature name="FeatureA, FeatureB" requirement="All">


<p>This can only be seen if 'FeatureA' and 'FeatureB' are enabled.</p>
</feature>
<feature name="FeatureA, FeatureB" requirement="Any">
<p>This can be seen if 'FeatureA', 'FeatureB', or both are enabled.</p>
</feature>

MVC filters
You can set up MVC filters so that they're activated based on the state of a feature flag. The following code adds an
MVC filter named SomeMvcFilter . This filter is triggered within the MVC pipeline only if FeatureA is enabled. This
capability is limited to IAsyncActionFilter .

using Microsoft.FeatureManagement.FeatureFilters;

IConfiguration Configuration { get; set;}

public void ConfigureServices(IServiceCollection services)


{
services.AddMvc(options => {
options.Filters.AddForFeature<SomeMvcFilter>(nameof(MyFeatureFlags.FeatureA));
});
}

Middleware
You can also use feature flags to conditionally add application branches and middleware. The following code
inserts a middleware component in the request pipeline only when FeatureA is enabled:

app.UseMiddlewareForFeature<ThirdPartyMiddleware>(nameof(MyFeatureFlags.FeatureA));

This code builds off the more-generic capability to branch the entire application based on a feature flag:

app.UseForFeature(featureName, appBuilder => {


appBuilder.UseMiddleware<T>();
});

Next steps
In this tutorial, you learned how to implement feature flags in your ASP.NET Core application by using the
Microsoft.FeatureManagement libraries. For more information about feature management support in ASP.NET Core
and App Configuration, see the following resources:
ASP.NET Core feature flag sample code
Microsoft.FeatureManagement documentation
Manage feature flags
Tutorial: Use feature flags in a Spring Boot app
9/22/2020 • 4 minutes to read • Edit Online

The Spring Boot Core Feature Management libraries provide support for implementing feature flags in a Spring
Boot application. These libraries allow you to declaratively add feature flags to your code.
The Feature Management libraries also manage feature flag lifecycles behind the scenes. For example, the libraries
refresh and cache flag states, or guarantee a flag state to be immutable during a request call. In addition, the Spring
Boot library offers integrations, including MVC controller actions, routes, and middleware.
The Add feature flags to a Spring Boot app Quickstart shows several ways to add feature flags in a Spring Boot
application. This tutorial explains these methods in more detail.
In this tutorial, you will learn how to:
Add feature flags in key parts of your application to control feature availability.
Integrate with App Configuration when you're using it to manage feature flags.

Set up feature management


The Spring Boot feature manager FeatureManager gets feature flags from the framework's native configuration
system. As a result, you can define your application's feature flags by using any configuration source that Spring
Boot supports, including the local bootstrap.yml file or environment variables. FeatureManager relies on
dependency injection. You can register the feature management services by using standard conventions:

private FeatureManager featureManager;

public HelloController(FeatureManager featureManager) {


this.featureManager = featureManager;
}

We recommend that you keep feature flags outside the application and manage them separately. Doing so allows
you to modify flag states at any time and have those changes take effect in the application right away. App
Configuration provides a centralized place for organizing and controlling all your feature flags through a dedicated
portal UI. App Configuration also delivers the flags to your application directly through its Spring Boot client
libraries.
The easiest way to connect your Spring Boot application to App Configuration is through the configuration
provider:
Spring Cloud 1.1.x

<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-feature-management-web</artifactId>
<version>1.1.2</version>
</dependency>

Spring Cloud 1.2.x


<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-feature-management-web</artifactId>
<version>1.2.2</version>
</dependency>

Feature flag declaration


Each feature flag has two parts: a name and a list of one or more filters that are used to evaluate if a feature's state
is on (that is, when its value is True ). A filter defines a use case for when a feature should be turned on.
When a feature flag has multiple filters, the filter list is traversed in order until one of the filters determines the
feature should be enabled. At that point, the feature flag is on, and any remaining filter results are skipped. If no
filter indicates the feature should be enabled, the feature flag is off.
The feature manager supports application.yml as a configuration source for feature flags. The following example
shows how to set up feature flags in a YAML file:

feature-management:
feature-set:
feature-a: true
feature-b: false
feature-c:
enabled-for:
-
name: Percentage
parameters:
value: 50

By convention, the feature-management section of this YML document is used for feature flag settings. The prior
example shows three feature flags with their filters defined in the EnabledFor property:
feature-a is on.
feature-b is off.
feature-c specifies a filter named Percentage with a parameters property. Percentage is a configurable filter.
In this example, Percentage specifies a 50-percent probability for the feature-c flag to be on.

Feature flag checks


The basic pattern of feature management is to first check if a feature flag is set to on. If so, the feature manager
then runs the actions that the feature contains. For example:

private FeatureManager featureManager;


...
if (featureManager.isEnabledAsync("feature-a").block()) {
// Run the following code
}

Dependency injection
In Spring Boot, you can access the feature manager FeatureManager through dependency injection:
@Controller
@ConfigurationProperties("controller")
public class HomeController {
private FeatureManager featureManager;

public HomeController(FeatureManager featureManager) {


this.featureManager = featureManager;
}
}

Controller actions
In MVC controllers, you use the @FeatureGate attribute to control whether a specific action is enabled. The
following Index action requires feature-a to be on before it can run:

@GetMapping("/")
@FeatureGate(feature = "feature-a")
public String index(Model model) {
...
}

When an MVC controller or action is blocked because the controlling feature flag is off, a registered
IDisabledFeaturesHandler interface is called. The default IDisabledFeaturesHandler interface returns a 404 status
code to the client with no response body.

MVC filters
You can set up MVC filters so that they're activated based on the state of a feature flag. The following code adds an
MVC filter named FeatureFlagFilter . This filter is triggered within the MVC pipeline only if feature-a is enabled.

@Component
public class FeatureFlagFilter implements Filter {

@Autowired
private FeatureManager featureManager;

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if(!featureManager.isEnabledAsync("feature-a").block()) {
chain.doFilter(request, response);
return;
}
...
chain.doFilter(request, response);
}
}

Routes
You can use feature flags to redirect routes. The following code will redirect a user from feature-a is enabled:
@GetMapping("/redirect")
@FeatureGate(feature = "feature-a", fallback = "/getOldFeature")
public String getNewFeature() {
// Some New Code
}

@GetMapping("/getOldFeature")
public String getOldFeature() {
// Some New Code
}

Next steps
In this tutorial, you learned how to implement feature flags in your Spring Boot application by using the
spring-cloud-azure-feature-management-web libraries. For more information about feature management support in
Spring Boot and App Configuration, see the following resources:
Spring Boot feature flag sample code
Manage feature flags
Tutorial: Manage feature flags in Azure App
Configuration
9/22/2020 • 2 minutes to read • Edit Online

You can store all feature flags in Azure App Configuration and administer them from a single place. App
Configuration has a portal UI named Feature Manager that's designed specifically for feature flags. App
Configuration also natively supports the .NET Core feature-flag data schema.
In this tutorial, you learn how to:
Define and manage feature flags in App Configuration.
Access feature flags from your application.

Create feature flags


The Feature Manager in the Azure portal for App Configuration provides a UI for creating and managing the
feature flags that you use in your applications.
To add a new feature flag:
1. Select Feature Manager > +Add to add a feature flag.

2. Enter a unique key name for the feature flag. You need this name to reference the flag in your code.
3. If you want, give the feature flag a description.
4. Set the initial state of the feature flag. This state is usually Off or On. The On state changes to Conditional if
you add a filter to the feature flag.
5. When the state is On, select +Add filter to specify any additional conditions to qualify the state. Enter a
built-in or custom filter key, and then select +Add parameter to associate one or more parameters with
the filter. Built-in filters include:

K EY JSO N PA RA M ET ERS

Microsoft.Percentage {"Value": 0-100 percent}

Microsoft.TimeWindow {"Start": UTC time, "End": UTC time}


Update feature flag states
To change a feature flag's state value:
1. Select Feature Manager .
2. To the right of a feature flag you want to modify, select the ellipsis (...), and then select Edit .
3. Set a new state for the feature flag.

Access feature flags


Feature flags created by the Feature Manager are stored and retrieved as regular key values. They're kept under a
special namespace prefix .appconfig.featureflag . To view the underlying key values, use the Configuration
Explorer. Your application can retrieve these values by using the App Configuration configuration providers, SDKs,
command-line extensions, and REST APIs.

Next steps
In this tutorial, you learned how to manage feature flags and their states by using App Configuration. For more
information about feature-management support in App Configuration and ASP.NET Core, see the following article:
Use feature flags in an ASP.NET Core app
Tutorial: Use Key Vault references in an ASP.NET Core
app
9/22/2020 • 6 minutes to read • Edit Online

In this tutorial, you learn how to use the Azure App Configuration service together with Azure Key Vault. App
Configuration and Key Vault are complementary services used side by side in most application deployments.
App Configuration helps you use the services together by creating keys that reference values stored in Key Vault.
When App Configuration creates such keys, it stores the URIs of Key Vault values rather than the values
themselves.
Your application uses the App Configuration client provider to retrieve Key Vault references, just as it does for any
other keys stored in App Configuration. In this case, the values stored in App Configuration are URIs that reference
the values in the Key Vault. They are not Key Vault values or credentials. Because the client provider recognizes the
keys as Key Vault references, it uses Key Vault to retrieve their values.
Your application is responsible for authenticating properly to both App Configuration and Key Vault. The two
services don't communicate directly.
This tutorial shows you how to implement Key Vault references in your code. It builds on the web app introduced in
the quickstarts. Before you continue, finish Create an ASP.NET Core app with App Configuration first.
You can use any code editor to do the steps in this tutorial. For example, Visual Studio Code is a cross-platform
code editor that's available for the Windows, macOS, and Linux operating systems.
In this tutorial, you learn how to:
Create an App Configuration key that references a value stored in Key Vault.
Access the value of this key from an ASP.NET Core web application.

Prerequisites
Before you start this tutorial, install the .NET Core SDK.
If you don't have an Azure subscription, create a free account before you begin.

Create a vault
1. Select the Create a resource option in the upper-left corner of the Azure portal:
2. In the search box, enter Key Vault .
3. From the results list, select Key vaults on the left.
4. In Key vaults , select Add .
5. On the right in Create key vault , provide the following information:
Select Subscription to choose a subscription.
In Resource Group , select Create new and enter a resource group name.
In Key vault name , a unique name is required. For this tutorial, enter Contoso-vault2 .
In the Region drop-down list, choose a location.
6. Leave the other Create key vault options with their default values.
7. Select Create .
At this point, your Azure account is the only one authorized to access this new vault.
Add a secret to Key Vault
To add a secret to the vault, you need to take just a few additional steps. In this case, add a message that you can
use to test Key Vault retrieval. The message is called Message , and you store the value "Hello from Key Vault" in it.
1. From the Key Vault properties pages, select Secrets .
2. Select Generate/Impor t .
3. In the Create a secret pane, enter the following values:
Upload options : Enter Manual .
Name : Enter Message .
Value : Enter Hello from Key Vault .
4. Leave the other Create a secret properties with their default values.
5. Select Create .

Add a Key Vault reference to App Configuration


1. Sign in to the Azure portal. Select All resources , and then select the App Configuration store instance that
you created in the quickstart.
2. Select Configuration Explorer .
3. Select + Create > Key vault reference , and then specify the following values:
Key : Select TestApp:Settings:KeyVaultMessage .
Label : Leave this value blank.
Subscription , Resource group , and Key vault : Enter the values corresponding to those in the key
vault you created in the previous section.
Secret : Select the secret named Message that you created in the previous section.
Connect to Key Vault
1. In this tutorial, you use a service principal for authentication to Key Vault. To create this service principal, use
the Azure CLI az ad sp create-for-rbac command:

az ad sp create-for-rbac -n "http://mySP" --sdk-auth

This operation returns a series of key/value pairs:

{
"clientId": "7da18cae-779c-41fc-992e-0527854c6583",
"clientSecret": "b421b443-1669-4cd7-b5b1-394d5c945002",
"subscriptionId": "443e30da-feca-47c4-b68f-1636b75e16b3",
"tenantId": "35ad10f1-7799-4766-9acf-f2d946161b77",
"activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
"resourceManagerEndpointUrl": "https://management.azure.com/",
"sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
"galleryEndpointUrl": "https://gallery.azure.com/",
"managementEndpointUrl": "https://management.core.windows.net/"
}

2. Run the following command to let the service principal access your key vault:

az keyvault set-policy -n <your-unique-keyvault-name> --spn <clientId-of-your-service-principal> --


secret-permissions delete get list set --key-permissions create decrypt delete encrypt get list
unwrapKey wrapKey

3. Add environment variables to store the values of clientId, clientSecret, and tenantId.
Windows command prompt
PowerShell
Bash

setx AZURE_CLIENT_ID <clientId-of-your-service-principal>


setx AZURE_CLIENT_SECRET <clientSecret-of-your-service-principal>
setx AZURE_TENANT_ID <tenantId-of-your-service-principal>

NOTE
These Key Vault credentials are used only within your application. Your application authenticates directly to Key Vault
with these credentials. They are never passed to the App Configuration service.

4. Restart your terminal to load these new environment variables.

Update your code to use a Key Vault reference


1. Add a reference to the required NuGet packages by running the following command:

dotnet add package Azure.Identity

2. Open Program.cs, and add references to the following required packages:


using Azure.Identity;

3. Update the CreateWebHostBuilder method to use App Configuration by calling the


config.AddAzureAppConfiguration method. Include the ConfigureKeyVault option, and pass the correct
credentials to your Key Vault.
.NET Core 2.x
.NET Core 3.x

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();

config.AddAzureAppConfiguration(options =>
{
options.Connect(settings["ConnectionStrings:AppConfig"])
.ConfigureKeyVault(kv =>
{
kv.SetCredential(new DefaultAzureCredential());
});
});
})
.UseStartup<Startup>();

4. When you initialized the connection to App Configuration, you set up the connection to Key Vault by calling
the ConfigureKeyVault method. After the initialization, you can access the values of Key Vault references in
the same way you access the values of regular App Configuration keys.
To see this process in action, open Index.cshtml in the Views > Home folder. Replace its contents with the
following code:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<style>
body {
background-color: @Configuration["TestApp:Settings:BackgroundColor"]
}
h1 {
color: @Configuration["TestApp:Settings:FontColor"];
font-size: @Configuration["TestApp:Settings:FontSize"]px;
}
</style>

<h1>@Configuration["TestApp:Settings:Message"]
and @Configuration["TestApp:Settings:KeyVaultMessage"]</h1>

You access the value of the Key Vault reference TestApp:Settings:KeyVaultMessage in the same way as
for the configuration value of TestApp:Settings:Message .

Build and run the app locally


1. To build the app by using the .NET Core CLI, run the following command in the command shell:

dotnet build
2. After the build is complete, use the following command to run the web app locally:

dotnet run

3. Open a browser window, and go to http://localhost:5000 , which is the default URL for the web app hosted
locally.

Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this tutorial, you created an App Configuration key that references a value stored in Key Vault. To learn how to
add an Azure-managed service identity that streamlines access to App Configuration and Key Vault, continue to the
next tutorial.
Managed identity integration
Tutorial: Use Key Vault references in a Java Spring app
9/22/2020 • 6 minutes to read • Edit Online

In this tutorial, you learn how to use the Azure App Configuration service together with Azure Key Vault. App
Configuration and Key Vault are complementary services used side by side in most application deployments.
App Configuration helps you use the services together by creating keys that reference values stored in Key Vault.
When App Configuration creates such keys, it stores the URIs of Key Vault values rather than the values themselves.
Your application uses the App Configuration client provider to retrieve Key Vault references, just as it does for any
other keys stored in App Configuration. In this case, the values stored in App Configuration are URIs that reference
the values in the Key Vault. They are not Key Vault values or credentials. Because the client provider recognizes the
keys as Key Vault references, it uses Key Vault to retrieve their values.
Your application is responsible for authenticating properly to both App Configuration and Key Vault. The two
services don't communicate directly.
This tutorial shows you how to implement Key Vault references in your code. It builds on the web app introduced in
the quickstarts. Before you continue, complete Create a Java Spring app with App Configuration first.
You can use any code editor to do the steps in this tutorial. For example, Visual Studio Code is a cross-platform code
editor that's available for the Windows, macOS, and Linux operating systems.
In this tutorial, you learn how to:
Create an App Configuration key that references a value stored in Key Vault.
Access the value of this key from a Java Spring application.

Prerequisites
Azure subscription - create one for free
A supported Java Development Kit (JDK) with version 8.
Apache Maven version 3.0 or above.

Create a vault
1. Select the Create a resource option in the upper-left corner of the Azure portal:
2. In the search box, enter Key Vault .
3. From the results list, select Key vaults on the left.
4. In Key vaults , select Add .
5. On the right in Create key vault , provide the following information:
Select Subscription to choose a subscription.
In Resource Group , select Create new and enter a resource group name.
In Key vault name , a unique name is required. For this tutorial, enter Contoso-vault2 .
In the Region drop-down list, choose a location.
6. Leave the other Create key vault options with their default values.
7. Select Create .
At this point, your Azure account is the only one authorized to access this new vault.
Add a secret to Key Vault
To add a secret to the vault, you need to take just a few additional steps. In this case, add a message that you can
use to test Key Vault retrieval. The message is called Message , and you store the value "Hello from Key Vault" in it.
1. From the Key Vault properties pages, select Secrets .
2. Select Generate/Impor t .
3. In the Create a secret pane, enter the following values:
Upload options : Enter Manual .
Name : Enter Message .
Value : Enter Hello from Key Vault .
4. Leave the other Create a secret properties with their default values.
5. Select Create .

Add a Key Vault reference to App Configuration


1. Sign in to the Azure portal. Select All resources , and then select the App Configuration store instance that
you created in the quickstart.
2. Select Configuration Explorer .
3. Select + Create > Key vault reference , and then specify the following values:
Key : Select /application/config.keyvaultmessage
Label : Leave this value blank.
Subscription , Resource group , and Key vault : Enter the values corresponding to the values in the key
vault you created in the previous section.
Secret : Select the secret named Message that you created in the previous section.
Connect to Key Vault
1. In this tutorial, you use a service principal for authentication to Key Vault. To create this service principal, use
the Azure CLI az ad sp create-for-rbac command:

az ad sp create-for-rbac -n "http://mySP" --sdk-auth

This operation returns a series of key/value pairs:

{
"clientId": "7da18cae-779c-41fc-992e-0527854c6583",
"clientSecret": "b421b443-1669-4cd7-b5b1-394d5c945002",
"subscriptionId": "443e30da-feca-47c4-b68f-1636b75e16b3",
"tenantId": "35ad10f1-7799-4766-9acf-f2d946161b77",
"activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
"resourceManagerEndpointUrl": "https://management.azure.com/",
"sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
"galleryEndpointUrl": "https://gallery.azure.com/",
"managementEndpointUrl": "https://management.core.windows.net/"
}

2. Run the following command to let the service principal access your key vault:

az keyvault set-policy -n <your-unique-keyvault-name> --spn <clientId-of-your-service-principal> --


secret-permissions delete get

3. Run the following command to get your object-id, then add it to App Configuration.

az ad sp show --id <clientId-of-your-service-principal>


az role assignment create --role "App Configuration Data Reader" --assignee-object-id <objectId-of-your-
service-principal> --resource-group <your-resource-group>

4. Create the environment variables AZURE_CLIENT_ID , AZURE_CLIENT_SECRET , and


AZURE_TENANT_ID . Use the values for the service principal that were displayed in the previous steps. At
the command line, run the following commands and restart the command prompt to allow the change to
take effect:

setx AZURE_CLIENT_ID "clientId"


setx AZURE_CLIENT_SECRET "clientSecret"
setx AZURE_TENANT_ID "tenantId"

If you use Windows PowerShell, run the following command:

$Env:AZURE_CLIENT_ID = "clientId"
$Env:AZURE_CLIENT_SECRET = "clientSecret"
$Env:AZURE_TENANT_ID = "tenantId"

If you use macOS or Linux, run the following command:

export AZURE_CLIENT_ID ='clientId'


export AZURE_CLIENT_SECRET ='clientSecret'
export AZURE_TENANT_ID ='tenantId'
NOTE
These Key Vault credentials are only used within your application. Your application authenticates directly with Key Vault using
these credentials without involving the App Configuration service. The Key Vault provides authentication for both your
application and your App Configuration service without sharing or exposing keys.

Update your code to use a Key Vault reference


1. Create an environment variable called APP_CONFIGURATION_ENDPOINT . Set its value to the endpoint
of your App Configuration store. You can find the endpoint on the Access Keys blade in the Azure portal.
Restart the command prompt to allow the change to take effect.
2. Open bootstrap.properties in the resources folder. Update this file to use the
APP_CONFIGURATION_ENDPOINT value. Remove any references to a connection string in this file.

spring.cloud.azure.appconfiguration.stores[0].endpoint= ${APP_CONFIGURATION_ENDPOINT}

3. Open MessageProperties.java. Add a new variable called keyVaultMessage:

private String keyVaultMessage;

public String getKeyVaultMessage() {


return keyVaultMessage;
}

public void setKeyVaultMessage(String keyVaultMessage) {


this.keyVaultMessage = keyVaultMessage;
}

4. Open HelloController.java. Update the getMessage method to include the message retrieved from Key Vault.

@GetMapping
public String getMessage() {
return "Message: " + properties.getMessage() + "\nKey Vault message: " +
properties.getKeyVaultMessage();
}

5. Create a new file called AzureCredentials.java and add the code below.
package com.example.demo;

import com.azure.core.credential.TokenCredential;
import com.azure.identity.EnvironmentCredentialBuilder;
import com.microsoft.azure.spring.cloud.config.AppConfigurationCredentialProvider;
import com.microsoft.azure.spring.cloud.config.KeyVaultCredentialProvider;

public class AzureCredentials implements AppConfigurationCredentialProvider, KeyVaultCredentialProvider{

@Override
public TokenCredential getKeyVaultCredential(String uri) {
return getCredential();
}

@Override
public TokenCredential getAppConfigCredential(String uri) {
return getCredential();
}

private TokenCredential getCredential() {


return new EnvironmentCredentialBuilder().build();
}

6. Create a new file called AppConfiguration.java. And add the code below.

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfiguration {

@Bean
public AzureCredentials azureCredentials() {
return new AzureCredentials();
}
}

7. Create a new file in your resources META-INF directory called spring.factories and add the code below.

org.springframework.cloud.bootstrap.BootstrapConfiguration=\
com.example.demo.AppConfiguration

8. Build your Spring Boot application with Maven and run it, for example:

mvn clean package


mvn spring-boot:run

9. After your application is running, use curl to test your application, for example:

curl -X GET http://localhost:8080/

You see the message that you entered in the App Configuration store. You also see the message that you
entered in Key Vault.
Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this tutorial, you created an App Configuration key that references a value stored in Key Vault. To learn how to
use feature flags in your Java Spring application, continue to the next tutorial.
Managed identity integration
Push settings to App Configuration with Azure
Pipelines
9/22/2020 • 5 minutes to read • Edit Online

The Azure App Configuration Push task pushes key-values from a configuration file into your App Configuration
store. This task enables full circle functionality within the pipeline as you're now able to pull settings from the App
Configuration store as well as push settings to the App Configuration store.

Prerequisites
Azure subscription - create one for free
App Configuration resource - create one for free in the Azure portal.
Azure DevOps project - create one for free
Azure App Configuration Push task - download for free from the Visual Studio Marketplace.

Create a service connection


A service connection allows you to access resources in your Azure subscription from your Azure DevOps project.
1. In Azure DevOps, go to the project containing your target pipeline and open the Project settings at the bottom
left.
2. Under Pipelines select Ser vice connections and select New ser vice connection in the top right.
3. Select Azure Resource Manager .
4. Select Ser vice principal (automatic) .
5. Fill in your subscription and resource. Give your service connection a name.
Now that your service connection is created, find the name of the service principal assigned to it. You'll add a new
role assignment to this service principal in the next step.
1. Go to Project Settings > Ser vice connections .
2. Select the service connection that you created in the previous section.
3. Select Manage Ser vice Principal .
4. Note the Display name listed.

Add role assignment


Assign the proper App Configuration role assignments to the credentials being used within the task so that the task
can access the App Configuration store.
1. Navigate to your target App Configuration store.
2. On the left, select Access control (IAM) .
3. At the top, select + Add and pick Add role assignment .
4. Under Role , select App Configuration Data Owner . This role allows the task to read from and write to the
App Configuration store.
5. Select the service principal associated with the service connection that you created in the previous section.

Use in builds
This section will cover how to use the Azure App Configuration Push task in an Azure DevOps build pipeline.
1. Navigate to the build pipeline page by clicking Pipelines > Pipelines . Documentation for build pipelines can
be found here.
If you're creating a new build pipeline, select Show assistant on the right side of the pipeline, and search
for the Azure App Configuration Push task.
If you're using an existing build pipeline, navigate to the Tasks tab when editing the pipeline, and search
for the Azure App Configuration Push Task.
2. Configure the necessary parameters for the task to push the key-values from the configuration file to the App
Configuration store. The Configuration File Path parameter begins at the root of the file repository.
3. Save and queue a build. The build log will display any failures that occurred during the execution of the task.

Use in releases
This section will cover how to use the Azure App Configuration Push task in an Azure DevOps release pipelines.
1. Navigate to release pipeline page by selecting Pipelines > Releases . Documentation for release pipelines can
be found here.
2. Choose an existing release pipeline. If you don’t have one, select + New to create a new one.
3. Select the Edit button in the top-right corner to edit the release pipeline.
4. Choose the Stage to add the task. More information about stages can be found here.
5. Select + for that Job, then add the Azure App Configuration Push task under the Deploy tab.
6. Configure the necessary parameters within the task to push your key-values from your configuration file to
your App Configuration store. Explanations of the parameters are available in the Parameters section below,
and in tooltips next to each parameter.
7. Save and queue a release. The release log will display any failures encountered during the execution of the task.

Parameters
The following parameters are used by the App Configuration Push task:
Azure subscription : A drop-down containing your available Azure service connections. To update and refresh
your list of available Azure service connections, press the Refresh Azure subscription button to the right of
the textbox.
App Configuration Name : A drop-down that loads your available configuration stores under the selected
subscription. To update and refresh your list of available configuration stores, press the Refresh App
Configuration Name button to the right of the textbox.
Configuration File Path : The path to your configuration file. You can browse through your build artifact to
select a configuration file. ( ... button to the right of the textbox).
Separator : The separator that's used to flatten .json and .yml files.
Depth : The depth that the .json and .yml files will be flattened to.
Prefix : A string that's appended to the beginning of each key pushed to the App Configuration store.
Label : A string that's added to each key-value as the label within the App Configuration store.
Content Type : A string that's added to each key-value as the content type within the App Configuration store.
Tags : A JSON object in the format of {"tag1":"val1", "tag2":"val2"} , which defines tags that are added to each
key-value pushed to your App Configuration store.
Delete all other Key-Values in store with the specified prefix and label : Default value is Unchecked .
Checked : Removes all key-values in the App Configuration store that match both the specified prefix and
label before pushing new key-values from the configuration file.
Unchecked : Pushes all key-values from the configuration file into the App Configuration store and
leaves everything else in the App Configuration store intact.
After filling out required parameters, run the pipeline. All key-values in the specified configuration file will be
uploaded to App Configuration.

Troubleshooting
If an unexpected error occurs, debug logs can be enabled by setting the pipeline variable system.debug to true .

FAQ
How can I upload multiple configuration files?
Create multiple instances of the Azure App Configuration Push task within the same pipeline to push multiple
configuration files to the App Configuration store.
Why am I receiving a 409 error when attempting to push key-values to my configuration store?
A 409 Conflict error message will occur if the task tries to remove or overwrite a key-value that is locked in the App
Configuration store.
Sync your GitHub repository to App Configuration
9/22/2020 • 8 minutes to read • Edit Online

Teams that want to continue using their existing source control practices can use GitHub Actions to automatically
sync their GitHub repository with their App Configuration store. This allows you to make changes to your config
files as you normally would, while getting App Configuration benefits like:
• Centralized configuration outside of your code
• Updating configuration without redeploying your entire app
• Integration with services like Azure App Service and Functions.
A GitHub Actions workflow defines an automated process in a GitHub repository. The Azure App Configuration
Sync Action triggers updates to an App Configuration instance when changes are made to the source repository. It
uses a YAML (.yml) file found in the /.github/workflows/ path of your repository to define the steps and
parameters. You can trigger configuration updates when pushing, reviewing, or branching app configuration files
just as you do with app code.
The GitHub documentation provides in-depth view of GitHub workflows and actions.

Enable GitHub Actions in your repository


To start using this GitHub action, go to your repository and select the Actions tab. Select New workflow , then Set
up a workflow yourself . Finally, search the marketplace for “Azure App Configuration Sync.”

Sync configuration files after a push


This action syncs Azure App Configuration files when a change is pushed to appsettings.json . When a developer
pushes a change to appsettings.json , the App Configuration Sync action updates the App Configuration instance
with the new values.
The first section of this workflow specifies that the action triggers on a push containing appsettings.json to the
master branch. The second section lists the jobs run once the action is triggered. The action checks out the relevant
files and updates the App Configuration instance using the connection string stored as a secret in the repository.
For more information about using secrets in GitHub, see GitHub's article about creating and using encrypted
secrets.

on:
push:
branches:
- 'master'
paths:
- 'appsettings.json'

jobs:
syncconfig:
runs-on: ubuntu-latest
steps:
# checkout done so that files in the repo can be read by the sync
- uses: actions/checkout@v1
- uses: azure/appconfiguration-sync@v1
with:
configurationFile: 'appsettings.json'
format: 'json'
# Replace <ConnectionString> with the name of the secret in your
# repository
connectionString: ${{ secrets.<ConnectionString> }}
separator: ':'

Use strict sync


By default the GitHub action does not enable strict mode, meaning that the sync will only add key-values from the
configuration file to the App Configuration instance (no key-value pairs will be deleted). Enabling strict mode will
mean key-value pairs that aren't in the configuration file are deleted from the App Configuration instance, so that it
matches the configuration file. If you are syncing from multiple sources or using Azure Key Vault with App
Configuration, you'll want to use different prefixes or labels with strict sync to avoid wiping out configuration
settings from other files (see samples below).
on:
push:
branches:
- 'master'
paths:
- 'appsettings.json'

jobs:
syncconfig:
runs-on: ubuntu-latest
steps:
# checkout done so that files in the repo can be read by the sync
- uses: actions/checkout@v1
- uses: azure/appconfiguration-sync@v1
with:
configurationFile: 'appsettings.json'
format: 'json'
# Replace <ConnectionString> with the name of the secret in your
# repository
connectionString: ${{ secrets.<ConnectionString> }}
separator: ':'
label: 'Label'
prefix: 'Prefix:'
strict: true

Sync multiple files in one action


If your configuration is in multiple files, you can use the pattern below to trigger a sync when either file is modified.
This pattern uses the glob library https://www.npmjs.com/package/glob . Note that if your config file name
contains a comma, you can use a backslash to escape the comma.

on:
push:
branches:
- 'master'
paths:
- 'appsettings.json'
- 'appsettings2.json'

jobs:
syncconfig:
runs-on: ubuntu-latest
steps:
# checkout done so that files in the repo can be read by the sync
- uses: actions/checkout@v1
- uses: azure/appconfiguration-sync@v1
with:
configurationFile: '{appsettings.json,appsettings2.json}'
format: 'json'
# Replace <ConnectionString> with the name of the secret in your repository
connectionString: ${{ secrets.<ConnectionString> }}
separator: ':'

Sync by prefix or label


Specifying prefixes or labels in your sync action will sync only that particular set. This is important for using strict
sync with multiple files. Depending on how the configuration is set up, either a prefix or a label can be associated
with each file and then each prefix or label can be synced separately so that nothing is overwritten. Typically
prefixes are used for different applications or services and labels are used for different environments.
Sync by prefix:
on:
push:
branches:
- 'master'
paths:
- 'appsettings.json'

jobs:
syncconfig:
runs-on: ubuntu-latest
steps:
# checkout done so that files in the repo can be read by the sync
- uses: actions/checkout@v1
- uses: azure/appconfiguration-sync@v1
with:
configurationFile: 'appsettings.json'
format: 'json'
# Replace <ConnectionString> with the name of the secret in your repository
connectionString: ${{ secrets.<ConnectionString> }}
separator: ':'
prefix: 'Prefix::'

Sync by label:

on:
push:
branches:
- 'master'
paths:
- 'appsettings.json'

jobs:
syncconfig:
runs-on: ubuntu-latest
steps:
# checkout done so that files in the repo can be read by the sync
- uses: actions/checkout@v1
- uses: azure/appconfiguration-sync@v1
with:
configurationFile: 'appsettings.json'
format: 'json'
# Replace <ConnectionString> with the name of the secret in your repository
connectionString: ${{ secrets.<ConnectionString> }}
separator: ':'
label: 'Label'

Use a dynamic label on sync


The following action inserts a dynamic label on each sync, ensuring that each sync can be uniquely identified and
allowing code changes to be mapped to config changes.
The first section of this workflow specifies that the action triggers on a push containing appsettings.json to the
master branch. The second section runs a job that creates a unique label for the config update based on the commit
hash. The job then updates the App Configuration instance with the new values and the unique label for this
update.
on:
push:
branches:
- 'master'
paths:
- 'appsettings.json'

jobs:
syncconfig:
runs-on: ubuntu-latest
steps:
# Creates a label based on the branch name and the first 8 characters
# of the commit hash
- id: determine_label
run: echo ::set-output name=LABEL::"${GITHUB_REF#refs/*/}/${GITHUB_SHA:0:8}"
# checkout done so that files in the repo can be read by the sync
- uses: actions/checkout@v1
- uses: azure/appconfiguration-sync@v1
with:
configurationFile: 'appsettings.json'
format: 'json'
# Replace <ConnectionString> with the name of the secret in your
# repository
connectionString: ${{ secrets.<ConnectionString> }}
separator: ':'
label: ${{ steps.determine_label.outputs.LABEL }}

Use Azure Key Vault with GitHub Action


Developers using Azure Key Vault with AppConfiguration should use two separate files, typically an
appsettings.json and a secretreferences.json. The secretreferences.json will contain the url to the key vault secret.
{ "mySecret": "{"uri":"https://myKeyVault.vault.azure.net/secrets/mySecret"}" }
The GitHub Action can then be configured to do a strict sync on the appsettings.json, followed by a non-strict sync
on secretreferences.json. The following sample will trigger a sync when either file is updated:
on:
push:
branches:
- 'master'
paths:
- 'appsettings.json'
- 'secretreferences.json'

jobs:
syncconfig:
runs-on: ubuntu-latest
steps:
# checkout done so that files in the repo can be read by the sync
- uses: actions/checkout@v1
- uses: azure/appconfiguration-sync@v1
with:
configurationFile: 'appsettings.json'
format: 'json'
# Replace <ConnectionString> with the name of the secret in your repository
connectionString: ${{ secrets.<ConnectionString> }}
separator: ':'
strict: true
- uses: azure/appconfiguration-sync@v1
with:
configurationFile: 'secretreferences.json'
format: 'json'
# Replace <ConnectionString> with the name of the secret in your repository
connectionString: ${{ secrets.<ConnectionString> }}
separator: ':'
contentType: 'application/vnd.microsoft.appconfig.keyvaultref+json;charset=utf-8'

Use max depth to limit GitHub Action


The default behavior for nested JSON attributes is to flatten the entire object. The JSON below defines this key-
value pair:

K EY VA L UE

Object:Inner:InnerKey InnerValue

{ "Object":
{ "Inner":
{
"InnerKey": "InnerValue"
}
}
}

If the nested object is intended to be the value pushed to the Configuration instance, you can use the depth value to
stop the flattening at the appropriate depth.
on:
push:
branches:
- 'master'
paths:
- 'appsettings.json'

jobs:
syncconfig:
runs-on: ubuntu-latest
steps:
# checkout done so that files in the repo can be read by the sync
- uses: actions/checkout@v1
- uses: azure/appconfiguration-sync@v1
with:
configurationFile: 'appsettings.json'
format: 'json'
# Replace <ConnectionString> with the name of the secret in your
# repository
connectionString: ${{ secrets.<ConnectionString> }}
separator: ':'
depth: 2

Given a depth of 2, the example above now returns the following key-value pair:

K EY VA L UE

Object:Inner {"InnerKey":"InnerValue"}

Understand action inputs


Input parameters specify data used by the action during runtime. The following table contains input parameters
accepted by App Configuration Sync and the expected values for each. For more information about action inputs
for GitHub Actions, see GitHub's documentation.

NOTE
Input IDs are case insensitive.

IN P UT N A M E REQ UIRED? VA L UE

configurationFile Yes Relative path to the configuration file in


the repository. Glob patterns are
supported and can include multiple files.

format Yes File format of the configuration file.


Valid formats are: JSON, YAML,
properties.

connectionString Yes Connection string for the App


Configuration instance. The connection
string should be stored as a secret in
the GitHub repository, and only the
secret name should be used in the
workflow.
IN P UT N A M E REQ UIRED? VA L UE

separator Yes Separator used when flattening the


configuration file to key-value pairs.
Valid values are: . , ; : - _ __ /

prefix No Prefix to be added to the start of keys.

label No Label used when setting key-value


pairs. If unspecified, a null label is used.

strict No A boolean value that determines


whether strict mode is enabled. The
default value is false.

depth No Max depth for flattening the


configuration file. Depth must be a
positive number. The default will have
no max depth.

tags No Specifies the tag set on key-value pairs.


The expected format is a stringified form
of a JSON object of the following shape:
{ [propertyName: string]: string; } Each
property name-value becomes a tag.

Next steps
In this article, you learned about the App Configuration Sync GitHub Action and how it can be used to automate
updates to your App Configuration instance. To learn how Azure App Configuration reacts to changes in key-value
pairs, continue to the next article.
Integrate with a CI/CD pipeline
9/22/2020 • 2 minutes to read • Edit Online

This article explains how to use data from Azure App Configuration in a continuous integration and continuous
deployment system.

Use App Configuration in your Azure DevOps Pipeline


If you have an Azure DevOps Pipeline, you can fetch key-values from App Configuration and set them as task
variables. The Azure App Configuration DevOps extension is an add-on module that provides this functionality.
Follow its instructions to use the extension in a build or release task sequence.

Deploy App Configuration data with your application


Your application may fail to run if it depends on Azure App Configuration and cannot reach it. Enhance the
resiliency of your application by packaging configuration data into a file that's deployed with the application and
loaded locally during application startup. This approach guarantees that your application has default setting values
on startup. These values are overwritten by any newer changes in an App Configuration store when it's available.
Using the Export function of Azure App Configuration, you can automate the process of retrieving current
configuration data as a single file. You can then embed this file in a build or deployment step in your continuous
integration and continuous deployment (CI/CD) pipeline.
The following example shows how to include App Configuration data as a build step for the web app introduced in
the quickstarts. Before you continue, finish Create an ASP.NET Core app with App Configuration first.
You can use any code editor to do the steps in this tutorial. Visual Studio Code is an excellent option available on
the Windows, macOS, and Linux platforms.
Prerequisites
If you build locally, download and install the Azure CLI if you haven’t already.
To do a cloud build, with Azure DevOps for example, make sure the Azure CLI is installed in your build system.
Export an App Configuration store
1. Open your .csproj file, and add the following script:

<Target Name="Export file" AfterTargets="Build">


<Message Text="Export the configurations to a temp file. " />
<Exec WorkingDirectory="$(MSBuildProjectDirectory)" Condition="$(ConnectionString) != ''"
Command="az appconfig kv export -d file --path $(OutDir)\azureappconfig.json --format json --separator :
--connection-string $(ConnectionString)" />
</Target>

2. Open Program.cs, and update the CreateWebHostBuilder method to use the exported JSON file by calling the
config.AddJsonFile() method. Add the System.Reflection namespace as well.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
var directory = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var settings = config.Build();

config.AddJsonFile(Path.Combine(directory, "azureappconfig.json"));
config.AddAzureAppConfiguration(settings["ConnectionStrings:AppConfig"]);
})
.UseStartup<Startup>();

Build and run the app locally


1. Set an environment variable named ConnectionString , and set it to the access key to your App
Configuration store. If you use the Windows command prompt, run the following command and restart the
command prompt to allow the change to take effect:

setx ConnectionString "connection-string-of-your-app-configuration-store"

If you use Windows PowerShell, run the following command:

$Env:ConnectionString = "connection-string-of-your-app-configuration-store"

If you use macOS or Linux, run the following command:

export ConnectionString='connection-string-of-your-app-configuration-store'

2. To build the app by using the .NET Core CLI, run the following command in the command shell:

dotnet build

3. After the build successfully completes, run the following command to run the web app locally:

dotnet run

4. Open a browser window and go to http://localhost:5000 , which is the default URL for the web app hosted
locally.
Next steps
In this tutorial, you exported Azure App Configuration data to be used in a deployment pipeline. To learn more
about how to use App Configuration, continue to the Azure CLI samples.
Azure CLI
Integrate with Kubernetes Deployment using Helm
5/21/2020 • 7 minutes to read • Edit Online

Helm provides a way to define, install, and upgrade applications running in Kubernetes. A Helm chart contains the
information necessary to create an instance of a Kubernetes application. Configuration is stored outside of the
chart itself, in a file called values.yaml.
During the release process, Helm merges the chart with the proper configuration to run the application. For
example, variables defined in values.yaml can be referenced as environment variables inside the running
containers. Helm also supports creation of Kubernetes Secrets, which can be mounted as data volumes or exposed
as environment variables.
You can override the values stored in values.yaml by providing additional YAML-based configuration files on the
command line when running Helm. Azure App Configuration supports exporting configuration values to YAML
files. Integrating this export capability into your deployment allows your Kubernetes applications to leverage
configuration values stored in App Configuration.
In this tutorial, you learn how to:
Use values from App Configuration when deploying an application to Kubernetes using Helm.
Create a Kubernetes Secret based on a Key Vault reference in App Configuration.
This tutorial assumes basic understanding of managing Kubernetes with Helm. Learn more about installing
applications with Helm in Azure Kubernetes Service.

Prerequisites
If you don't have an Azure subscription, create a free account before you begin.
Install Azure CLI (version 2.4.0 or later)
Install Helm (version 2.14.0 or later)
A Kubernetes cluster.

Create an App Configuration store


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and select
Enter.
2. Select App Configuration from the search results, and then select Create .

3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N


SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the same
time by deleting the resource group.
For more information, see Use
resource groups to manage your
Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted. For
the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.

4. Select Create . The deployment might take a few minutes.


5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.
6. Select Configuration Explorer > Create to add the following key-value pairs:

K EY VA L UE

settings.color White

settings.message Data from Azure App Configuration

Leave Label and Content Type empty for now.

Add a Key Vault reference to App Configuration


1. Sign in to the Azure portal and add a secret to Key Vault with name Password and value myPassword .
2. Select the App Configuration store instance that you created in previous section.
3. Select Configuration Explorer .
4. Select + Create > Key vault reference , and then specify the following values:
Key : Select secrets.password .
Label : Leave this value blank.
Subscription , Resource group , and Key vault : Enter the values corresponding to those in the key
vault you created in previous step.
Secret : Select the secret named Password that you created in the previous section.

Create Helm chart


First, create a sample Helm chart with the following command

helm create mychart

Helm creates a new directory called mychart with the structure shown below.

TIP
Follow this charts guide to learn more.

mychart
|-- Chart.yaml
|-- charts
|-- templates
| |-- NOTES.txt
| |-- _helpers.tpl
| |-- deployment.yaml
| |-- ingress.yaml
| `-- service.yaml
`-- values.yaml

Next, update the spec:template:spec:containers section of the deployment.yaml file. The following snippet adds
two environment variables to the container. You'll set their values dynamically at deployment time.
env:
- name: Color
value: {{ .Values.settings.color }}
- name: Message
value: {{ .Values.settings.message }}

The complete deployment.yaml file after the update should look like below.

apiVersion: apps/v1beta2
kind: Deployment
metadata:
name: {{ include "mychart.fullname" . }}
labels:
app.kubernetes.io/name: {{ include "mychart.name" . }}
helm.sh/chart: {{ include "mychart.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
app.kubernetes.io/name: {{ include "mychart.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
template:
metadata:
labels:
app.kubernetes.io/name: {{ include "mychart.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
spec:
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
env:
- name: Color
value: {{ .Values.settings.color }}
- name: Message
value: {{ .Values.settings.message }}
ports:
- name: http
containerPort: 80
protocol: TCP
livenessProbe:
httpGet:
path: /
port: http
readinessProbe:
httpGet:
path: /
port: http
resources:
{{ toYaml .Values.resources | indent 12 }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{ toYaml . | indent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{ toYaml . | indent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{ toYaml . | indent 8 }}
{{- end }}
To store sensitive data as Kubernetes Secrets, add a secrets.yaml file under the templates folder.

TIP
Learn more about how to use Kubernetes Secrets.

apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
password: {{ .Values.secrets.password | b64enc }}

Finally, update the values.yaml file with the following content to optionally provide default values of the
configuration settings and secrets that referenced in the deployment.yaml and secrets.yaml files. Their actual values
will be overwritten by configuration pulled from App Configuration.

# settings will be overwritten by App Configuration


settings:
color: red
message: myMessage

Pass configuration from App Configuration in Helm install


First, download the configuration from App Configuration to a myConfig.yaml file. Use a key filter to only download
those keys that start with settings.. If in your case the key filter is not sufficient to exclude keys of Key Vault
references, you may use the argument --skip-keyvault to exclude them.

TIP
Learn more about the export command.

az appconfig kv export -n myAppConfiguration -d file --path myConfig.yaml --key "settings.*" --separator "." -
-format yaml

Next, download secrets to a file called mySecrets.yaml. The command-line argument --resolve-keyvault resolves
the Key Vault references by retrieving the actual values in Key Vault. You'll need to run this command with
credentials that have access permissions to the corresponding Key Vault.

WARNING
As this file contains sensitive information, keep the file with care and clean up when it's not needed anymore.

az appconfig kv export -n myAppConfiguration -d file --path mySecrets.yaml --key "secrets.*" --separator "." --
resolve-keyvault --format yaml

Use helm upgrade's -f argument to pass in the two configuration files you've created. They'll override the
configuration values defined in values.yaml with the values exported from App Configuration.
helm upgrade --install -f myConfig.yaml -f mySecrets.yaml "example" ./mychart

You can also use the --set argument for helm upgrade to pass literal key values. Using the --set argument is a
good way to avoid persisting sensitive data to disk.

$secrets = az appconfig kv list -n myAppConfiguration --key "secrets.*" --resolve-keyvault --query "[*].


{name:key, value:value}" | ConvertFrom-Json

foreach ($secret in $secrets) {


$keyvalues += $secret.name + "=" + $secret.value + ","
}

if ($keyvalues){
$keyvalues = $keyvalues.TrimEnd(',')
helm upgrade --install --set $keyvalues "example" ./mychart
}
else{
helm upgrade --install "example" ./mychart
}

Verify that configurations and secrets were set successfully by accessing the Kubernetes Dashboard. You'll see that
the color and message values from App Configuration were populated into the container's environment variables.

One secret, password , stores as Key Vault reference in App Configuration was also added into Kubernetes Secrets.
Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this tutorial, you exported Azure App Configuration data to be used in a Kubernetes deployment with Helm. To
learn more about how to use App Configuration, continue to the Azure CLI samples.
Azure CLI
Azure CLI samples
9/22/2020 • 2 minutes to read • Edit Online

The following table includes links to bash scripts for Azure App Configuration by using the Azure CLI.

SC RIP T DESC RIP T IO N

Create

Create an App Configuration store Creates a resource group and an App Configuration store
instance.

Use

Work with key values Creates, views, updates, and deletes key values.

Import key values Imports key values from other sources.

Export key values Exports key values to other targets.

Delete

Delete an App Configuration store Deletes an App Configuration store instance.


Keys and values
9/22/2020 • 4 minutes to read • Edit Online

Azure App Configuration stores configuration data as key-values. Key-values are a simple and flexible
representation of application settings used by developers.

Keys
Keys serve as identifiers for key-values and are used to store and retrieve corresponding values. It's a common
practice to organize keys into a hierarchical namespace by using a character delimiter, such as / or : . Use a
convention best suited to your application. App Configuration treats keys as a whole. It doesn't parse keys to figure
out how their names are structured or enforce any rule on them.
Here is an example of key names structured into a hierarchy based on component services:

AppName:Service1:ApiEndpoint
AppName:Service2:ApiEndpoint

The use of configuration data within application frameworks might dictate specific naming schemes for key-values.
For example, Java's Spring Cloud framework defines Environment resources that supply settings to a Spring
application. These are parameterized by variables that include application name and profile. Keys for Spring Cloud-
related configuration data typically start with these two elements separated by a delimiter.
Keys stored in App Configuration are case-sensitive, unicode-based strings. The keys app1 and App1 are distinct in
an App Configuration store. Keep this in mind when you use configuration settings within an application because
some frameworks handle configuration keys case-insensitively. We do not recommend using case to differentiate
keys.
You can use any unicode character in key names except for % . A key name cannot be . or .. either. There's a
combined size limit of 10 KB on a key-value. This limit includes all characters in the key, its value, and all associated
optional attributes. Within this limit, you can have many hierarchical levels for keys.
Design key namespaces
There are two general approaches to naming keys used for configuration data: flat or hierarchical. These methods
are similar from an application usage standpoint, but hierarchical naming offers a number of advantages:
Easier to read. Delimiters in a hierarchical key name function as spaces in a sentence. They also provide natural
breaks between words.
Easier to manage. A key name hierarchy represents logical groups of configuration data.
Easier to use. It's simpler to write a query that pattern-matches keys in a hierarchical structure and retrieves
only a portion of configuration data. Also, many newer programming frameworks have native support for
hierarchical configuration data such that your application can make use of specific sets of configuration.
You can organize keys in App Configuration hierarchically in many ways. Think of such keys as URIs. Each
hierarchical key is a resource path composed of one or more components that are joined together by delimiters.
Choose what character to use as a delimiter based on what your application, programming language, or
framework needs. Use multiple delimiters for different keys in App Configuration.
Label keys
Key-values in App Configuration can optionally have a label attribute. Labels are used to differentiate key-values
with the same key. A key app1 with labels A and B forms two separate keys in an App Configuration store. By
default, a key-value has no label. To explicitly reference a key-value without a label, use \0 (URL encoded as %00 ).
Label provides a convenient way to create variants of a key. A common use of labels is to specify multiple
environments for the same key:

Key = AppName:DbEndpoint & Label = Test


Key = AppName:DbEndpoint & Label = Staging
Key = AppName:DbEndpoint & Label = Production

Version key-values
Use labels as a way to create multiple versions of a key-value. For example, you can input an application version
number or a Git commit ID in labels to identify key-values associated with a particular software build.

NOTE
If you are looking for change versions, App Configuration keeps all changes of a key-value occurred in the past certain period
of time automatically. See point-in-time snapshot for more details.

Query key-values
Each key-value is uniquely identified by its key plus a label that can be \0 . You query an App Configuration store
for key-values by specifying a pattern. The App Configuration store returns all key-values that match the pattern
including their corresponding values and attributes. Use the following key patterns in REST API calls to App
Configuration:

K EY DESC RIP T IO N

key is omitted or key=* Matches all keys

key=abc Matches key name abc exactly

key=abc* Matches key names that start with abc

key=abc,xyz Matches key names abc or xyz . Limited to five CSVs

You also can include the following label patterns:

L A B EL DESC RIP T IO N

label is omitted or label=* Matches any label, which includes \0

label=%00 Matches \0 label

label=1.0.0 Matches label 1.0.0 exactly

label=1.0.* Matches labels that start with 1.0.

label=%00,1.0.0 Matches labels \0 or 1.0.0 , limited to five CSVs


NOTE
* , , , and \ are reserved characters in queries. If a reserved character is used in your key names or labels, you must
escape it by using \{Reserved Character} in queries.

Values
Values assigned to keys are also unicode strings. You can use all unicode characters for values.
Use Content-Type
Each key-value in App Configuration has a content-type attribute. You can optionally use this attribute to store
information about the type of value in a key-value that helps your application to process it properly. You can use
any format for the content-type. App Configuration uses Media Types (also known as MIME types) for built-in data
types such as feature flags, Key Vault references, and JSON key-values.

Next steps
Point-in-time snapshot
Feature management
Event handling
Point-in-time snapshot
9/22/2020 • 2 minutes to read • Edit Online

Azure App Configuration maintains a record of changes made to key-values. This record provides a timeline of
key-value changes. You can reconstruct the history of any key-value and provide its past value at any moment
within the key history period (7 days for Free tier stores, or 30 days for Standard tier stores). Using this feature,
you can “time-travel” backward and retrieve an old key-value. For example, you can recover configuration settings
used before the most recent deployment in order to roll back the application to the previous configuration.

Key-value retrieval
You can use Azure portal or CLI to retrieve past key-values. In Azure CLI, use az appconfig revision list , adding
appropriate parameters to retrieve the required values. Specify the Azure App Configuration instance by providing
either the store name ( --name <app-config-store-name> ) or by using a connection string (
--connection-string <your-connection-string> ). Restrict the output by specifying a specific point in time (
--datetime ) and by specifying the maximum number of items to return ( --top ).

If you don't have Azure CLI installed locally, you can optionally use Azure Cloud Shell.
Retrieve all recorded changes to your key-values.

az appconfig revision list --name <your-app-config-store-name>.

Retrieve all recorded changes for the key environment and the labels test and prod .

az appconfig revision list --name <your-app-config-store-name> --key environment --label test,prod

Retrieve all recorded changes in the hierarchical key space environment:prod .

az appconfig revision list --name <your-app-config-store-name> --key environment:prod:*

Retrieve all recorded changes for the key color at a specific point-in-time.

az appconfig revision list --connection-string <your-app-config-connection-string> --key color --datetime


"2019-05-01T11:24:12Z"

Retrieve the last 10 recorded changes to your key-values and return only the values for key , label , and
last_modified time stamp.

az appconfig revision list --name <your-app-config-store-name> --top 10 --fields key label last_modified

Next steps
Create an ASP.NET Core web app
Feature management overview
9/22/2020 • 3 minutes to read • Edit Online

Traditionally, shipping a new application feature requires a complete redeployment of the application itself. Testing
a feature often requires multiple deployments of the application. Each deployment may change the feature or
expose the feature to different customers for testing.
Feature management is a modern software-development practice that decouples feature release from code
deployment and enables quick changes to feature availability on demand. It uses a technique called feature flags
(also known as feature toggles, feature switches, and so on) to dynamically administer a feature's lifecycle.
Feature management helps developers address the following problems:
Code branch management : Use feature flags to wrap new application functionality currently under
development. Such functionality is "hidden" by default. You can safely ship the feature, even though it's
unfinished, and it will stay dormant in production. Using this approach, called dark deployment, you can
release all your code at the end of each development cycle. You no longer need to maintain code branches
across multiple development cycles because a given feature requires more than one cycle to complete.
Test in production : Use feature flags to grant early access to new functionality in production. For example,
you can limit access to team members or to internal beta testers. These users will experience the full-fidelity
production experience instead of a simulated or partial experience in a test environment.
Flighting : Use feature flags to incrementally roll out new functionality to end users. You can target a small
percentage of your user population first and increase that percentage gradually over time.
Instant kill switch : Feature flags provide an inherent safety net for releasing new functionality. You can turn
application features on and off without redeploying any code. If necessary, you can quickly disable a feature
without rebuilding and redeploying your application.
Selective activation : Use feature flags to segment your users and deliver a specific set of features to each
group. You may have a feature that works only on a certain web browser. You can define a feature flag so that
only users of that browser can see and use the feature. With this approach, you can easily expand the
supported browser list later without having to make any code changes.

Basic concepts
Here are several new terms related to feature management:
Feature flag : A feature flag is a variable with a binary state of on or off. The feature flag also has an associated
code block. The feature flag's state triggers whether the code block runs.
Feature manager : A feature manager is an application package that handles the life cycle of all the feature
flags in an application. The feature manager also provides additional functionality, including caching feature
flags and updating their states.
Filter : A filter is a rule for evaluating the state of a feature flag. Potential filters include user groups, device or
browser types, geographic locations, and time windows.
An effective implementation of feature management consists of at least two components working in concert:
An application that makes use of feature flags.
A separate repository that stores the feature flags and their current states.

Using feature flags in your code


The basic pattern for implementing feature flags in an application is simple. A feature flag is a Boolean state
variable controlling a conditional statement in your code:

if (featureFlag) {
// Run the following code
}

You can set the value of featureFlag statically.

bool featureFlag = true;

You can evaluate the flag's state based on certain rules:

bool featureFlag = isBetaUser();

You can extend the conditional to set application behavior for either state:

if (featureFlag) {
// This following code will run if the featureFlag value is true
} else {
// This following code will run if the featureFlag value is false
}

Feature flag repository


To use feature flags effectively, you need to externalize all the feature flags used in an application. This allows you
to change feature flag states without modifying and redeploying the application itself.
Azure App Configuration provides a centralized repository for feature flags. You can use it to define different kinds
of feature flags and manipulate their states quickly and confidently. You can then use the App Configuration
libraries for various programming language frameworks to easily access these feature flags from your application.
Use feature flags in an ASP.NET Core app shows how the .NET Core App Configuration provider and Feature
Management libraries are used together to implement feature flags for your ASP.NET web application.

Next steps
Add feature flags to an ASP.NET Core web app
Reacting to Azure App Configuration events
9/22/2020 • 2 minutes to read • Edit Online

Azure App Configuration events enable applications to react to changes in key-values. This is done without the
need for complicated code or expensive and inefficient polling services. Instead, events are pushed through Azure
Event Grid to subscribers such as Azure Functions, Azure Logic Apps, or even to your own custom http listener.
Critically, you only pay for what you use.
Azure App Configuration events are sent to the Azure Event Grid which provides reliable delivery services to your
applications through rich retry policies and dead-letter delivery. To learn more, see Event Grid message delivery
and retry.
Common App Configuration event scenarios include refreshing application configuration, triggering deployments,
or any configuration-oriented workflow. When changes are infrequent, but your scenario requires immediate
responsiveness, event-based architecture can be especially efficient.
Take a look at Route Azure App Configuration events to a custom web endpoint - CLI for a quick example.

Available Azure App Configuration events


Event grid uses event subscriptions to route event messages to subscribers. Azure App Configuration event
subscriptions can include two types of events:

EVEN T N A M E DESC RIP T IO N

Microsoft.AppConfiguration.KeyValueModified Fired when a key-value is created or replaced

Microsoft.AppConfiguration.KeyValueDeleted Fired when a key-value is deleted

Event schema
Azure App Configuration events contain all the information you need to respond to changes in your data. You can
identify an App Configuration event because the eventType property starts with "Microsoft.AppConfiguration".
Additional information about the usage of Event Grid event properties is documented in Event Grid event schema.

P RO P ERT Y TYPE DESC RIP T IO N

topic string Full Azure Resource Manager id of the


App Configuration that emits the
event.

subject string The URI of the key-value that is the


subject of the event.

eventTime string The date/time that the event was


generated, in ISO 8601 format.

eventType string "Microsoft.AppConfiguration.KeyValue


Modified" or
"Microsoft.AppConfiguration.KeyValue
Deleted".

Id string A unique identifier of this event.

dataVersion string The schema version of the data object.

metadataVersion string The schema version of top-level


properties.

data object Collection of Azure App Configuration


specific event data

data.key string The key of the key-value that was


modified or deleted.

data.label string The label, if any, of the key-value that


was modified or deleted.

data.etag string For KeyValueModified the etag of


the new key-value. For
KeyValueDeleted the etag of the
key-value that was deleted.

Here is an example of a KeyValueModified event:


[{
"id": "84e17ea4-66db-4b54-8050-df8f7763f87b",
"topic": "/subscriptions/00000000-0000-0000-0000-
000000000000/resourceGroups/testrg/providers/microsoft.appconfiguration/configurationstores/contoso",
"subject": "https://contoso.azconfig.io/kv/Foo?label=FizzBuzz",
"data": {
"key": "Foo",
"label": "FizzBuzz",
"etag": "FnUExLaj2moIi4tJX9AXn9sakm0"
},
"eventType": "Microsoft.AppConfiguration.KeyValueModified",
"eventTime": "2019-05-31T20:05:03Z",
"dataVersion": "1",
"metadataVersion": "1"
}]

For more information, see Azure App Configuration events schema.

Practices for consuming events


Applications that handle App Configuration events should follow these recommended practices:
Multiple subscriptions can be configured to route events to the same event handler, so do not assume events
are from a particular source. Instead, check the topic of the message to ensure the App Configuration instance
sending the event.
Check the eventType and do not assume that all events you receive will be the types you expect.
Use the etag fields to understand if your information about objects is still up-to-date.
Use the sequencer fields to understand the order of events on any particular object.
Use the subject field to access the key-value that was modified.

Next steps
Learn more about Event Grid and give Azure App Configuration events a try:
About Event Grid
Route Azure App Configuration events to a custom web endpoint
Use customer-managed keys to encrypt your App
Configuration data
9/22/2020 • 5 minutes to read • Edit Online

Azure App Configuration encrypts sensitive information at rest. The use of customer-managed keys provides
enhanced data protection by allowing you to manage your encryption keys. When managed key encryption is used,
all sensitive information in App Configuration is encrypted with a user-provided Azure Key Vault key. This provides
the ability to rotate the encryption key on demand. It also provides the ability to revoke Azure App Configuration's
access to sensitive information by revoking the App Configuration instance's access to the key.

Overview
Azure App Configuration encrypts sensitive information at rest using a 256-bit AES encryption key provided by
Microsoft. Every App Configuration instance has its own encryption key managed by the service and used to
encrypt sensitive information. Sensitive information includes the values found in key-value pairs. When customer-
managed key capability is enabled, App Configuration uses a managed identity assigned to the App Configuration
instance to authenticate with Azure Active Directory. The managed identity then calls Azure Key Vault and wraps the
App Configuration instance's encryption key. The wrapped encryption key is then stored and the unwrapped
encryption key is cached within App Configuration for one hour. App Configuration refreshes the unwrapped
version of the App Configuration instance's encryption key hourly. This ensures availability under normal operating
conditions.

IMPORTANT
If the identity assigned to the App Configuration instance is no longer authorized to unwrap the instance's encryption key, or
if the managed key is permanently deleted, then it will no longer be possible to decrypt sensitive information stored in the
App Configuration instance. Using Azure Key Vault's soft delete function mitigates the chance of accidentally deleting your
encryption key.

When users enable the customer managed key capability on their Azure App Configuration instance, they control
the service’s ability to access their sensitive information. The managed key serves as a root encryption key. A user
can revoke their App Configuration instance’s access to their managed key by changing their key vault access
policy. When this access is revoked, App Configuration will lose the ability to decrypt user data within one hour. At
this point, the App Configuration instance will forbid all access attempts. This situation is recoverable by granting
the service access to the managed key once again. Within one hour, App Configuration will be able to decrypt user
data and operate under normal conditions.

NOTE
All Azure App Configuration data is stored for up to 24 hours in an isolated backup. This includes the unwrapped encryption
key. This data is not immediately available to the service or service team. In the event of an emergency restore, Azure App
Configuration will re-revoke itself from the managed key data.

Requirements
The following components are required to successfully enable the customer-managed key capability for Azure App
Configuration:
Standard tier Azure App Configuration instance
Azure Key Vault with soft-delete and purge-protection features enabled
An RSA or RSA-HSM key within the Key Vault
The key must not be expired, it must be enabled, and it must have both wrap and unwrap capabilities
enabled
Once these resources are configured, two steps remain to allow Azure App Configuration to use the Key Vault key:
1. Assign a managed identity to the Azure App Configuration instance
2. Grant the identity GET , WRAP , and UNWRAP permissions in the target Key Vault's access policy.

Enable customer-managed key encryption for your Azure App


Configuration instance
To begin, you will need a properly configured Azure App Configuration instance. If you do not yet have an App
Configuration instance available, follow one of these quickstarts to set one up:
Create an ASP.NET Core app with Azure App Configuration
Create a .NET Core app with Azure App Configuration
Create a .NET Framework app with Azure App Configuration
Create a Java Spring app with Azure App Configuration

TIP
The Azure Cloud Shell is a free interactive shell that you can use to run the command line instructions in this article. It has
common Azure tools preinstalled, including the .NET Core SDK. If you are logged in to your Azure subscription, launch your
Azure Cloud Shell from shell.azure.com. You can learn more about Azure Cloud Shell by reading our documentation

Create and configure an Azure Key Vault


1. Create an Azure Key Vault using the Azure CLI. Note that both vault-name and resource-group-name are
user-provided and must be unique. We use contoso-vault and contoso-resource-group in these examples.

az keyvault create --name contoso-vault --resource-group contoso-resource-group

2. Enable soft-delete and purge-protection for the Key Vault. Substitute the names of the Key Vault (
contoso-vault ) and Resource Group ( contoso-resource-group ) created in step 1.

az keyvault update --name contoso-vault --resource-group contoso-resource-group --enable-purge-


protection --enable-soft-delete

3. Create a Key Vault key. Provide a unique key-name for this key, and substitute the names of the Key Vault (
contoso-vault ) created in step 1. Specify whether you prefer RSA or RSA-HSM encryption.

az keyvault key create --name key-name --kty {RSA or RSA-HSM} --vault-name contoso-vault

The output from this command shows the key ID ("kid") for the generated key. Make a note of the key ID to
use later in this exercise. The key ID has the form:
https://{my key vault}.vault.azure.net/keys/{key-name}/{Key version} . The key ID has three important
components:
a. Key Vault URI: `https://{my key vault}.vault.azure.net
b. Key Vault key name: {Key Name}
c. Key Vault key version: {Key version}
4. Create a system assigned managed identity using the Azure CLI, substituting the name of your App
Configuration instance and resource group used in the previous steps. The managed identity will be used to
access the managed key. We use contoso-app-config to illustrate the name of an App Configuration
instance:

az appconfig identity assign --name contoso-app-config --resource-group contoso-resource-group --


identities [system]

The output of this command includes the principal ID ("principalId") and tenant ID ("tenandId") of the system
assigned identity. These IDs will be used to grant the identity access to the managed key.

{
"principalId": {Principal Id},
"tenantId": {Tenant Id},
"type": "SystemAssigned",
"userAssignedIdentities": null
}

5. The managed identity of the Azure App Configuration instance needs access to the key to perform key
validation, encryption, and decryption. The specific set of actions to which it needs access includes: GET ,
WRAP , and UNWRAP for keys. Granting the access requires the principal ID of the App Configuration instance's
managed identity. This value was obtained in the previous step. It is shown below as contoso-principalId .
Grant permission to the managed key using the command line:

az keyvault set-policy -n contoso-vault --object-id contoso-principalId --key-permissions get wrapKey


unwrapKey

6. Once the Azure App Configuration instance can access the managed key, we can enable the customer-
managed key capability in the service using the Azure CLI. Recall the following properties recorded during
the key creation steps: key name key vault URI .

az appconfig update -g contoso-resource-group -n contoso-app-config --encryption-key-name key-name --


encryption-key-version key-version --encryption-key-vault key-vault-Uri

Your Azure App Configuration instance is now configured to use a customer-managed key stored in Azure Key
Vault.

Next Steps
In this article, you configured your Azure App Configuration instance to use a customer-managed key for
encryption. Learn how to integrate your service with Azure Managed Identities.
Using private endpoints for Azure App Configuration
9/22/2020 • 4 minutes to read • Edit Online

You can use private endpoints for Azure App Configuration to allow clients on a virtual network (VNet) to securely
access data over a private link. The private endpoint uses an IP address from the VNet address space for your App
Configuration store. Network traffic between the clients on the VNet and the App Configuration store traverses
over the VNet using a private link on the Microsoft backbone network, eliminating exposure to the public internet.
Using private endpoints for your App Configuration store enables you to:
Secure your application configuration details by configuring the firewall to block all connections to App
Configuration on the public endpoint.
Increase security for the virtual network (VNet) ensuring data doesn't escape from the VNet.
Securely connect to the App Configuration store from on-premises networks that connect to the VNet using
VPN or ExpressRoutes with private-peering.

Conceptual overview
A private endpoint is a special network interface for an Azure service in your Virtual Network (VNet). When you
create a private endpoint for your App Config store, it provides secure connectivity between clients on your VNet
and your configuration store. The private endpoint is assigned an IP address from the IP address range of your
VNet. The connection between the private endpoint and the configuration store uses a secure private link.
Applications in the VNet can connect to the configuration store over the private endpoint using the same
connection strings and authorization mechanisms that they would use other wise . Private endpoints can
be used with all protocols supported by the App Configuration store.
While App Configuration doesn't support service endpoints, private endpoints can be created in subnets that use
Service Endpoints. Clients in a subnet can connect securely to an App Configuration store using the private
endpoint while using service endpoints to access others.
When you create a private endpoint for a service in your VNet, a consent request is sent for approval to the service
account owner. If the user requesting the creation of the private endpoint is also an owner of the account, this
consent request is automatically approved.
Service account owners can manage consent requests and private endpoints through the Private Endpoints tab of
the config store in the Azure portal.
Private endpoints for App Configuration
When creating a private endpoint, you must specify the App Configuration store to which it connects. If you have
multiple App Configuration instances within an account, you need a separate private endpoint for each store.
Connecting to private endpoints
Azure relies upon DNS resolution to route connections from the VNet to the configuration store over a private link.
You can quickly find connections strings in the Azure portal by selecting your App Configuration store, then
selecting Settings > Access Keys .

IMPORTANT
Use the same connection string to connect to your App Configuration store using private endpoints as you would use for a
public endpoint. Don't connect to the store using its privatelink subdomain URL.
DNS changes for private endpoints
When you create a private endpoint, the DNS CNAME resource record for the configuration store is updated to an
alias in a subdomain with the prefix privatelink . Azure also creates a private DNS zone corresponding to the
privatelink subdomain, with the DNS A resource records for the private endpoints.

When you resolve the endpoint URL from within the VNet hosting the private endpoint, it resolves to the private
endpoint of the store. When resolved from outside the VNet, the endpoint URL resolves to the public endpoint.
When you create a private endpoint, the public endpoint is disabled.
If you are using a custom DNS server on your network, clients must be able to resolve the fully qualified domain
name (FQDN) for the service endpoint to the private endpoint IP address. Configure your DNS server to delegate
your private link subdomain to the private DNS zone for the VNet, or configure the A records for
AppConfigInstanceA.privatelink.azconfig.io with the private endpoint IP address.

TIP
When using a custom or on-premises DNS server, you should configure your DNS server to resolve the store name in the
privatelink subdomain to the private endpoint IP address. You can do this by delegating the privatelink subdomain to
the private DNS zone of the VNet, or configuring the DNS zone on your DNS server and adding the DNS A records.

Pricing
Enabling private endpoints requires a Standard tier App Configuration store. To learn about private link pricing
details, see Azure Private Link pricing.

Next steps
Learn more about creating a private endpoint for your App Configuration store, refer to the following articles:
Create a private endpoint using the Private Link Center in the Azure portal
Create a private endpoint using Azure CLI
Create a private endpoint using Azure PowerShell
Learn to configure your DNS server with private endpoints:
Name resolution for resources in Azure virtual networks
DNS configuration for Private Endpoints
Authorize access to Azure App Configuration using
Azure Active Directory
9/22/2020 • 2 minutes to read • Edit Online

Besides using Hash-based Message Authentication Code (HMAC), Azure App Configuration supports using Azure
Active Directory (Azure AD) to authorize requests to App Configuration instances. Azure AD allows you to use role-
based access control (RBAC) to grant permissions to a security principal. A security principal may be a user, a
managed identity or an application service principal. To learn more about roles and role assignments, see
Understanding different roles.

Overview
Requests made by a security principal to access an App Configuration resource must be authorized. With Azure AD,
access to a resource is a two-step process:
1. The security principal's identity is authenticated and an OAuth 2.0 token is returned. The resource name to
request a token is https://login.microsoftonline.com/{tenantID} where {tenantID} matches the Azure Active
Directory tenant ID to which the service principal belongs.
2. The token is passed as part of a request to the App Configuration service to authorize access to the specified
resource.
The authentication step requires that an application request contains an OAuth 2.0 access token at runtime. If an
application is running within an Azure entity, such as an Azure Functions app, an Azure Web App, or an Azure VM, it
can use a managed identity to access the resources. To learn how to authenticate requests made by a managed
identity to Azure App Configuration, see Authenticate access to Azure App Configuration resources with Azure
Active Directory and managed identities for Azure Resources.
The authorization step requires that one or more Azure roles be assigned to the security principal. Azure App
Configuration provides Azure roles that encompass sets of permissions for App Configuration resources. The roles
that are assigned to a security principal determine the permissions provided to the principal. For more information
about Azure roles, see Azure built-in roles for Azure App Configuration.

Assign Azure roles for access rights


Azure Active Directory (Azure AD) authorizes access rights to secured resources through Azure role-based access
control (Azure RBAC).
When an Azure role is assigned to an Azure AD security principal, Azure grants access to those resources for that
security principal. Access is scoped to the App Configuration resource. An Azure AD security principal may be a
user, or an application service principal, or a managed identity for Azure resources.

Azure built-in roles for Azure App Configuration


Azure provides the following Azure built-in roles for authorizing access to App Configuration data using Azure AD
and OAuth:
App Configuration Data Owner : Use this role to give read/write/delete access to App Configuration data.
This does not grant access to the App Configuration resource.
App Configuration Data Reader : Use this role to give read access to App Configuration data. This does not
grant access to the App Configuration resource.
Contributor : Use this role to manage the App Configuration resource. While the App Configuration data can be
accessed using access keys, this role does not grant direct access to the data using Azure AD.
Reader : Use this role to give read access to the App Configuration resource. This does not grant access to the
resource's access keys, nor to the data stored in App Configuration.

NOTE
Currently, the Azure portal and CLI only support HMAC authentication to access App Configuration data. Azure AD
authentication is not supported. Therefore, users of the Azure portal and CLI require the Contributor role to retrieve the
access keys of the App Configuration resource. Granting App Configuration Data Reader or App Configuration Data Owner
roles has no impact on access through the portal and CLI.

Next steps
Learn more about using managed identities to administer your App Configuration service.
How to use managed identities for Azure App
Configuration
5/8/2020 • 3 minutes to read • Edit Online

This topic shows you how to create a managed identity for Azure App Configuration. A managed identity from
Azure Active Directory (AAD) allows Azure App Configuration to easily access other AAD-protected resources, such
as Azure Key Vault. The identity is managed by the Azure platform. It does not require you to provision or rotate
any secrets. For more about managed identities in AAD, see Managed identities for Azure resources.
Your application can be granted two types of identities:
A system-assigned identity is tied to your configuration store. It's deleted if your configuration store is
deleted. A configuration store can only have one system-assigned identity.
A user-assigned identity is a standalone Azure resource that can be assigned to your configuration store. A
configuration store can have multiple user-assigned identities.

Adding a system-assigned identity


Creating an App Configuration store with a system-assigned identity requires an additional property to be set on
the store.
Using the Azure CLI
To set up a managed identity using the Azure CLI, use the az appconfig identity assign command against an existing
configuration store. You have three options for running the examples in this section:
Use Azure Cloud Shell from the Azure portal.
Use the embedded Azure Cloud Shell via the "Try It" button, located in the top-right corner of each code block
below.
Install the latest version of Azure CLI (2.1 or later) if you prefer to use a local CLI console.
The following steps will walk you through creating an App Configuration store and assigning it an identity using
the CLI:
1. If you're using the Azure CLI in a local console, first sign in to Azure using az login. Use an account that is
associated with your Azure subscription:

az login

2. Create an App Configuration store using the CLI. For more examples of how to use the CLI with Azure App
Configuration, see App Configuration CLI samples:

az group create --name myResourceGroup --location eastus


az appconfig create --name myTestAppConfigStore --location eastus --resource-group myResourceGroup --sku
Free

3. Run the az appconfig identity assign command to create the system-assigned identity for this configuration
store:
az appconfig identity assign --name myTestAppConfigStore --resource-group myResourceGroup

Adding a user-assigned identity


Creating an App Configuration store with a user-assigned identity requires that you create the identity and then
assign its resource identifier to your store.
Using the Azure CLI
To set up a managed identity using the Azure CLI, use the az appconfig identity assign command against an existing
configuration store. You have three options for running the examples in this section:
Use Azure Cloud Shell from the Azure portal.
Use the embedded Azure Cloud Shell via the "Try It" button, located in the top-right corner of each code block
below.
Install the latest version of Azure CLI (2.0.31 or later) if you prefer to use a local CLI console.
The following steps will walk you through creating a user-assigned identity and an App Configuration store, then
assigning the identity to the store using the CLI:
1. If you're using the Azure CLI in a local console, first sign in to Azure using az login. Use an account that is
associated with your Azure subscription:

az login

2. Create an App Configuration store using the CLI. For more examples of how to use the CLI with Azure App
Configuration, see App Configuration CLI samples:

az group create --name myResourceGroup --location eastus


az appconfig create --name myTestAppConfigStore --location eastus --resource-group myResourceGroup --sku
Free

3. Create a user-assigned identity called myUserAssignedIdentity using the CLI.

az identity create -resource-group myResourceGroup --name myUserAssignedIdentity

In the output of this command, note the value of the id property.


4. Run the az appconfig identity assign command to assign the new user-assigned identity to this configuration
store. Use the value of the id property that you noted in the previous step.

az appconfig identity assign --name myTestAppConfigStore --resource-group myResourceGroup --identities


/subscriptions/[subscription
id]/resourcegroups/myResourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myUserAssi
gnedIdentity

Removing an identity
A system-assigned identity can be removed by disabling the feature by using the az appconfig identity remove
command in the Azure CLI. User-assigned identities can be removed individually. Removing a system-assigned
identity in this way will also delete it from AAD. System-assigned identities are also automatically removed from
AAD when the app resource is deleted.
Next steps
Create an ASP.NET Core app with Azure App Configuration
Resiliency and disaster recovery
9/22/2020 • 3 minutes to read • Edit Online

Currently, Azure App Configuration is a regional service. Each configuration store is created in a particular Azure
region. A region-wide outage affects all stores in that region. App Configuration doesn't offer automatic failover to
another region. This article provides general guidance on how you can use multiple configuration stores across
Azure regions to increase the geo-resiliency of your application.

High-availability architecture
To realize cross-region redundancy, you need to create multiple App Configuration stores in different regions. With
this setup, your application has at least one additional configuration store to fall back on if the primary store
becomes inaccessible. The following diagram illustrates the topology between your application and its primary and
secondary configuration stores:

Your application loads its configuration from both the primary and secondary stores in parallel. Doing this
increases the chance of successfully getting the configuration data. You're responsible for keeping the data in both
stores in sync. The following sections explain how you can build geo-resiliency into your application.

Failover between configuration stores


Technically, your application isn't executing a failover. It's attempting to retrieve the same set of configuration data
from two App Configuration stores simultaneously. Arrange your code so that it loads from the secondary store
first and then the primary store. This approach ensures that the configuration data in the primary store takes
precedence whenever it's available. The following code snippet shows how you can implement this arrangement in
.NET Core:
.NET Core 2.x
.NET Core 3.x
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(settings["ConnectionString_SecondaryStore"], optional: true)
.AddAzureAppConfiguration(settings["ConnectionString_PrimaryStore"], optional: true);
})
.UseStartup<Startup>();

Notice the optional parameter passed into the AddAzureAppConfiguration function. When set to true , this
parameter prevents the application from failing to continue if the function can't load configuration data.

Synchronization between configuration stores


It's important that your geo-redundant configuration stores all have the same set of data. There are two ways to
achieve this:
Backup manually using the Export function
You can use the Expor t function in App Configuration to copy data from the primary store to the secondary on
demand. This function is available through both the Azure portal and the CLI.
From the Azure portal, you can push a change to another configuration store by following these steps.
1. Go to the Impor t/Expor t tab, and select Expor t > App Configuration > Target > Select a resource .
2. In the new blade that opens, specify the subscription, resource group, and resource name of your secondary
store, then select Apply .
3. The UI is updated so that you can choose what configuration data you want to export to your secondary
store. You can leave the default time value as is and set both From label and Label to the same value.
Select Apply . Repeat this for all the labels in your primary store.
4. Repeat the previous steps whenever your configuration changes.
The export process can also be achieved using the Azure CLI. The following command shows how to export all
configurations from the primary store to the secondary:

az appconfig kv export --destination appconfig --name {PrimaryStore} --dest-name {SecondaryStore} --label


* --preserve-labels -y

Backup automatically using Azure Functions


The backup process can be automated by using Azure Functions. It leverages the integration with Azure Event Grid
in App Configuration. Once set up, App Configuration will publish events to Event Grid for any changes made to
key-values in a configuration store. Thus, an Azure Functions app can listen to these events and backup data
accordingly. For details, see the tutorial on how to backup App Configuration stores automatically.

Next steps
In this article, you learned how to augment your application to achieve geo-resiliency during runtime for App
Configuration. You also can embed configuration data from App Configuration at build or deployment time. For
more information, see Integrate with a CI/CD pipeline.
Use feature filters to enable a feature for a subset of
users
9/22/2020 • 2 minutes to read • Edit Online

Feature flags allow you to activate or deactivate functionality in your application. A simple feature flag is either on
or off. The application always behaves the same way. For example, you could roll out a new feature behind a feature
flag. When the feature flag is enabled, all users see the new feature. Disabling the feature flag hides the new feature.
In contrast, a conditional feature flag allows the feature flag to be enabled or disabled dynamically. The application
may behave differently, depending on the feature flag criteria. Suppose you want to show your new feature to a
small subset of users at first. A conditional feature flag allows you to enable the feature flag for some users while
disabling it for others. Feature filters determine the state of the feature flag each time it's evaluated.
The Microsoft.FeatureManagement library includes two feature filters:
PercentageFilter enables the feature flag based on a percentage.
TimeWindowFilter enables the feature flag during a specified window of time.
You can also create your own feature filter that implements the Microsoft.FeatureManagement.IFeatureFilter
interface.

Registering a feature filter


You register a feature filter by calling the AddFeatureFilter method, specifying the name of the feature filter. For
example, the following code registers PercentageFilter :

public void ConfigureServices(IServiceCollection services)


{
services.AddControllersWithViews();
services.AddFeatureManagement().AddFeatureFilter<PercentageFilter>();
}

Configuring a feature filter in Azure App Configuration


Some feature filters have additional settings. For example, PercentageFilter activates a feature based on a
percentage. It has a setting defining the percentage to use.
You can configure these settings for feature flags defined in Azure App Configuration. For example, follow these
steps to use PercentageFilter to enable the feature flag for 50% of requests to a web app:
1. Follow the instructions in Quickstart: Add feature flags to an ASP.NET Core app to create a web app with a
feature flag.
2. In the Azure portal, go to your configuration store and click Feature Manager .
3. Click on the context menu for the Beta feature flag that you created in the quickstart. Click Edit .
4. In the Edit screen, select the On radio button if it isn't already selected. Then click the Add Filter button.
(The On radio button's label will change to read Conditional .)
5. In the Key field, enter Microsoft.Percentage.

6. Click the context menu next to the feature filter key. Click Edit Parameters .
7. Hover under the Name header so that text boxes appear in the grid. Enter a Name of Value and a Value of
50. The Value field indicates the percentage of requests for which to enable the feature filter.

8. Click Apply to return to the Edit feature flag screen. Then click Apply again to save the feature flag
settings.
9. The State of the feature flag now appears as Conditional. This state indicates that the feature flag will be
enabled or disabled on a per-request basis, based on the criteria enforced by the feature filter.
Feature filters in action
To see the effects of this feature flag, launch the application and hit the Refresh button in your browser multiple
times. You'll see that the Beta item appears on the toolbar about 50% of the time. It's hidden the rest of the time,
because the PercentageFilter deactivates the Beta feature for a subset of requests. The following video shows this
behavior in action.

Next steps
Feature management overview
Use labels to enable configurations for different
environments
9/22/2020 • 2 minutes to read • Edit Online

Many applications need to use different configurations for different environments. Suppose that an application has
a configuration value that defines the connection string to use for its back-end database. The application
developers use a different database from the one used in production. The database connection string that the
application uses must change as the application moves from development to production.
In Azure App Configuration, you can use labels to define different values for the same key. For example, you can
define a single key with different values for development and production. You can specify which label to load when
connecting to App Configuration.
To demonstrate this functionality, you'll modify the web app created in Quickstart: Create an ASP.NET Core app with
Azure App Configuration to use different configuration settings for development versus production. Complete the
quickstart before proceeding.

Specify a label when adding a configuration value


In the Azure portal, go to Configuration Explorer and find the TestApp:Settings:FontColor key that you created in
the quickstart. Select its context menu and then select Add Value .

On the Add Value screen, enter a Value of red and a Label of Development . Leave Content type empty. Select
Apply .

Load configuration values with a specified label


By default, Azure App Configuration only loads configuration values with no label. If you've defined labels for your
configuration values, you'll want to specify the labels to use when connecting to App Configuration.
In the previous section, you created a different configuration value for the development environment. You use the
HostingEnvironment.EnvironmentName variable to dynamically determine which environment the app currently runs
in. To learn more, see Use multiple environments in ASP.NET Core.
Load configuration values with the label corresponding to the current environment by passing the environment
name into the Select method:

public static IHostBuilder CreateHostBuilder(string[] args) =>


Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options =>
options
.Connect(Environment.GetEnvironmentVariable("AppConfigConnectionString"))
// Load configuration values with no label
.Select(KeyFilter.Any, LabelFilter.Null)
// Override with any configuration values specific to current hosting env
.Select(KeyFilter.Any, hostingContext.HostingEnvironment.EnvironmentName)
);
})
.UseStartup<Startup>());

IMPORTANT
The preceding code snippet loads the App Configuration connection string from an environment variable named
AppConfigConnectionString . Be sure that this environment variable is set properly.

The Select method is called twice. The first time, it loads configuration values with no label. Then, it loads
configuration values with the label corresponding to the current environment. These environment-specific values
override any corresponding values with no label. You don't need to define environment-specific values for every
key. If a key doesn't have a value with a label corresponding to the current environment, it uses the value with no
label.

Test in different environments


Open the launchSettings.json file under the Properties directory. Find the config entry under profiles . In the
environmentVariables section, set the ASPNETCORE_ENVIRONMENT variable to Production .
With the new values set, build and run your application.

dotnet build
dotnet run

Use a web browser to go to http://localhost:5000 . You'll notice that the font color is black.
Update launchSettings.json to set the ASPNETCORE_ENVIRONMENT variable to Development . Run dotnet run again.
You'll notice that the font color is now red. This is because the application now uses the value of
TestApp:Settings:FontColor that has the Development label. All other configuration values remain the same as
their production values.

Next steps
Configuration in ASP.NET Core
Import or export configuration data
9/22/2020 • 2 minutes to read • Edit Online

Azure App Configuration supports data import and export operations. Use these operations to work with
configuration data in bulk and exchange data between your App Configuration store and code project. For example,
you can set up one App Configuration store for testing and another for production. You can copy application
settings between them so that you don't have to enter data twice.
This article provides a guide for importing and exporting data with App Configuration. If you’d like to set up an
ongoing sync with your GitHub repo, take a look at our GitHub Action.

Import data
Import brings configuration data into an App Configuration store from an existing source. Use the import function
to migrate data into an App Configuration store or aggregate data from multiple sources. App Configuration
supports importing from a JSON, YAML, or properties file.
Import data by using either the Azure portal or the Azure CLI. From the Azure portal, follow these steps:
1. Browse to your App Configuration store, and select Impor t/Expor t from the Operations menu.
2. On the Impor t tab, select Source ser vice > Configuration File .
3. Select For language and select your desired input type.
4. Select the Folder icon, and browse to the file to import.

5. Select a Separator , and optionally enter a Prefix to use for imported key names.
6. Optionally, select a Label .
7. Select Apply to finish the import.
Export data
Export writes configuration data stored in App Configuration to another destination. Use the export function, for
example, to save data in an App Configuration store to a file that's embedded with your application code during
deployment.
Export data by using either the Azure portal or the Azure CLI. From the Azure portal, follow these steps:
1. Browse to your App Configuration store, and select Impor t/Expor t .
2. On the Expor t tab, select Target ser vice > Configuration File .
3. Optionally enter a Prefix and select a Label and a point-in-time for keys to be exported.
4. Select a File type > Separator .
5. Select Apply to finish the export.
Next steps
Create an ASP.NET Core web app
Leverage content-type to store JSON key-values in
App Configuration
9/22/2020 • 8 minutes to read • Edit Online

Data is stored in App Configuration as key-values, where values are treated as the string type by default. However,
you can specify a custom type by leveraging the content-type property associated with each key-value, so that you
can preserve the original type of your data or have your application behave differently based on content-type.

Overview
In App Configuration, you can use the JSON media type as the content-type of your key-values to avail benefits like:
Simpler data management : Managing key-values, like arrays, will become a lot easier in the Azure portal.
Enhanced data expor t : Primitive types, arrays, and JSON objects will be preserved during data export.
Native suppor t with App Configuration provider : Key-values with JSON content-type will work fine when
consumed by App Configuration provider libraries in your applications.
Valid JSON content-type
Media types, as defined here, can be assigned to the content-type associated with each key-value. A media type
consists of a type and a subtype. If the type is application and the subtype (or suffix) is json , the media type will
be considered a valid JSON content-type. Some examples of valid JSON content-types are:
application/json
application/activity+json
application/vnd.foobar+json;charset=utf-8
Valid JSON values
When a key-value has JSON content-type, its value must be in valid JSON format for clients to process it correctly.
Otherwise, clients may fail or fall back and treat it as string format. Some examples of valid JSON values are:
"John Doe"
723
false
null
"2020-01-01T12:34:56.789Z"
[1, 2, 3, 4]
{"ObjectSetting":{"Targeting":{"Default":true,"Level":"Information"}}}

NOTE
For the rest of this article, any key-value in App Configuration that has a valid JSON content-type and a valid JSON value will
be referred to as JSON key-value .

In this tutorial, you'll learn how to:


Create JSON key-values in App Configuration.
Import JSON key-values from a JSON file.
Export JSON key-values to a JSON file.
Consume JSON key-values in your applications.
Prerequisites
Azure subscription - create one for free.
Latest version of Azure CLI (2.10.0 or later). To find the version, run az --version . If you need to install or
upgrade, see Install Azure CLI. If you are using Azure CLI, you must first sign in using az login . You can
optionally use the Azure Cloud Shell.

Use Azure Cloud Shell


Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. You can use
either Bash or PowerShell with Cloud Shell to work with Azure services. You can use the Cloud Shell preinstalled
commands to run the code in this article without having to install anything on your local environment.
To start Azure Cloud Shell:

O P T IO N EXA M P L E/ L IN K

Select Tr y It in the upper-right corner of a code block.


Selecting Tr y It doesn't automatically copy the code to Cloud
Shell.

Go to https://shell.azure.com, or select the Launch Cloud


Shell button to open Cloud Shell in your browser.

Select the Cloud Shell button on the menu bar at the upper
right in the Azure portal.

To run the code in this article in Azure Cloud Shell:


1. Start Cloud Shell.
2. Select the Copy button on a code block to copy the code.
3. Paste the code into the Cloud Shell session by selecting Ctrl +Shift +V on Windows and Linux or by selecting
Cmd +Shift +V on macOS.
4. Select Enter to run the code.

Create an App Configuration store


1. To create a new App Configuration store, sign in to the Azure portal. In the upper-left corner of the home
page, select Create a resource . In the Search the Marketplace box, enter App Configuration and select
Enter.
2. Select App Configuration from the search results, and then select Create .

3. On the App Configuration > Create pane, enter the following settings:

SET T IN G SUGGEST ED VA L UE DESC RIP T IO N


SET T IN G SUGGEST ED VA L UE DESC RIP T IO N

Resource name Globally unique name Enter a unique resource name to use
for the App Configuration store
resource. The name must be a string
between 5 and 50 characters and
contain only numbers, letters, and
the - character. The name can't
start or end with the - character.

Subscription Your subscription Select the Azure subscription that


you want to use to test App
Configuration. If your account has
only one subscription, it's
automatically selected and the
Subscription list isn't displayed.

Resource group AppConfigTestResources Select or create a resource group for


your App Configuration store
resource. This group is useful for
organizing multiple resources that
you might want to delete at the same
time by deleting the resource group.
For more information, see Use
resource groups to manage your
Azure resources.

Location Central US Use Location to specify the


geographic location in which your
app configuration store is hosted. For
the best performance, create the
resource in the same region as other
components of your application.

Pricing tier Free Select the desired pricing tier. For


more details, please see the App
Configuration pricing page.

4. Select Create . The deployment might take a few minutes.


5. After the deployment finishes, select Settings > Access Keys . Make a note of the primary read-only key
connection string. You'll use this connection string later to configure your application to communicate with
the App Configuration store that you created.

Create JSON key-values in App Configuration


JSON key-values can be created using Azure portal, Azure CLI or by importing from a JSON file. In this section, you
will find instructions on creating the same JSON key-values using all three methods.
Create JSON key-values using Azure portal
Browse to your App Configuration store, and select Configuration Explorer > Create > Key-value to add the
following key-value pairs:

K EY VA L UE C O N T EN T T Y P E

Settings:BackgroundColor "Green" application/json

Settings:FontSize 24 application/json

Settings:UseDefaultRouting false application/json

Settings:BlockedUsers null application/json

Settings:ReleaseDate "2020-08-04T12:34:56.789Z" application/json

Settings:RolloutPercentage [25,50,75,100] application/json

Settings:Logging {"Test":{"Level":"Debug"},"Prod": application/json


{"Level":"Warning"}}

Leave Label empty and select Apply .


Create JSON key-values using Azure CLI
The following commands will create JSON key-values in your App Configuration store. Replace <appconfig_name>
with the name of your App Configuration store.

appConfigName=<appconfig_name>
az appconfig kv set -n $appConfigName --content-type application/json --key Settings:BackgroundColor --value
\"Green\"
az appconfig kv set -n $appConfigName --content-type application/json --key Settings:FontSize --value 24
az appconfig kv set -n $appConfigName --content-type application/json --key Settings:UseDefaultRouting --value
false
az appconfig kv set -n $appConfigName --content-type application/json --key Settings:BlockedUsers --value null
az appconfig kv set -n $appConfigName --content-type application/json --key Settings:ReleaseDate --value
\"2020-08-04T12:34:56.789Z\"
az appconfig kv set -n $appConfigName --content-type application/json --key Settings:RolloutPercentage --value
[25,50,75,100]
az appconfig kv set -n $appConfigName --content-type application/json --key Settings:Logging --value {\"Test\":
{\"Level\":\"Debug\"},\"Prod\":{\"Level\":\"Warning\"}}

IMPORTANT
If you are using Azure CLI or Azure Cloud Shell to create JSON key-values, the value provided must be an escaped JSON
string.
Import JSON key-values from a file
Create a JSON file called Import.json with the following content and import as key-values into App Configuration:

{
"Settings": {
"BackgroundColor": "Green",
"BlockedUsers": null,
"FontSize": 24,
"Logging": {"Test":{"Level":"Debug"},"Prod":{"Level":"Warning"}},
"ReleaseDate": "2020-08-04T12:34:56.789Z",
"RolloutPercentage": [25,50,75,100],
"UseDefaultRouting": false
}
}

az appconfig kv import -s file --format json --path "~/Import.json" --content-type "application/json" --


separator : --depth 2

NOTE
The --depth argument is used for flattening hierarchical data from a file into key-value pairs. In this tutorial, depth is
specified for demonstrating that you can also store JSON objects as values in App Configuration. If depth is not specified,
JSON objects will be flattened to the deepest level by default.

The JSON key-values you created should look like this in App Configuration:

Export JSON key-values to a file


One of the major benefits of using JSON key-values is the ability to preserve the original data type of your values
while exporting. If a key-value in App Configuration doesn't have JSON content-type, its value will be treated as
string.
Consider these key-values without JSON content-type:

K EY VA L UE C O N T EN T T Y P E

Settings:FontSize 24
K EY VA L UE C O N T EN T T Y P E

Settings:UseDefaultRouting false

When you export these key-values to a JSON file, the values will be exported as strings:

{
"Settings": {
"FontSize": "24",
"UseDefaultRouting": "false"
}
}

However, when you export JSON key-values to a file, all values will preserve their original data type. To verify this,
export key-values from your App Configuration to a JSON file. You'll see that the exported file has the same
contents as the Import.json file you previously imported.

az appconfig kv export -d file --format json --path "~/Export.json" --separator :

NOTE
If your App Configuration store has some key-values without JSON content-type, they will also be exported to the same file
in string format. If you want to export only the JSON key-values, assign a unique label or prefix to your JSON key-values and
use label or prefix filtering during export.

Consuming JSON key-values in applications


The easiest way to consume JSON key-values in your application is through App Configuration provider libraries.
With the provider libraries, you don't need to implement special handling of JSON key-values in your application.
They're always deserialized for your application in the same way that other JSON configuration provider libraries
do.

IMPORTANT
Native support for JSON key-values is available in .NET configuration provider version 4.0.0 (or later). See Next steps section
for more details.

If you are using the SDK or REST API to read key-values from App Configuration, based on the content-type, your
application is responsible for deserializing the value of a JSON key-value using any standard JSON deserializer.

Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.

IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make sure
that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article inside a
resource group that contains other resources you want to keep, delete each resource individually from its respective pane
instead of deleting the resource group.
1. Sign in to the Azure portal, and select Resource groups .
2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to confirm,
and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
Now that you know how to work with JSON key-values in your App Configuration store, create an application for
consuming these key-values:
ASP.NET Core quickstart
Prerequisite: Microsoft.Azure.AppConfiguration.AspNetCore package v4.0.0 or later.
.NET Core quickstart
Prerequisite: Microsoft.Extensions.Configuration.AzureAppConfiguration package v4.0.0 or later.
Route Azure App Configuration events to a web
endpoint with Azure CLI
9/22/2020 • 5 minutes to read • Edit Online

In this article, you learn how to set up Azure App Configuration event subscriptions to send key-value modification
events to a web endpoint. Azure App Configuration users can subscribe to events emitted whenever key-values
are modified. These events can trigger web hooks, Azure Functions, Azure Storage Queues, or any other event
handler that is supported by Azure Event Grid. Typically, you send events to an endpoint that processes the event
data and takes actions. However, to simplify this article, you send the events to a web app that collects and displays
the messages.

Prerequisites
Azure subscription - create one for free. You can optionally use the Azure Cloud Shell.

Use Azure Cloud Shell


Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. You can
use either Bash or PowerShell with Cloud Shell to work with Azure services. You can use the Cloud Shell
preinstalled commands to run the code in this article without having to install anything on your local environment.
To start Azure Cloud Shell:

O P T IO N EXA M P L E/ L IN K

Select Tr y It in the upper-right corner of a code block.


Selecting Tr y It doesn't automatically copy the code to Cloud
Shell.

Go to https://shell.azure.com, or select the Launch Cloud


Shell button to open Cloud Shell in your browser.

Select the Cloud Shell button on the menu bar at the upper
right in the Azure portal.

To run the code in this article in Azure Cloud Shell:


1. Start Cloud Shell.
2. Select the Copy button on a code block to copy the code.
3. Paste the code into the Cloud Shell session by selecting Ctrl +Shift +V on Windows and Linux or by
selecting Cmd +Shift +V on macOS.
4. Select Enter to run the code.
If you choose to install and use the CLI locally, this article requires that you're running the latest version of Azure
CLI (2.0.70 or later). To find the version, run az --version . If you need to install or upgrade, see Install Azure CLI.
If you aren't using Cloud Shell, you must first sign in using az login .
Create a resource group
Event Grid topics are Azure resources, and must be placed in an Azure resource group. The resource group is a
logical collection into which Azure resources are deployed and managed.
Create a resource group with the az group create command.
The following example creates a resource group named <resource_group_name> in the westus location. Replace
<resource_group_name> with a unique name for your resource group.

az group create --name <resource_group_name> --location westus

Create an App Configuration store


Replace <appconfig_name> with a unique name for your configuration store, and <resource_group_name> with the
resource group you created earlier. The name must be unique because it is used as a DNS name.

az appconfig create \
--name <appconfig_name> \
--location westus \
--resource-group <resource_group_name> \
--sku free

Create a message endpoint


Before subscribing to the topic, let's create the endpoint for the event message. Typically, the endpoint takes
actions based on the event data. To simplify this quickstart, you deploy a pre-built web app that displays the event
messages. The deployed solution includes an App Service plan, an App Service web app, and source code from
GitHub.
Replace <your-site-name> with a unique name for your web app. The web app name must be unique because it's
part of the DNS entry.

$sitename=<your-site-name>

az group deployment create \


--resource-group <resource_group_name> \
--template-uri "https://raw.githubusercontent.com/Azure-Samples/azure-event-grid-
viewer/master/azuredeploy.json" \
--parameters siteName=$sitename hostingPlanName=viewerhost

The deployment may take a few minutes to complete. After the deployment has succeeded, view your web app to
make sure it's running. In a web browser, navigate to: https://<your-site-name>.azurewebsites.net
You should see the site with no messages currently displayed.

Enable the Event Grid resource provider


If you haven't previously used Event Grid in your Azure subscription, you might need to register the Event Grid
resource provider. Run the following command to register the provider:

az provider register --namespace Microsoft.EventGrid

It might take a moment for the registration to finish. To check the status, run:
az provider show --namespace Microsoft.EventGrid --query "registrationState"

When registrationState is Registered , you're ready to continue.

Subscribe to your App Configuration store


You subscribe to a topic to tell Event Grid which events you want to track and where to send those events. The
following example subscribes to the App Configuration you created, and passes the URL from your web app as the
endpoint for event notification. Replace <event_subscription_name> with a name for your event subscription. For
<resource_group_name> and <appconfig_name> , use the values you created earlier.

The endpoint for your web app must include the suffix /api/updates/ .

appconfigId=$(az appconfig show --name <appconfig_name> --resource-group <resource_group_name> --query id --


output tsv)
endpoint=https://$sitename.azurewebsites.net/api/updates

az eventgrid event-subscription create \


--resource-id $appconfigId \
--name <event_subscription_name> \
--endpoint $endpoint

View your web app again, and notice that a subscription validation event has been sent to it. Select the eye icon to
expand the event data. Event Grid sends the validation event so the endpoint can verify that it wants to receive
event data. The web app includes code to validate the subscription.

Trigger an App Configuration event


Now, let's trigger an event to see how Event Grid distributes the message to your endpoint. Create a key-value
using the <appconfig_name> from earlier.

az appconfig kv set --name <appconfig_name> --key Foo --value Bar --yes

You've triggered the event, and Event Grid sent the message to the endpoint you configured when subscribing.
View your web app to see the event you just sent.
[{
"id": "deb8e00d-8c64-4b6e-9cab-282259c7674f",
"topic": "/subscriptions/{subscription-
id}/resourceGroups/eventDemoGroup/providers/microsoft.appconfiguration/configurationstores/{appconfig-name}",
"subject": "https://{appconfig-name}.azconfig.io/kv/Foo",
"data": {
"key": "Foo",
"etag": "a1LIDdNEIV6wCnfv3xaip7fMXD3"
},
"eventType": "Microsoft.AppConfiguration.KeyValueModified",
"eventTime": "2019-05-31T18:59:54Z",
"dataVersion": "1",
"metadataVersion": "1"
}]

Clean up resources
If you plan to continue working with this App Configuration and event subscription, do not clean up the resources
created in this article. If you do not plan to continue, use the following command to delete the resources you
created in this article.
Replace <resource_group_name> with the resource group you created above.

az group delete --name <resource_group_name>

Next steps
Now that you know how to create topics and event subscriptions, learn more about key-value events and what
Event Grid can help you do:
Reacting to Key-Value Events
About Event Grid
Azure Event Grid handlers
Back up App Configuration stores automatically
9/22/2020 • 9 minutes to read • Edit Online

In this article, you'll learn how to set up an automatic backup of key-values from a primary Azure App
Configuration store to a secondary store. The automatic backup uses the integration of Azure Event Grid with App
Configuration.
After you set up the automatic backup, App Configuration will publish events to Azure Event Grid for any changes
made to key-values in a configuration store. Event Grid supports a variety of Azure services from which users can
subscribe to the events emitted whenever key-values are created, updated, or deleted.

Overview
In this article, you'll use Azure Queue storage to receive events from Event Grid and use a timer-trigger of Azure
Functions to process events in the queue in batches.
When a function is triggered, based on the events, it will fetch the latest values of the keys that have changed from
the primary App Configuration store and update the secondary store accordingly. This setup helps combine
multiple changes that occur in a short period in one backup operation, which avoids excessive requests made to
your App Configuration stores.

Resource provisioning
The motivation behind backing up App Configuration stores is to use multiple configuration stores across different
Azure regions to increase the geo-resiliency of your application. To achieve this, your primary and secondary stores
should be in different Azure regions. All other resources created in this tutorial can be provisioned in any region of
your choice. This is because if primary region is down, there will be nothing new to back up until the primary
region is accessible again.
In this tutorial, you'll create a secondary store in the centralus region and all other resources in the westus
region.
Prerequisites
Azure subscription. Create one for free.
Visual Studio 2019 with the Azure development workload.
.NET Core SDK.
Latest version of the Azure CLI (2.3.1 or later). To find the version, run az --version . If you need to install or
upgrade, see Install Azure CLI. If you're using the Azure CLI, you must first sign in by using az login . You can
optionally use Azure Cloud Shell.

Use Azure Cloud Shell


Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. You can
use either Bash or PowerShell with Cloud Shell to work with Azure services. You can use the Cloud Shell
preinstalled commands to run the code in this article without having to install anything on your local environment.
To start Azure Cloud Shell:

O P T IO N EXA M P L E/ L IN K

Select Tr y It in the upper-right corner of a code block.


Selecting Tr y It doesn't automatically copy the code to Cloud
Shell.

Go to https://shell.azure.com, or select the Launch Cloud


Shell button to open Cloud Shell in your browser.

Select the Cloud Shell button on the menu bar at the upper
right in the Azure portal.

To run the code in this article in Azure Cloud Shell:


1. Start Cloud Shell.
2. Select the Copy button on a code block to copy the code.
3. Paste the code into the Cloud Shell session by selecting Ctrl +Shift +V on Windows and Linux or by
selecting Cmd +Shift +V on macOS.
4. Select Enter to run the code.

Create a resource group


The resource group is a logical collection into which Azure resources are deployed and managed.
Create a resource group by using the az group create command.
The following example creates a resource group named <resource_group_name> in the westus location. Replace
<resource_group_name> with a unique name for your resource group.

resourceGroupName="<resource_group_name>"
az group create --name $resourceGroupName --location westus

Create App Configuration stores


Create your primary and secondary App Configuration stores in different regions. Replace
<primary_appconfig_name>and <secondary_appconfig_name> with unique names for your configuration stores. Each
store name must be unique because it's used as a DNS name.

primaryAppConfigName="<primary_appconfig_name>"
secondaryAppConfigName="<secondary_appconfig_name>"
az appconfig create \
--name $primaryAppConfigName \
--location westus \
--resource-group $resourceGroupName\
--sku standard

az appconfig create \
--name $secondaryAppConfigName \
--location centralus \
--resource-group $resourceGroupName\
--sku standard

Create a queue
Create a storage account and a queue for receiving the events published by Event Grid.

storageName="<unique_storage_name>"
queueName="<queue_name>"
az storage account create -n $storageName -g $resourceGroupName -l westus --sku Standard_LRS
az storage queue create --name $queueName --account-name $storageName --auth-mode login

Enable the Event Grid resource provider


If you haven't previously used Event Grid in your Azure subscription, you might need to register the Event Grid
resource provider. Run the following command to register the provider:

az provider register --namespace Microsoft.EventGrid

It might take a moment for the registration to finish. To check the status, run:

az provider show --namespace Microsoft.EventGrid --query "registrationState"

When registrationState is Registered , you're ready to continue.

Subscribe to your App Configuration store events


You subscribe to these two events from the primary App Configuration store:
Microsoft.AppConfiguration.KeyValueModified
Microsoft.AppConfiguration.KeyValueDeleted

The following command creates an Event Grid subscription for the two events sent to your queue. The endpoint
type is set to storagequeue , and the endpoint is set to the queue ID. Replace <event_subscription_name> with the
name of your choice for the event subscription.
storageId=$(az storage account show --name $storageName --resource-group $resourceGroupName --query id --
output tsv)
queueId="$storageId/queueservices/default/queues/$queueName"
appconfigId=$(az appconfig show --name $primaryAppConfigName --resource-group $resourceGroupName --query id --
output tsv)
eventSubscriptionName="<event_subscription_name>"
az eventgrid event-subscription create \
--source-resource-id $appconfigId \
--name $eventSubscriptionName \
--endpoint-type storagequeue \
--endpoint $queueId \
--included-event-types Microsoft.AppConfiguration.KeyValueModified
Microsoft.AppConfiguration.KeyValueDeleted

Create functions for handling events from Queue storage


Set up with ready-to -use functions
In this article, you'll work with C# functions that have the following properties:
Runtime stack .NET Core 3.1
Azure Functions runtime version 3.x
Function triggered by timer every 10 minutes
To make it easier for you to start backing up your data, we've tested and published a function that you can use
without making any changes to the code. Download the project files and publish them to your own Azure function
app from Visual Studio.

IMPORTANT
Don't make any changes to the environment variables in the code you've downloaded. You'll create the required app settings
in the next section.

Build your own function


If the sample code provided earlier doesn't meet your requirements, you can also create your own function. Your
function must be able to perform the following tasks in order to complete the backup:
Periodically read contents of your queue to see if it contains any notifications from Event Grid. Refer to the
Storage Queue SDK for implementation details.
If your queue contains event notifications from Event Grid, extract all the unique <key, label> information
from event messages. The combination of key and label is the unique identifier for key-value changes in the
primary store.
Read all settings from the primary store. Update only those settings in the secondary store that have a
corresponding event in the queue. Delete all settings from the secondary store that were present in the queue
but not in the primary store. You can use the App Configuration SDK to access your configuration stores
programmatically.
Delete messages from the queue if there were no exceptions during processing.
Implement error handling according to your needs. Refer to the preceding code sample to see some common
exceptions that you might want to handle.
To learn more about creating a function, see: Create a function in Azure that is triggered by a timer and Develop
Azure Functions using Visual Studio.
IMPORTANT
Use your best judgement to choose the timer schedule based on how often you make changes to your primary
configuration store. Running the function too often might end up throttling requests for your store.

Create function app settings


If you're using a function that we've provided, you need the following app settings in your function app:
PrimaryStoreEndpoint : Endpoint for the primary App Configuration store. An example is
https://{primary_appconfig_name}.azconfig.io .
SecondaryStoreEndpoint : Endpoint for the secondary App Configuration store. An example is
https://{secondary_appconfig_name}.azconfig.io .
StorageQueueUri : Queue URI. An example is https://{unique_storage_name}.queue.core.windows.net/{queue_name}
.
The following command creates the required app settings in your function app. Replace <function_app_name> with
the name of your function app.

functionAppName="<function_app_name>"
primaryStoreEndpoint="https://$primaryAppConfigName.azconfig.io"
secondaryStoreEndpoint="https://$secondaryAppConfigName.azconfig.io"
storageQueueUri="https://$storageName.queue.core.windows.net/$queueName"
az functionapp config appsettings set --name $functionAppName --resource-group $resourceGroupName --settings
StorageQueueUri=$storageQueueUri PrimaryStoreEndpoint=$primaryStoreEndpoint
SecondaryStoreEndpoint=$secondaryStoreEndpoint

Grant access to the managed identity of the function app


Use the following command or the Azure portal to add a system-assigned managed identity for your function app.

az functionapp identity assign --name $functionAppName --resource-group $resourceGroupName

NOTE
To perform the required resource creation and role management, your account needs Owner permissions at the appropriate
scope (your subscription or resource group). If you need assistance with role assignment, learn how to add or remove Azure
role assignments by using the Azure portal.

Use the following commands or the Azure portal to grant the managed identity of your function app access to your
App Configuration stores. Use these roles:
Assign the App Configuration Data Reader role in the primary App Configuration store.
Assign the App Configuration Data Owner role in the secondary App Configuration store.
functionPrincipalId=$(az functionapp identity show --name $functionAppName --resource-group
$resourceGroupName --query principalId --output tsv)
primaryAppConfigId=$(az appconfig show -n $primaryAppConfigName --query id --output tsv)
secondaryAppConfigId=$(az appconfig show -n $secondaryAppConfigName --query id --output tsv)

az role assignment create \


--role "App Configuration Data Reader" \
--assignee $functionPrincipalId \
--scope $primaryAppConfigId

az role assignment create \


--role "App Configuration Data Owner" \
--assignee $functionPrincipalId \
--scope $secondaryAppConfigId

Use the following command or the Azure portal to grant the managed identity of your function app access to your
queue. Assign the Storage Queue Data Contributor role in the queue.

az role assignment create \


--role "Storage Queue Data Contributor" \
--assignee $functionPrincipalId \
--scope $queueId

Trigger an App Configuration event


To test that everything works, you can create, update, or delete a key-value from the primary store. You should
automatically see this change in the secondary store a few seconds after the timer triggers Azure Functions.

az appconfig kv set --name $primaryAppConfigName --key Foo --value Bar --yes

You've triggered the event. In a few moments, Event Grid will send the event notification to your queue. After the
next scheduled run of your function, view configuration settings in your secondary store to see if it contains the
updated key-value from the primary store.

NOTE
You can trigger your function manually during the testing and troubleshooting without waiting for the scheduled timer-
trigger.

After you make sure that the backup function ran successfully, you can see that the key is now present in your
secondary store.

az appconfig kv show --name $secondaryAppConfigName --key Foo

{
"contentType": null,
"etag": "eVgJugUUuopXnbCxg0dB63PDEJY",
"key": "Foo",
"label": null,
"lastModified": "2020-04-27T23:25:08+00:00",
"locked": false,
"tags": {},
"value": "Bar"
}
Troubleshooting
If you don't see the new setting in your secondary store:
Make sure the backup function was triggered after you created the setting in your primary store.
It's possible that Event Grid couldn't send the event notification to the queue in time. Check if your queue still
contains the event notification from your primary store. If it does, trigger the backup function again.
Check Azure Functions logs for any errors or warnings.
Use the Azure portal to ensure that the Azure function app contains correct values for the application settings
that Azure Functions is trying to read.
You can also set up monitoring and alerting for Azure Functions by using Azure Application Insights.

Clean up resources
If you plan to continue working with this App Configuration and event subscription, don't clean up the resources
created in this article. If you don't plan to continue, use the following command to delete the resources created in
this article.

az group delete --name $resourceGroupName

Next steps
Now that you know how to set up automatic backup of your key-values, learn more about how you can increase
the geo-resiliency of your application:
Resiliency and disaster recovery
Use managed identities to access App Configuration
9/22/2020 • 8 minutes to read • Edit Online

Azure Active Directory managed identities simplify secrets management for your cloud application. With a
managed identity, your code can use the service principal created for the Azure service it runs on. You use a
managed identity instead of a separate credential stored in Azure Key Vault or a local connection string.
Azure App Configuration and its .NET Core, .NET Framework, and Java Spring client libraries have managed
identity support built into them. Although you aren't required to use it, the managed identity eliminates the need
for an access token that contains secrets. Your code can access the App Configuration store using only the
service endpoint. You can embed this URL in your code directly without exposing any secret.
This article shows how you can take advantage of the managed identity to access App Configuration. It builds on
the web app introduced in the quickstarts. Before you continue, Create an ASP.NET Core app with App
Configuration first.
This article also shows how you can use the managed identity in conjunction with App Configuration's Key Vault
references. With a single managed identity, you can seamlessly access both secrets from Key Vault and
configuration values from App Configuration. If you wish to explore this capability, finish Use Key Vault
References with ASP.NET Core first.
You can use any code editor to do the steps in this tutorial. Visual Studio Code is an excellent option available on
the Windows, macOS, and Linux platforms.
In this article, you learn how to:
Grant a managed identity access to App Configuration.
Configure your app to use a managed identity when you connect to App Configuration.
Optionally, configure your app to use a managed identity when you connect to Key Vault through an App
Configuration Key Vault reference.

Prerequisites
To complete this tutorial, you must have:
.NET Core SDK.
Azure Cloud Shell configured.
If you don't have an Azure subscription, create a free account before you begin.

Add a managed identity


To set up a managed identity in the portal, you first create an application and then enable the feature.
1. Create an App Services instance in the Azure portal as you normally do. Go to it in the portal.
2. Scroll down to the Settings group in the left pane, and select Identity .
3. On the System assigned tab, switch Status to On and select Save .
4. Answer Yes when prompted to enable system assigned managed identity.
Grant access to App Configuration
1. In the Azure portal, select All resources and select the App Configuration store that you created in the
quickstart.
2. Select Access control (IAM) .
3. On the Check access tab, select Add in the Add role assignment card UI.
4. Under Role , select App Configuration Data Reader . Under Assign access to , select App Ser vice
under System assigned managed identity .
5. Under Subscription , select your Azure subscription. Select the App Service resource for your app.
6. Select Save .

7. Optional: If you wish to grant access to Key Vault as well, follow the directions in Assign a Key Vault access
policy.
Use a managed identity
1. Add a reference to the Azure.Identity package:

dotnet add package Azure.Identity

2. Find the endpoint to your App Configuration store. This URL is listed on the Access keys tab for the store
in the Azure portal.
3. Open appsettings.json, and add the following script. Replace <service_endpoint>, including the brackets,
with the URL to your App Configuration store.

"AppConfig": {
"Endpoint": "<service_endpoint>"
}

4. Open Program.cs, and add a reference to the Azure.Identity and


Microsoft.Azure.Services.AppAuthentication namespaces:

using Azure.Identity;

5. If you wish to access only values stored directly in App Configuration, update the CreateWebHostBuilder
method by replacing the config.AddAzureAppConfiguration() method.

IMPORTANT
CreateHostBuilder replaces CreateWebHostBuilder in .NET Core 3.0. Select the correct syntax based on your
environment.

.NET Core 2.x


.NET Core 3.x

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options =>
options.Connect(new Uri(settings["AppConfig:Endpoint"]), new
ManagedIdentityCredential()));
})
.UseStartup<Startup>();

6. To use both App Configuration values and Key Vault references, update Program.cs as shown below. This
code creates a new KeyVaultClient using an AzureServiceTokenProvider and passes this reference to a
call to the UseAzureKeyVault method.
.NET Core 2.x
.NET Core 3.x
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
var credentials = new ManagedIdentityCredential();

config.AddAzureAppConfiguration(options =>
{
options.Connect(new Uri(settings["AppConfig:Endpoint"]), credentials)
.ConfigureKeyVault(kv =>
{
kv.SetCredential(credentials);
});
});
})
.UseStartup<Startup>();

You can now access Key Vault references just like any other App Configuration key. The config provider
will use the KeyVaultClient that you configured to authenticate to Key Vault and retrieve the value.

NOTE
ManagedIdentityCredential only supports managed identity authentication. It doesn't work in local environments. If
you want to run the code locally, consider using DefaultAzureCredential , which supports service principal
authentication as well. Check the link for details.

Prepare your repository


To get automatic builds from Azure App Service Kudu build server, make sure that your repository root has the
correct files in your project.

RUN T IM E RO OT DIREC TO RY F IL ES

ASP.NET (Windows only) *.sln, *.csproj, or default.aspx

ASP.NET Core *.sln or *.csproj

PHP index.php

Ruby (Linux only) Gemfile

Node.js server.js, app.js, or package.json with a start script

Python *.py, requirements.txt, or runtime.txt

HTML default.htm, default.html, default.asp, index.htm, index.html,


or iisstart.htm

WebJobs <job_name>/run.<extension> under


App_Data/jobs/continuous for continuous WebJobs, or
App_Data/jobs/triggered for triggered WebJobs. For more
information, see Kudu WebJobs documentation.

Functions See Continuous deployment for Azure Functions.


To customize your deployment, include a .deployment file in the repository root. For more information, see
Customize deployments and Custom deployment script.

NOTE
If you develop in Visual Studio, let Visual Studio create a repository for you. The project is immediately ready to be
deployed by using Git.

Deploy from local Git


The easiest way to enable local Git deployment for your app with the Kudu build server is to use Azure Cloud
Shell.
Configure a deployment user
FTP and local Git can deploy to an Azure web app by using a deployment user. Once you configure your
deployment user, you can use it for all your Azure deployments. Your account-level deployment username and
password are different from your Azure subscription credentials.
To configure the deployment user, run the az webapp deployment user set command in Azure Cloud Shell.
Replace <username> and <password> with a deployment user username and password.
The username must be unique within Azure, and for local Git pushes, must not contain the ‘@’ symbol.
The password must be at least eight characters long, with two of the following three elements: letters,
numbers, and symbols.

az webapp deployment user set --user-name <username> --password <password>

The JSON output shows the password as null . If you get a 'Conflict'. Details: 409 error, change the
username. If you get a 'Bad Request'. Details: 400 error, use a stronger password.
Record your username and password to use to deploy your web apps.
Enable local Git with Kudu
If you don't have a local git repository for your app, you'll need to initialize one. To initialize a local git repository,
run the following commands from your app's project directory:

git init
git add .
git commit -m "Initial version"

To enable local Git deployment for your app with the Kudu build server, run
az webapp deployment source config-local-git in Cloud Shell.

az webapp deployment source config-local-git --name <app_name> --resource-group <group_name>

This command gives you something similar to the following output:

{
"url": "https://<username>@<app_name>.scm.azurewebsites.net/<app_name>.git"
}

Deploy your project


In the local terminal window , add an Azure remote to your local Git repository. Replace <url> with the URL of
the Git remote that you got from Enable local Git with Kudu.

git remote add azure <url>

Push to the Azure remote to deploy your app with the following command. When you're prompted for a
password, enter the password you created in Configure a deployment user. Don't use the password you use to
sign in to the Azure portal.

git push azure master

You might see runtime-specific automation in the output, such as MSBuild for ASP.NET, npm install for Node.js,
and pip install for Python.
Browse to the Azure web app
Browse to your web app by using a browser to verify that the content is deployed.

http://<app_name>.azurewebsites.net

Use managed identity in other languages


App Configuration providers for .NET Framework and Java Spring also have built-in support for managed
identity. You can use your store's URL endpoint instead of its full connection string when you configure one of
these providers.
For example, you can update the .NET Framework console app created in the quickstart to specify the following
settings in the App.config file:

<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection,
System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
restartOnExternalChanges="false" requirePermission="false" />
</configSections>

<configBuilders>
<builders>
<add name="MyConfigStore" mode="Greedy" endpoint="${Endpoint}"
type="Microsoft.Configuration.ConfigurationBuilders.AzureAppConfigurationBuilder,
Microsoft.Configuration.ConfigurationBuilders.AzureAppConfiguration" />
<add name="Environment" mode="Greedy"
type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder,
Microsoft.Configuration.ConfigurationBuilders.Environment" />
</builders>
</configBuilders>

<appSettings configBuilders="Environment,MyConfigStore">
<add key="AppName" value="Console App Demo" />
<add key="Endpoint" value ="Set via an environment variable - for example, dev, test, staging, or
production endpoint." />
</appSettings>

Clean up resources
If you do not want to continue using the resources created in this article, delete the resource group you created
here to avoid charges.
IMPORTANT
Deleting a resource group is irreversible. The resource group and all the resources in it are permanently deleted. Make
sure that you don't accidentally delete the wrong resource group or resources. If you created the resources for this article
inside a resource group that contains other resources you want to keep, delete each resource individually from its
respective pane instead of deleting the resource group.

1. Sign in to the Azure portal, and select Resource groups .


2. In the Filter by name box, enter the name of your resource group.
3. In the result list, select the resource group name to see an overview.
4. Select Delete resource group .
5. You're asked to confirm the deletion of the resource group. Enter the name of your resource group to
confirm, and select Delete .
After a few moments, the resource group and all its resources are deleted.

Next steps
In this tutorial, you added an Azure managed identity to streamline access to App Configuration and improve
credential management for your app. To learn more about how to use App Configuration, continue to the Azure
CLI samples.
CLI samples
Azure Policy built-in definitions for Azure App
Configuration
9/22/2020 • 2 minutes to read • Edit Online

This page is an index of Azure Policy built-in policy definitions for Azure App Configuration. For additional Azure
Policy built-ins for other services, see Azure Policy built-in definitions.
The name of each built-in policy definition links to the policy definition in the Azure portal. Use the link in the
Version column to view the source on the Azure Policy GitHub repo.

Azure App Configuration


NAME VERSIO N
( A ZURE PO RTA L) DESC RIP T IO N EF F EC T ( S) ( GIT HUB)

App Configuration should Customer-managed keys Audit, Disabled 1.0.1


use a customer-managed provide enhanced data
key protection by allowing you
to manage your encryption
keys. This is often required
to meet compliance
requirements.

App Configuration should Private endpoint AuditIfNotExists, Disabled 1.0.1


use a private link connections allow clients on
a virtual network to securely
access Azure App
Configuration over a private
link.

Next steps
See the built-ins on the Azure Policy GitHub repo.
Review the Azure Policy definition structure.
Review Understanding policy effects.

You might also like