DynamoDB 101 — Connect to DynamoDB in Lambda function
Connecting to DynamoDB from Lambda is even easier than you can think of.
Firstly, you need to create an execution role which later you can attach to the lambda function. To do so:
- Login IAM, select Roles under Access management in the left sidebar, click on the Create role button.
- In the Select type of trusted entity section, select AWS service and select Lambda in the Choose a use case section.
3. Select a policy/policies you want to attach to this role, you can also create a customized policy to restrict the access permission other than granting write/read permission on all tables. If you don’t know how to create a customized policy, check out this tutorial. You have to at least grant GetItem read permission on the table(s) you want access in Lambda.
4. After adding permissions, click on Next: Tags button.
5. Add any number of descriptive key value tag pairs as you want, click on Next: Review button.
6. In the review page, supply a name for this role and possibly role description if you want, then click on Create role button.
Secondly, create a lambda function. To do so:
- click on Create function button.
- Supply a name for this new function in the basic information section.
- Click on Choose or create an execution role in the permission section, then click on Use an existing role ratio button and select the policy created earlier, click on Create function button.
Lastly, let’s connect to DynamoDB in this Lambda function. In the index.js file:
And that’s it! Interestingly enough you don’t even have to add a package.json to include aws-sdk dependency. You also don’t have to use AWS.config.update() method to specify access key and secret key since you have granted permission to access DynamoDB to this Lambda function.