AWS Lambda Dynamodb Trigger

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:

AWS Lambda Dynamodb Trigger

DynamoDB with stream enabled:

AWS Lambda Dynamodb Trigger

You can create the dynamodb table with stream enabled using below AWS CLI

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
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’.

AWS Lambda Dynamodb Trigger

Step 2: Click on ‘Create a function’.

AWS Lambda Dynamodb Trigger

Step 3: Provide function name, runtime and IAM role and click ‘Create Function’.

AWS Lambda Dynamodb Trigger

Step 4: In the function code section, paste below python code.

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'])))

AWS Lambda Dynamodb Trigger

Step 5: Click ‘DynamoDB’ as function trigger.

AWS Lambda Dynamodb Trigger

Observed: Trigger configuration is auto-populated with DynamoDB table, click ‘ADD’ and finally click ‘Save’.

AWS Lambda Dynamodb Trigger

Step 6: Iinsert some data in the DynamoDB table for event generation.

aws dynamodb put-item \
--table-name CloudAffaire \
--item '{"id":{"N":"100"},"ename":{"S":"Debjeet"}}' \
--region ap-south-1

Step 7: Check the CloudWatch Logs.

AWS Lambda Dynamodb Trigger

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

 

Leave a Reply

Close Menu