Setting keys in appsettings.json with ENV variables - ASP.NET Core 3.1 Docker

Viewed 8969

I have a .NET Core Web API and I am trying to find out how to use ENV variables to configure keys in my appsetttings.json so I can then populate with data when creating a Docker container.

So far I have managed to inject IOptions<> into my test controller and I was able to debug the values, which were NULL because the app is currently not running in a container just yet.

Test controller:

namespace TestWebApplication.Controllers
{
    [ApiController]
    [Route("api/")]
    public class TestController : ControllerBase
    {
        private readonly IOptions<EnvironmentConfiguration> _environmentConfiguration;

        public TestController(IOptions<EnvironmentConfiguration> environmentConfiguration)
        {
            _environmentConfiguration = environmentConfiguration;
        }

        [HttpGet]
        [Route("testmessage")]
        public ActionResult<string> TestMessage()
        {
            var test = _environmentConfiguration.Value;

            return Ok($"Value from EXAMPLE_1 is {test.EXAMPLE_1}");
        }
    }
}

Environment configuration:

namespace TestWebApplication.Models
{
    public class EnvironmentConfiguration
    {
        public string EXAMPLE_1 { get; set; }
        public string EXAMPLE_2 { get; set; }
     }
}

After following some older tutorials I noticed I actually never needed to put any code in ConfigureServices for this to work.

For example, lets say I have this part of my appsettings.json:

"eureka": {
    "client": {
      ......
    },
    "instance": {
      "port": "xxxx",
      "ipAddress": "SET THIS WITH ENV",
    }
  }

How could I set an environment variable to populate the ipAddress so when I go to Docker, I run something like this:

docker run .... -e EXAMPLE_1 -e IP_ADDRESS ....

1 Answers

For instance you have a section in appsettings.json:

{
    "Section1" : {
        "SectionA": {
            "PropA": "A",
            "PropB": "B"
        }
    }
}

and a class:

public class SectionA
{
    public string PropA { get; set; }
    public string PropB { get; set; }
}

In Startup.cs map class to section to be able to inject IOptions<SectionA>:

services.Configure<SectionA>(Configuration.GetSection("Section1:SectionA"));

Then you can override properties of SectionA using this naming convention for environment variables: Section1__SectionA__PropA.

Also read this https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#keys

Related