Kirill Zonov

Building an Amazon Lambda function to write to the DynamoDB

December 16, 2017 | 5 Minute Read

In this post, we will create a Lambda function which can write to the Amazon DynamoDB table. For this, we will create a table, modify existing function and set up IAM roles. Log in to your AWS account and let’s get started! In the previous post I gave you an introduction to the Amazon DynamoDB, now it’s time to try it out by yourselves. To make it we will use a Greeter Lambda function from this post. So please make sure that the configuration from that post works for you and then proceed with this lesson. First, let’s go to the Amazon DynamoDB page in the AWS Console. Then create a new table there. I will name it “kzonovGreetedVisitors”. create amazon dynamodb table

That’s it for now for the DynamoDB configuration. We just keep everything to be a default, it’s suitable for most of the basic use cases. As you may see, I added one partition key, which is Name for me. It’s intentionally not an auto-generated field, because our Name will be unique. You can go to the Items tab, to make sure that your table is empty.

Now let’s open our previously created (if you don’t have it - follow my Lambda introduction post) and slightly modify the code.

const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
exports.handler = (event, context, callback) => {
    dynamodb.putItem({
        TableName: "kzonovGreetedVisitors",
        Item: {
            "name": {
                S: event.queryStringParameters["name"]
            }
        }
    }, function(err, data) {
        if (err) {
            console.log(err, err.stack);
            callback(null, {
                statusCode: '500',
                body: err
            });
        } else {
            callback(null, {
                statusCode: '200',
                body: 'Hello ' + event.queryStringParameters["name"] + '!'
            });
        }
    })
};

Let me explain to you what do we do here. First, we require the AWS Nodejs SDK, then don’t be confused by the API version, how my colleague said, “they just implemented so great API, so no need to change it for five years now” :) In the handler function, we invoke putItem, which accepts two params: the action object and the callback. The object should be clear for you, just one key may be confusing is the S. It means that the thing you put into the table has a String type. So if it would be a boolean, you would specify B, f.e. Callback function also should be graspable, if you read my Lambda introduction post, which I already mentioned. But now your function won’t work because it doesn’t have sufficient permissions. To give it - scroll down and find the “Execution role” block. In it, you will see your function role, remember it.

Go to Services (on the top) -> IAM -> Roles (will appear in the left column). Then search for your role name and you will get smth like this:

Then open your role and you will see a link at the bottom “Add inline policy”, click on it. IAM Role main page

There you will have already selected Policy generator, click on Select there.

In order to fill in the ARN field, you need to open your DynamoDB config in the separate tab. Copy the ARN from there and paste it here. ARN for DynamoDB

As a rule of thumb, your policies work on to deny all. So you should manually specify, which actions do you want to allow. Here I suggest you add allowance only to one action, PutItem. Don’t select all, because it will mean that your function will have too broad permissions. After filling all fields as on the image above, press Add Statement. After that Next Step and you will see smth like that:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1513430700000",
            "Effect": "Allow",
            "Action": [
                "dynamodb:PutItem"
            ],
            "Resource": [
                "arn:aws:dynamodb:eu-west-1:123123123123::table/kzonovGreetedVisitors"
            ]
        }
    ]
}

After clicking on the Add policy you will return to the Role page and you’ll have a new policy attached there. Now your Lambda function should be able to put a line into your table. If you followed my previous lesson, now you can go to the API Gateway to test it.

test it with ApiGateway

Click test, in the new window enter Query strings, so it can greet you by name :) After that click Test and hopefully, you’ll get smth like this:

It means that at least you received 200 ok and your body is correct. Now let’s go to your table in the DynamoDB and make sure that the next item had been added. Yay!!!

New record in DynamoDB

Thank you for reading and see you on the third lesson, where we will add a trigger for our DynamoDB table!