TL;DR Replace dots with underscore and colons with double underscores.

Consider the following IOptions<MetroSettings> implementation

public class MetroSettings  
{
    public RealTimeDepartures RealTimeDepartures { get; set; }
}

public class RealTimeDepartures  
{
    public string ApiKey { get; set; }
    public string BaseUrl { get; set; }
}

In my Startup I have the following code:

...
var builder = new ConfigurationBuilder()  
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", true, true)
        .AddEnvironmentVariables("MyNamespace.MyPrefix.");
Configuration = builder.Build();  
...

And my appsettings.json looks like this:

{
    "Metro": {
        "RealTimeDepartures": {
            "ApiKey": "OVERRIDE ME WITH A SYSTEM ENVIRONMENT VARIABLE",
            "BaseUrl": "http://example.com"
        }
    }
}

I don't like having API keys and other sensitive data in config files, I prefer environment variables.

In ASP.Net core it's pretty straight forward to transform the appsettings file with environment variables.

On windows you just run this in your terminal:

set MyNamespace.MyPrefix.Metro:RealTimeDepartures:ApiKey=MySecretApiKeyHere  

and your good to go, at least in a windows environment.

I, however, wanted to run my application on a Ubuntu server and I ran into some problems.

When I ran the following command

export MyNamespace.MyPrefix.Metro:RealTimeDepartures:ApiKey=TESTING  

I got the following error:

export: MyNamespace.Metro:RealTimeDepartures:ApiKey=TESTING': not a valid identifier  

Apparently you are not allowed to have dots or colons in the environment variable name.

So, what to do?

Luckily I found this issue on github (open source ftw!) and I was able to make it work by doing the following:

  • Change my prefix from MyNamespace.MyPrefix. to MyNamespace_MyPrefix_ in the Startup file.
  • Replace the colons with double underscores instead

Before:

MyNamespace.MyPrefix.Metro:RealTimeDepartures:ApiKey=TESTING  

After:

MyNamespace_MyPrefix_Metro__RealTimeDepartures__ApiKey=TESTING  
  • Setting the correct environment variables in windows and ubuntu.

Windows:

set MyNamespace_MyPrefix_Metro__RealTimeDepartures__ApiKey=MySecretApiKeyHere  

Ubuntu:

export MyNamespace_MyPrefix_Metro__RealTimeDepartures__ApiKey=MySecretApiKeyHere  

(I actually ended up adding the variable directly in the /etc/environment file)