Home > Back-end >  how does a variable in appsetting.json get swapped with actual value?
how does a variable in appsetting.json get swapped with actual value?

Time:03-11

in some asp.net core projects, I often see something like this in appsetting.json file:

{
   "Logging": {
      "LogLevel": {
        "Default": "Warning"
      }
   },
   "UserName" : "${userName}"
}

${userName} looks like a variable template that can be swapped by docker/k8s etc, but how does it work, because inside the application, I still access UserName as:

var userName = _configuration["UserName"];  // output is "${userName}"

so does docker change the variable template? Does it update the appsetting.json file directly, for example, docker will use ENV's value in the dockerfile to scan the appsetting.json file and swap ${userName} with actual value?

CodePudding user response:

This looks like an interpolated string stored against the "UserName" key in the appsettings.json.

You would be relying on the code (C#, etc) to substitute the username value at runtime rather than this having anything to do with a container runtime.

When instantiating a container via various alternatives (Docker, Docker Compose, Kubernetes, etc) you would pass in environment variables when the container (pods in the case of K8s) when container(s) are created.

How this (injection of environment variables) is done depends on how you spin up your container. The idea is the same but syntax may vary depending on whether you are using "docker run", or "docker compose" or "kubernetes", etc. But the principal is the same.

In the case of a .NET Core container you would then be relying on an "order of precedence" to derive the values for the ConfigurationManager, e.g. https://devblogs.microsoft.com/premier-developer/order-of-precedence-when-configuring-asp-net-core/

Containers wouldn't modify/inject/swap the underlying codebase in the deployed container.

However, they could inject environment variables into the container/pod when instantiating.

Not sure if I've interpreted your question correctly.

  • Related