How to add configuration values in AppSettings.json in Azure functions. Is there any structure for it?
In Azure Functions 2.x, you need to use the .Net core configuration management style, contained in package Microsoft.Extensions.Configuration
. This allows you to create a local settings.json
file on your dev computer for local configuration in the Values
and ConnectionString
portion of the json file. The local json
settings file isn't published to Azure, and instead, Azure will obtain settings from the Application Settings associated with the Function.
In your function code, accept a parameter of type Microsoft.Azure.WebJobs.ExecutionContext context
, where you can then build an IConfigurationRoot
provider:
[FunctionName("MyFunction")]
public static async Task Run([TimerTrigger("0 */15 * * * *")]TimerInfo myTimer,
TraceWriter log, Microsoft.Azure.WebJobs.ExecutionContext context,
CancellationToken ctx)
{
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
// This abstracts away the .json and app settings duality
var myValue = config["MyKey"];
var myConnString = config.GetConnectionString("connString");
... etc
The AddJsonFile
allows you to add a local development config file e.g. local.settings.json
containing local dev values (not published)
{
"IsEncrypted": false,
"Values": {
"MyKey": "MyValue",
...
},
"ConnectionStrings": {
"connString": "...."
}
Although seemingly using ConnectionStrings for anything other than EF seems to be discouraged
And once deployed to Azure, you can change the values of the settings on the function Application Settings blade:
As stated here
These settings can also be read in your code as environment variables. In C#, use
System.Environment.GetEnvironmentVariable
orConfigurationManager.AppSettings
. In JavaScript, useprocess.env
. Settings specified as a system environment variable take precedence over values in thelocal.settings.json
file.
You don't have to use System.Environment.GetEnvironmentVariable()
to access your app settings.
ConfigurationManager
is available to Azure Functions in run.csx like so:
System.Configuration.ConfigurationManager.AppSettings["SettingName"]