Search code examples
aws-sdk-net

AWS SDK Configuration with Environmental Variables & Dependency Injection .NET Core


I am having trouble getting the AWS Setup Extension to process environment variables.

Following instructions on the AWS Docs + Unofficial Docs.

In my StartUp file, I add the following config and services.

 services.AddDefaultAWSOptions(root.GetAWSOptions());
 services.AddAWSService<IAmazonDynamoDB>();

My configuration includes a JSON file with AWS settings and also environmental variables.

    public static IConfigurationRoot Configuration  => new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables()
    .Build();

According to the following diagram and the Unofficial Docs. AWS Setup should attempt to configure credentials from environmental variables failing higher priority options.

enter image description here

However, I have found it is able to import an AWS profile but not the environmental variables.

I've been investigating in the following repo under the console app if anyone cared to reproduce. https://github.com/aws/aws-sdk-net/issues/1717


Solution

  • I have resorted to the following workaround. It's fine but it would be good to know if the documentation is incorrect for .NET Core or if I@m doing something wrong.

                services.AddSingleton<IAmazonDynamoDB>(sp =>
                {
                    var clientConfig = root.GetAWSOptions();
                    var credentials = new BasicAWSCredentials(
                        System.Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID"),
                        System.Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY")); // default credentials no need real one                    
                    return new AmazonDynamoDBClient(credentials, clientConfig.Region );
                });