Best place to store environment variables for Azure Function

DarthVadar123451 picture DarthVadar123451 · Jan 5, 2017 · Viewed 33k times · Source

I'm testing an azure function locally with several api keys. Whats the best place to store environment variables and how do I access them? I tried

System.Environment.GetEnvironmentVariable("name")}

but I'm not sure where the environment variable is stored.

Thanks!

Answer

chris31389 picture chris31389 · Nov 22, 2017

You should have a file called local.settings.json. Here is the azure website for Functions-Run-Local

It states

These settings can also be read in your code as environment variables. In C#, use System.Environment.GetEnvironmentVariable or ConfigurationManager.AppSettings. In JavaScript, use process.env. Settings specified as a system environment variable take precedence over values in the local.settings.json file.

example local.settings.json

{
  "IsEncrypted": false,   
  "Values": {
    "AzureWebJobsStorage": "<connection string>", 
    "AzureWebJobsDashboard": "<connection string>" 
  },
  "Host": {
    "LocalHttpPort": 7071, 
    "CORS": "*" 
  },
  "ConnectionStrings": {
    "SQLConnectionString": "Value"
  }
}

It says that you need to put the application settings under the Values property within the local.settings.json.

To retrieve I used ConfigurationManager.AppSettings["CustomSetting"] as it lets you retrieve connection strings.

I have just been playing around with this and discovered that you have to have a a string key and a string value. I got an error when I tried having a subsection (like you would in an appsettings.json). I had to have the local.settings.json look like this:

{
  "IsEncrypted": false,   
  "Values": {
    "AzureWebJobsStorage": "<connection string>", 
    "AzureWebJobsDashboard": "<connection string>" 
    "CustomSetting":"20"
  }
}