AWS Lambda allows you to write code without having to worry about provisioning and maintaining servers. You simply create an Lambda function, upload your code and it’s run whenever the relevant event is triggered. DynamoDB is a NoSql Database Amazon provide for easy integration with your Cloud solution. DynamoDB spreads data and traffic over a number of servers so you don’t have to worry about how your tables scale. Both these tools have great potential and for the most part they are fairly accessible, but what if you want to combine them as part of a larger application or service?
This tutorial covers the creation of a very simple Lambda which inserts data in to a DynamoDB table. The example code is available here.
An AWS account that can deploy AWS Lambdas and DynamoDB tables.
You will need an IAM Role that can deploy AWS Lambdas as well as put files in to DynamoDB instances. IAM Roles allow the various tools to run as a user with a specific set of permissions or policies as they are referred to. To create the role needed;
- Go to Services > Security > IAM.
- Click on “Roles”.
- Click on “Create New Role”.
- Give your role a name.
- From “AWS Service Roles” select “AWS Lambda”.
- Use the filter to find and the policies for DynamoDB and AWS Lambda. AWSLambdaBasicExecution and AmazonDynamoDBFullAccess would suffice but they aren’t the most secure options.
- Review and create the role.
- Go to Services > Storage & Content Delivery > DynamoDB.
- Click “Create Table”.
- Name your table.
- Name the primary key “id”.
- Make sure “Use default settings” is enabled.
This is where you can create your AWS Lambda function, take some time to have a tinker with the UI as Amazon have definitely put effort in to making it accessible. The option to change the color scheme for the inline code editor is very nice!
- Go to Services > Compute > Lambda.
- Click “Create a Lambda function”.
- Click “Configure function”.
- Name the function.
- Add a description for the function.
- Select “Node.js 4.3” as the runtime.
- Under “Lambda function code” select “Edit code inline” as the “Code entry type” and paste in the example from this repository.
- Under “Lambda function handler and role” select the role created previously.
- Review and create your function.
The last step is to test your Lambda, handily AWS provides a number of ways you can feed data to your Lambda and trigger it, all without having to manually make the events occur.
- With your Lambda selected click on “Actions” and select “Configure test event”.
- For this example the “Hello World” template is used.
- Save the changes and test your Lambda! If you go to the DynamoDB table you created you will see the entries should have been added!
…and that’s all there is to it! Amazon have clearly gone to great effort to make this as accessible as possible and the potential is very interesting. In the future I intend on looking at Amazon API Gateway, to see if I can put an API in front of my Lambda function!