Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 372
Zanon Avatar asked Feb 07 '16 11:02

Zanon


2 Answers

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.

like image 138
Zanon Avatar answered Oct 29 '22 16:10

Zanon


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.

like image 41
JaredHatfield Avatar answered Oct 29 '22 15:10

JaredHatfield