Skip to main content

Lambda Function with Amazon DynamoDB

DynamoDB can trigger AWS Lambda when the data in added to the tables, updated or deleted. In this chapter, we will work on a simple example that will add items to the DynamoDB table and AWS Lambda which will read the data and send mail with the data added.

Requisites

To use Amazon DB and AWS Lambda, we need to follow the steps as shown below −

  • Create a table in DynamoDB with primary key
  • Create a role which will have permission to work with DynamoDBand AWS Lambda.
  • Create function in AWS Lambda
  • AWS Lambda Trigger to send mail
  • Add data in DynamoDB

Let us discuss each of this step in detail.

Example

We are going to work out on following example which shows the basic interaction between DynamoDB and AWS Lambda. This example will help you to understand the following operations −

  • Creating a table called customer in Dynamodb table and how to enter data in that table.
  • Triggering AWS Lambda function once the data is entered and sending mail using Amazon SES service.

The basic block diagram that explains the flow of the example is as shown below −

Block Diagram
Create Table in DynamoDB with Primary Key

Log in to AWS console. Go to AWS Services and select DynamoDB as shown below. Select DynamoDB.

Dynamodb

DynamoDB shows the options as shown below −

Dynamodb Option

Now, click Create table to create the table as shown. We have named the table as customer with primary key for that table as cust_id. Click on Create button to add the table to dynamodb.

Create Dynamodb

The table created is as shown below −

Table Details

We can add items to the table created as follows −

Recent Alerts

Click Items and click Create item button as shown −

Create Item

Create Item2

Creating Role with Permissions to Work with DynamoDB and AWS Lambda

To create role, Go to AWS services and click IAM.

Creating Role

Let us create a policy to be used only for the DynamoDB table created earlier −

Create Policy Dynamo

Now, choose a Service. Observe that the service we have selected is DynamoDB. For Actions we have taken all Dynamodb actions ie access to list, read and write. For resources, we will select the table resource type actions. When you click it, you can see a screen as follows −

Dynamodb Action

Now, select table and Add ARN to it as shown. We will get ARN details from customer table created as shown below −

Table Created

Enter arn details here −

Specify Arn

Click Add button to save the changes. Once done Click on Review policy. Enter the name of the policy, description etc as shown below −

Add Button

Click on create policy to save it. Add the policy to the role to be created. Select Role from left side and enter the details.

Create Role

Observe that the policies added are newpolicyfordynamdb, awslambdafullaccess, cloudwatchfullaccess and amazonsesfullaccess. Add the role and will use it while creating AWS Lambda function.

Create Function in AWS Lambda

Thus, we have created Lambda function called newlambdafordynamodb as shown.

New Lambda

Now, let us add DynamodDB trigger to the AWS Lambda created. The runtime we shall use is Node.js.

Designer Trigger

You can find the following details in Dynamodb trigger that are to be configured for AWS Lambda −

Dynamo Trigger

Now, simply click Add to add the trigger to AWS Lambda.

AWS Lambda Trigger to Send Mail

AWS Lambda will get triggered when data is inserted intoAWS Lambda. The event parameter will have the dynamodb data inserted. This will read the data from the event and send email.

Sending an email

To send email, you need to follow the steps given below −

Step 1

Go to AWS service and select SES (simple email service). Validate the email to which we need to send an email as shown −

Verify EmailStep 2

Click the button Verify a New Email Address to add the email address.

Verify a New Email
Step 3

Enter an email address to verify it. The email address will receive and activation mail from Amazon which needs to be clicked. Once the activation is done, the email id is verified and can be used with AWS services.

Step 4

The AWS Lambda code which reads data from the event and sends email is given below −

var aws = require('aws-sdk');
var ses = new aws.SES({
region
: 'us-east-1'
});
exports
.handler = function(event, context, callback) {
console
.log(event);
let tabledetails = JSON.parse(JSON.stringify(event.Records[0].dynamodb));
console
.log(tabledetails.NewImage.address.S);
let customerid = tabledetails.NewImage.cust_id.S;
let name = tabledetails.NewImage.name.S;
let address = tabledetails.NewImage.address.S;

var eParams = {
Destination: {
ToAddresses: ["xxxxx@gmail.com"]
},
Message: {
Body: {
Text: {
Data: "The data added is as follows:\n CustomerId:"+customerid+"\n Name:"+name+"\nAddress:"+address
}
},
Subject: {
Data: "Data Inserted in Dynamodb table customer"
}
},
Source: "xxxxx@gmail.com"
};
console
.log('===SENDING EMAIL===');
var email = ses.sendEmail(eParams, function(err, data) {
if (err) console.log(err);
else {
console
.log("===EMAIL SENT===");
console
.log("EMAIL CODE END");
console
.log('EMAIL: ', email);
context
.succeed(event);
callback
(null, "email is send");
}
});
}

Now, save the Lambda function and data in DynamoDB table.

Add Data in DynamoDB

Use the following sequence to add data in DynamoDB.

Step 1

Go to the table customer created in Dynamodb.

Customer Created
Step 2

Click Create item.

Create Item Dynamo
Step 3

Click Save button and check the email id provided in AWS Lambda to see if the mail has been sent by AWS Lambda.

Gmail

 

Comments

Popular posts from this blog

C++ How to use Date and Time

The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program. There are four time-related types: clock_t, time_t, size_t , and tm . The types clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer. The structure type tm holds the date and time in the form of a C structure having the following elements: struct tm { int tm_sec ; // seconds of minutes from 0 to 61 int tm_min ; // minutes of hour from 0 to 59 int tm_hour ; // hours of day from 0 to 24 int tm_mday ; // day of month from 1 to 31 int tm_mon ; // month of year from 0 to 11 int tm_year ; // year since 1900 int tm_wday ; // days since sunday int tm_yday ; // days since January 1st int tm_isdst ; // hours of daylight savin...

C++ References

A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable. C++ References vs Pointers: References are often confused with pointers but three major differences between references and pointers are: You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage. Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time. A reference must be initialized when it is created. Pointers can be initialized at any time. Creating References in C++: Think of a variable name as a label attached to the variable's location in memory. You can then think of a reference as a second label attached to that memory location. Therefore, you can access the contents of the variabl...

Lambda Function with Amazon SNS

  Amazon SNS is a service used for push notification. In this chapter, we will explain working of AWS Lambda and Amazon SNS with the help of an example where will perform the following actions − Create Topic in SNS Service and use AWS Lambda Add Topics to CloudWatch Send SNS text message on phone number given. Requisites To create Topic in SNS Service and use AWS Lambda Add Topics to CloudWatch, we need not follow the steps given below − Create Topic in SNS Create Role for permission in IAM Create AWS Lambda Function Publish to topic to activate trigger Check the message details in CloudWatch service. To send SNS text message on phone number given, we need to do the following − Add code in AWS Lambda to send message to your phone. Example In this example, we will create a topic in SNS. When details are entered in the topic to publish, AWS Lambda is triggered. The topic details are logged in CloudWatch and a message is sent on phone by AWS Lambda. Here is a basic block diagram which...