简体   繁体   中英

How to access DynamoDB from AWS Lambda when using the Serverless Framework?

I'm using the Serverless Framework to manage my AWS Lambda deploys. The framework credentials has access to DynamoDB resources, but my Lambda, deployed with the framework, can't access my DynamoDB tables.

How can I give my Lambda functions the proper access?

EDIT : updated the answer for Serverless Framework 1.x.

The solution is to set the iamRoleStatements to allow Lambda to access the DynamoDB resources. Note: the credentials used by the Serverless Framework must have permission to the same DynamoDB resources.

  1. add the iamRoleStatements in your serverless.yml :

     provider: name: aws runtime: nodejs4.3 stage: dev region: us-east-1 iamRoleStatements: - Effect: "Allow" Action: - "dynamodb:*" Resource: "arn:aws:dynamodb:${self:provider.region}:*:table/*" 
  2. deploy the changes:

     > serverless deploy 

To give permissions in a function level (instead of allowing all functions to access DynamoDB), see my other answer here .

While I'm not familiar with the way Serverless works, what you are looking for is an IAM Role .

You can assign a role to an EC2 instances or AWS Lambda functions so that code that you write that uses the AWS SDK will automatically be able to retrieve AWS credentials with the permissions associated with that role. For AWS Lambda and your use case you will want to grant the role you assign AWS Lambda access to the DynamoDB tables it requires to run.

This can be deceivingly simple to use, you simply do not provide credentials and it just works (as long as the role has the correct permissions)! The AWS SDK takes care of everything for you by automatically retrieving credentials that are associated with the Role.

From the link you provided the specific question that references this under the best practice is Credentials from IAM Roles for EC2 Instances where it refers to EC2 instances, but this also applies to AWS Lambda.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM