Read the database connection string and other secrets from environment variables

It is not good practice to store secrets in the source code repository. The sample C# dotnet core application code stores the database connection string in the appsettings.json file which eventually will be pushed into GitHub. To follow the Twelve-Factor App methodology, store the configuration values in environment variables and load them runtime. This method enables your application to run in a Docker container and in a Kubernetes pod.

If the connection string is not specified, we get the error message

System.ArgumentNullException: ‘Value cannot be null.
Parameter name: connectionString’

To read the connection string from an environment variable

Add the builders to the Startup.cs file

       public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
            Env = env;

            // Read the connection string from the "ASPNETCORE_ConnectionStrings:DefaultConnection" environment variable
            // RESTART Visual Studio if you add or edit environment variables for the change to take effect.
            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 for the environment variables to have the highest priority
            builder.AddEnvironmentVariables("ASPNETCORE_");
            Configuration = builder.Build();
        }

Create the ASPNETCORE_ConnectionStrings__DefaultConnection environment variable. The double underscore will be converted to a colon ( : ) . This variable name works on Windows, and also in Linux where the environment variable name cannot contain colons.

Server=MY_SERVER_URL;Port=5432;Database=MY_DATABASE;Username=MY_USER;Password=MY_PASSWORD

IMPORTANT: If you add or change an environment variable, restart Visual Studio for the change to take effect. It is not enough to restart the application.

Leave a comment

Leave a Reply