Asp.Net Core Environment Variable Colon in Linux

ASP.NET Core Environment variable colon in Linux

Reading the docs carefully:

If : cannot be used in environment variables in your system, replace : with __ (double underscore).

ie:

export MySettings__SomeSetting=MyNewValue

Merging appsettings with environment variables in .NET Core

config.
AddJsonFile("appsettings.json").
AddJsonFile("appsettings.docker.json", true).
AddEnvironmentVariables();

is actually enough to override appsettings values using environment variables.

Let's say you have the following in your appsettings.json file;

{
"Logging": {
"Level": "Debug"
}
}

you can override value of Logging.Level by setting the environment variable named Logging:Level to the value of your preference.

Be aware that : is used to specify nested properties in environment variable keys.

Also note: from docs;

If a colon (:) can't be used in environment variable names on your system, replace the colon (:) with a double-underscore (__).

How to correctly store connection strings in environment variables for retrieval by production ASP.Net Core MVC applications

There is a typo/wrong value set in your connection variables.

Which can be seen in this output you pasted:

Variable                    Value
ConnectionStrings:TestDb "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"

This likely happend while setting the variable via

$env:ConnectionStrings:MyDb = """Server=..."""

the correct way is to set it without the quotation marks.

$env:ConnectionStrings:MyDb = "Server=..."

Old answer (for other users who may search for similar issues)

The convention for connection strings is SQLCONNSTR_, MYSQLCONNSTR_, SQLAZURECONNSTR_ and CUSTOMCONNSTR_ which are used by Azure Web Apps, but should also work for self-hosting, VMs or any other cloud provider.

So if you have an environment variable called CUSTOMCONNSTR_TestDb it will be the same as defining it in appsettings.json in

{
"connectionStrings": {
"TestDb": "..."
}
}

It will also override the value inside it, if AddEnvironmentVariables() is called after .UseJsonFile(...). Last registration wins.

var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
// This one needs to be last
.AddEnvironmentVariables();

You can also use other variables to override configuration values. iirc. ASPNETCORE_ is the default prefix (but you can change it in the AddEnvironmentVariables("MY_")).

So a ASPNETCORE_MySettings overrides Configuration["MySettings"] (or Configuration.Get("MySettings")) and ASPNETCORE_My__Settings (use double underscore for level hierarchy on Linux, read where : is used to obtain the config - Linux disallows colon in variable names) overrides Configuration["My:Settings"] so same as

{
"my": {
"settings": "..."
}
}

Unless they changed that recently.

FWIW: Environment variables/configuration key names are case-insensitive as far as I remember.

How to override ASP.NET Core configuration array settings using environment variables

After looking at the configuration in the debugger I found the answer.

  • Serilog__WriteTo__0__Args__path (All platforms)
  • Serilog:WriteTo:0:Args:path (Windows)
  • Serilog--WriteTo--0--Args--path (sourced From Azure Key Vault)

Note: The Configuration in ASP.NET Core documentation now covers this.

So I need to use the array index (zero-based) as if it were a name.

Here is the screenshot of the debugger, also (thanks to Victor Hurdugaci in the comments), the unit tests are a good place to look for examples.

configuration in the debugger

Sending .Net Core application settings to kubernetes pods as environment variables

I believe you are referring to the env in the container definition for a Pod. From the YAML/JSON perspective, I don't see a problem with specifying a : in a key for an environment variable. You can also put it within quotes and should be valid JSON/YAML:

# convert.yaml
apiVersion: v1
kind: Pod
metadata:
name: envar-demo
labels:
purpose: demonstrate-envars
spec:
containers:
- name: envar-demo-container
image: dotnetapp
env:
- name: ConnectionString:Mydb
value: ConnectionString

Same in JSON:

$ kubectl convert -f convert.yaml -o=json
{
"kind": "Pod",
"apiVersion": "v1",
"metadata": {
"name": "envar-demo",
"creationTimestamp": null,
"labels": {
"purpose": "demonstrate-envars"
}
},
"spec": {
"containers": [
{
"name": "envar-demo-container",
"image": "dotnetapp",
"env": [
{
"name": "ConnectionString:Mydb",
"value": "ConnectionString"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"imagePullPolicy": "Always"
}
],
"restartPolicy": "Always",
"terminationGracePeriodSeconds": 30,
"dnsPolicy": "ClusterFirst",
"securityContext": {},
"schedulerName": "default-scheduler"
},
"status": {}
}

However, looks like this was a known issue with Windows/.NET applications. An attempt to fix it has been tried and ditched due to the fact the this is not valid in Bash. But looks like they settled to use the __ instead of : workaround

Configuring AppSettings with ASP.Net Core on Azure Web App for Containers: Whither Colons?

After more experimentation than I'd like to admit I think I have the answer.

Where you use : on an App Service, use a __ (double underscore) on an App Service with containers.

So Parent__ChildOne instead of Parent:ChildOne.

To read a little more (not much more), I wrote this up as a blog post here: https://blog.johnnyreilly.com/2018/07/28/azure-app-service-web-app-containers-asp-net-nested-configuration/



Related Topics



Leave a reply



Submit