AWS Lambda Dynamodb Trigger
Hello Everyone
Welcome to CloudAffaire and this is Debjeet.
In the last blog post, we have learned how to execute a lambda function from the AWS console.
https://cloudaffaire.com/invoke-lambda-from-aws-console/
So far in this series, we have used push events as lambda trigger (For example S3). Lambda also supports pull events as lambda trigger. AWS DynamoDB is one such event source where lambda pulls the event from DynamoDB, instead of later pushing the events to lambda. In this blog post, we are going to configure DynamoDB as lambda trigger.
Prerequisite for this demo:
Proper IAM role for lambda:
DynamoDB with stream enabled:
You can create the dynamodb table with stream enabled using below AWS CLI
1 2 3 4 5 6 7 |
aws dynamodb create-table \ --table-name CloudAffaire \ --attribute-definitions AttributeName=id,AttributeType=N AttributeName=ename,AttributeType=S \ --key-schema AttributeName=id,KeyType=HASH AttributeName=ename,KeyType=RANGE \ --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 \ --region ap-south-1 \ --output table |
1 2 3 4 5 6 |
aws dynamodb update-table \ --table-name CloudAffaire \ --attribute-definitions AttributeName=id,AttributeType=N AttributeName=ename,AttributeType=S \ --stream-specification StreamEnabled=TRUE,StreamViewType=NEW_AND_OLD_IMAGES \ --region ap-south-1 \ --output table |
Next, we are going to create the lambda function with DynamoDB as a trigger.
AWS Lambda Dynamodb Trigger
Step 1: Login to AWS console and navigate to ‘Lambda’.
Step 2: Click on ‘Create a function’.
Step 3: Provide function name, runtime and IAM role and click ‘Create Function’.
Step 4: In the function code section, paste below python code.
1 2 3 4 5 6 7 |
from __future__ import print_function def lambda_handler(event, context): for record in event['Records']: print(record['eventID']) print(record['eventName']) print('Successfully processed %s records.' % str(len(event['Records']))) |
Step 5: Click ‘DynamoDB’ as function trigger.
Observed: Trigger configuration is auto-populated with DynamoDB table, click ‘ADD’ and finally click ‘Save’.
Step 6: Iinsert some data in the DynamoDB table for event generation.
1 2 3 4 |
aws dynamodb put-item \ --table-name CloudAffaire \ --item '{"id":{"N":"100"},"ename":{"S":"Debjeet"}}' \ --region ap-south-1 |
Step 7: Check the CloudWatch Logs.
Hope you have enjoyed this blog post and with this, we are concluding our introductory series in AWS Lambda. In the next blog post, we will start with a new AWS service.
To get more details on Lambda, please refer below AWS documentation
https://docs.aws.amazon.com/lambda/index.html
Is there any way in which I can trigger lambda only when a existing record in a dynamodb table is modified. The lambda should not be triggered on insert and delete.