AllocZero / EfficientDynamoDb

High-performance C# DynamoDb library
https://alloczero.github.io/EfficientDynamoDb/
MIT License
204 stars 19 forks source link

How to use configure to use Execution Role? #214

Closed baynezy closed 1 year ago

baynezy commented 1 year ago

When I use the AWS SDK I authenticate with the Execution Role attached to my Lambda function. This doesn't require me to add anything specific to my .Net code as the SDK utilises this without any prompt.

I am hoping to do the same with EfficientDynamoDB. However, I am struggling to work out how to do that.

DynamoDbContextConfig requires an IAwsCredentialsProvider which gets from the AWSCredentialsExtensions.ToCredentialsProvider extension method which extends AWSCredentials. I have looked at all the sub-classes of AWSCredentials I can find. However, none of them seem to be suitable.

Can anyone point me in the right direction??

firenero commented 1 year ago

Hi @baynezy,

I assume that with AWS SDK you create your context somewhat similar to this: var context = new DynamoDBContext(new AmazonDynamoDBClient());, i.e. relying on automatic credentials resolution.

It seems that Lambda sets the environment variables with credentials when you attach the Execution Role. And the SDK itself loops through different credential providers until it finds the correct one.

I can't check it will Lambda at the moment but it seems like either AssumeRoleWithWebIdentityCredentials.FromEnvironmentVariables().ToCredentialsProvider() or new EnvironmentVariablesAWSCredentials().ToCredentialsProvider() is what you need. Then you can pass the credentials provider into DynamoDbContextConfig.

Could you test it and let me know which provider works for you?

I think we can add a similar FallbackCredentialsFactory in the future to simplify credentials handling but I can't commit to any timeline at this point.

baynezy commented 1 year ago

@firenero - thanks for your help. I worked it out in the end.

var credentials = FallbackCredentialsFactory.GetCredentials();
var config = new DynamoDbContextConfig(RegionEndpoint.EUWest2, credentials.ToCredentialsProvider());
_context = new DynamoDbContext(config);