Azure App Configuration
Azure App Configuration
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.
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
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.
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.
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.
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.
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
3. On the App Configuration > Create pane, enter the following settings:
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.
K EY VA L UE
TestApp:Settings:BackgroundColor White
TestApp:Settings:FontSize 24
TestApp:Settings:FontColor Black
Leave Label and Content Type empty for now. Select Apply .
IMPORTANT
CreateHostBuilder replaces CreateWebHostBuilder in .NET Core 3.0. Select the correct syntax based on your
environment.
<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>
TIP
To learn more about Secret Manager, please see Safe storage of app secrets in development in ASP.NET Core
dotnet restore
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;
IMPORTANT
CreateHostBuilder replaces CreateWebHostBuilder in .NET Core 3.0. Select the correct syntax based on your
environment.
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>
<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>
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.
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.
2. Select App Configuration from the search results, and then select Create .
3. On the App Configuration > Create pane, enter the following settings:
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.
K EY VA L UE
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.
$Env:ConnectionString = "connection-string-of-your-app-configuration-store"
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.
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
2. Select App Configuration from the search results, and then select Create .
3. On the App Configuration > Create pane, enter the following settings:
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.
K EY VA L UE
<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 .
Console.WriteLine(message);
}
$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.
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
2. Select App Configuration from the search results, and then select Create .
3. On the App Configuration > Create pane, enter the following settings:
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.
K EY VA L UE
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.
static Function1()
{
var builder = new ConfigurationBuilder();
builder.AddAzureAppConfiguration(Environment.GetEnvironmentVariable("ConnectionString"));
Configuration = builder.Build();
}
$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.
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.
2. Select App Configuration from the search results, and then select Create .
3. On the App Configuration > Create pane, enter the following settings:
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.
K EY VA L UE
/application/config.message Hello
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-appconfiguration-config</artifactId>
<version>1.1.5</version>
</dependency>
<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;
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;
@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}
$Env:APP_CONFIGURATION_CONNECTION_STRING = "connection-string-of-your-app-configuration-store"
export APP_CONFIGURATION_CONNECTION_STRING='connection-string-of-your-app-configuration-store'
2. After your application is running, use curl to test your application, for example:
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.
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.
{
"$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.
K EY VA L UE L A B EL
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 .
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.
3. On the App Configuration > Create pane, enter the following settings:
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.
Leave label undefined for now. Select Apply to save the new feature flag.
IMPORTANT
CreateHostBuilder replaces CreateWebHostBuilder in .NET Core 3.0. Select the correct syntax based on your
environment.
<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>
TIP
To learn more about Secret Manager, please see Safe storage of app secrets in development in ASP.NET Core.
dotnet restore
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.
5. Open Startup.cs, and add references to the .NET Core feature manager:
using Microsoft.FeatureManagement;
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
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAzureAppConfiguration();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
namespace TestFeatureFlags
{
public enum MyFeatureFlags
{
Beta
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.FeatureManagement;
using Microsoft.FeatureManagement.Mvc;
namespace TestFeatureFlags.Controllers
{
public class BetaController: Controller
{
private readonly IFeatureManager _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:
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>
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.
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.
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
3. On the App Configuration > Create pane, enter the following settings:
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.
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Configuration.AzureAppConfiguration
Microsoft.FeatureManagement
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();
services.AddSingleton<IConfiguration>(configuration).AddFeatureManagement();
if (await featureManager.IsEnabledAsync("Beta"))
{
Console.WriteLine("Welcome to the beta!");
}
}
Console.WriteLine("Hello World!");
}
$Env:ConnectionString = "connection-string-of-your-app-configuration-store"
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.
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
3. On the App Configuration > Create pane, enter the following settings:
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.
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.
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.
static Function1()
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddAzureAppConfiguration(options =>
{
options.Connect(Environment.GetEnvironmentVariable("ConnectionString"))
.UseFeatureFlags();
}).Build();
ServiceProvider = services.BuildServiceProvider();
}
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";
$Env:ConnectionString = "connection-string-of-your-app-configuration-store"
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.
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.
3. On the App Configuration > Create pane, enter the following settings:
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.
<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>
<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.
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 {
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;
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 {
@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>
</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">© 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;
}
code {
font-size: 80%;
}
K EY STAT E
Beta On
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.
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.
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; }
}
}
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
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.
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
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>
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: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.
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.
namespace TestConsole
{
class Program
{
private static IConfiguration _configuration = null;
private static IConfigurationRefresher _refresher = null;
_refresher = options.GetRefresher();
});
_configuration = builder.Build();
PrintMessage().Wait();
}
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.
$Env:ConnectionString = "connection-string-of-your-app-configuration-store"
export ConnectionString='connection-string-of-your-app-configuration-store'
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
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.
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
3. On the App Configuration > Create pane, enter the following settings:
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.
K EY VA L UE
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
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.
await _refresher.TryRefreshAsync();
Console.WriteLine(_configuration["TestApp:Settings:Message"] ?? "Hello world!");
}
$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
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.
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
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.
await ConfigurationRefresher.TryRefreshAsync();
$Env:ConnectionString = "connection-string-of-your-app-configuration-store"
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
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.
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.
<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-appconfiguration-config-web</artifactId>
<version>1.2.7</version>
</dependency>
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:
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.
using Microsoft.FeatureManagement;
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;
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;
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;
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);
});
});
"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.
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:
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
{
...
}
[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.
The feature <feature> tag can also be used to show content if any or all features in a list are enabled.
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;
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:
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.
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>
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.
Dependency injection
In Spring Boot, you can access the feature manager FeatureManager through dependency injection:
@Controller
@ConfigurationProperties("controller")
public class HomeController {
private 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.
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
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 .
{
"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:
3. Add environment variables to store the values of clientId, clientSecret, and tenantId.
Windows command prompt
PowerShell
Bash
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.
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 .
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.
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 .
{
"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:
3. Run the following command to get your object-id, then add it to App Configuration.
$Env:AZURE_CLIENT_ID = "clientId"
$Env:AZURE_CLIENT_SECRET = "clientSecret"
$Env:AZURE_TENANT_ID = "tenantId"
spring.cloud.azure.appconfiguration.stores[0].endpoint= ${APP_CONFIGURATION_ENDPOINT}
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;
@Override
public TokenCredential getKeyVaultCredential(String uri) {
return getCredential();
}
@Override
public TokenCredential getAppConfigCredential(String uri) {
return getCredential();
}
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:
9. After your application is running, use curl to test your application, for example:
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.
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.
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.
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: ':'
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
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: ':'
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'
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 }}
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'
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"}
NOTE
Input IDs are case insensitive.
IN P UT N A M E REQ UIRED? VA L UE
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.
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>();
$Env:ConnectionString = "connection-string-of-your-app-configuration-store"
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.
3. On the App Configuration > Create pane, enter the following settings:
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.
K EY VA L UE
settings.color White
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.
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.
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.
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.
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.
Delete
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:
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
L A B EL DESC RIP T IO N
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.
Retrieve all recorded changes for the key environment and the labels test and prod .
Retrieve all recorded changes for the key color at a specific point-in-time.
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.
if (featureFlag) {
// Run the following code
}
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
}
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.
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.
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.
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
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.
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:
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:
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 .
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.
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.
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:
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
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:
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.
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.
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.
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.
On the Add Value screen, enter a Value of red and a Label of Development . Leave Content type empty. Select
Apply .
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.
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 .
O P T IO N EXA M P L E/ L IN K
Select the Cloud Shell button on the menu bar at the upper
right in the Azure portal.
3. On the App Configuration > Create pane, enter the following settings:
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.
K EY VA L UE C O N T EN T T Y P E
Settings:FontSize 24 application/json
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
}
}
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:
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.
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.
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.
O P T IO N EXA M P L E/ L IN K
Select the Cloud Shell button on the menu bar at the upper
right in the Azure portal.
az appconfig create \
--name <appconfig_name> \
--location westus \
--resource-group <resource_group_name> \
--sku free
$sitename=<your-site-name>
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.
It might take a moment for the registration to finish. To check the status, run:
az provider show --namespace Microsoft.EventGrid --query "registrationState"
The endpoint for your web app must include the suffix /api/updates/ .
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.
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.
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.
O P T IO N EXA M P L E/ L IN K
Select the Cloud Shell button on the menu bar at the upper
right in the Azure portal.
resourceGroupName="<resource_group_name>"
az group create --name $resourceGroupName --location westus
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
It might take a moment for the registration to finish. To check the status, run:
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
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.
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
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)
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.
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.
{
"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.
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.
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:
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>"
}
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.
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.
RUN T IM E RO OT DIREC TO RY F IL ES
PHP index.php
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.
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.
{
"url": "https://<username>@<app_name>.scm.azurewebsites.net/<app_name>.git"
}
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.
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
<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.
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.
Next steps
See the built-ins on the Azure Policy GitHub repo.
Review the Azure Policy definition structure.
Review Understanding policy effects.