How to load secrets in linux container usiing AddKeyPerFile

Viewed 1265

I have asp net core project which I am deploying inside linux containers in kubernetes cluster. My secrets are mounted in /secrets folder in the container and I found https://github.com/aspnet/Configuration/tree/master/src/Config.KeyPerFile and tried to use builder.AddKeyPerFile("/secrets", false); to load the secrets. But it does not work. configuration["File1"] returns empty where File1 is a file inside "/secrets" folder which contains one of the secrets.

When I execute the below in the service code, I am able to read the secrets.

List<KeyValuePair<string, string>> secrets =
    new List<KeyValuePair<string, string>>();

foreach (var secretFile in Directory.GetFiles("/secrets", "*.*", System.IO.SearchOption.AllDirectories))
{
    secrets.Add(
        new KeyValuePair<string, string>(
        Path.GetFileName(secretFile), File.ReadAllText(secretFile)));
}

I am trying to find out how to use builder.AddKeyPerFile extension method for this.

2 Answers

I'm using with .Net Core 3.1 and it works.

new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile("appsettings.Development.json", optional: true)
    .AddKeyPerFile("/secret/", optional: true)
    .Build();

So I could access the stored secret as:

var file1 = configuration["File1"];

I haven't tried with older version of .Net Core but definitely works with 3.1. Only thing I was running into that the path needs to be absolute.

If you are using one of the following packages with version 3.1.25

  • Microsoft.Extensions.Configuration.Binder
  • Microsoft.Extensions.Configuration.Json
  • Microsoft.Extensions.Configuration.UserSecrets
  • Microsoft.Extensions.Configuration.EnvironmentVariables
  • Microsoft.Extensions.Configuration.KeyPerFile
  • Microsoft.Extensions.Options.ConfigurationExtensions
  • Microsoft.Extensions.Options

please downgrade them, because there is something wrong with them when you are reading secrets from files. I tried 3.1.16 and it works fine. I did report the situation here on GitHub.

Related