2

I am using AWS Systems Manager Parameter Store to hold database connection strings which are used to dynamically build a DbContext in my .NET Core Application

I am using the .NET Core AWS configuration provider (from https://aws.amazon.com/blogs/developer/net-core-configuration-provider-for-aws-systems-manager/) which injects my parameters into the IConfiguration at runtime.

At the moment I am having to keep my AWS access key/secret in code so it can be accessed by the ConfigurationBuilder but would like to move this out of the code base and stored it in appsettings or similar.

Here is my method to create the webhost builder called at startup

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
    var webHost = WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

    AWSCredentials credentials = new BasicAWSCredentials("xxxx", "xxxx");

    AWSOptions options = new AWSOptions()
    {
        Credentials = credentials,
        Region = Amazon.RegionEndpoint.USEast2
    };

    webHost.ConfigureAppConfiguration(config =>
    {
        config.AddJsonFile("appsettings.json");
        config.AddSystemsManager("/ParameterPath", options, reloadAfter: new System.TimeSpan(0, 1, 0)); // Reload every minute
    });

 return webHost;
}

I need to be able to inject the BasicAWSCredentials parameter from somewhere.

pr.lwd
  • 140
  • 10

1 Answers1

1

You need to access an already built configuration to be able to retrieve the information you seek.

Consider building one to retrieve the needed credentials

public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
    var webHost = WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>();

    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    var access_key = configuration.GetValue<string>("access_key:path_here");
    var secret_key = configuration.GetValue<string>("secret_key:path_here");

    AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);

    AWSOptions options = new AWSOptions() {
        Credentials = credentials,
        Region = Amazon.RegionEndpoint.USEast2
    };

    webHost.ConfigureAppConfiguration(config => {
        config.AddJsonFile("appsettings.json");
        config.AddSystemsManager("/ParameterPath", options, reloadAfter: new System.TimeSpan(0, 1, 0)); // Reload every minute
    });

    return webHost;
}

I would also suggest reviewing Configuring AWS Credentials from the docs to use the SDK to find a possible alternative way to storing and retrieving the credentials.

Nkosi
  • 235,767
  • 35
  • 427
  • 472