Home > database >  Override appsettings.json Array With Env Variable
Override appsettings.json Array With Env Variable

Time:03-29

I have this array in my appsettings.json:

  "ServiceDefinitions": [
    {
      "Name": "encryption-api",
      "Url": "http://localhost:5032",
      "ApiKey": "",
      "ExposedEndpoints": [
        "encrypt",
        "decrypt"
      ]
    }
  ],

I want to be able to override this with an environment variable. I've added the env vars to the configuration builder like this, which seems to work for other values:

builder.Configuration.AddEnvironmentVariables();

And then I've attempted to set this in my Docker Compose file with:

environment:
      - ASPNETCORE_URLS=http://gateway:8080/
      - ServiceDefinitions="{\"Name\":\"encryption-api\",\"Url\":\"http://encryption-api:80\",\"ApiKey\":\"\",\"ExposedEndpoints\":[\"encrypt\",\"decrypt\"]}"

However, it's still picking up the value from the json file rather than the env var. I've also tried setting it inside [] but that makes no difference.

How can I do this?

CodePudding user response:

Microsoft docs regarding app configuration.

You are going to want to make sure that your Json provider is registered before your environment variables provider. Then you'll want to setup your environment variables in your Docker file as follows:

environment:
      - ASPNETCORE_URLS=http://gateway:8080/
      - ServiceDefinitions__Name="encryption-api"
      - ServiceDefinitions__Url="http://encryption-api:80"
      - ServiceDefinitions__ApiKey=""
      - ServiceDefinitions__ExposedEndpoints__0="encrypt"
      - ServiceDefinitions__ExposedEndpoints__1="decrypt"

CodePudding user response:

We can override the environment variables set in the Docker file when running the image by using the -e flag:

Docker run -e "ServiceDefinitions=encryption-api" myimage

Official doc: ASP.NET Core and Docker Environment Variables

  • Related