A NodeJS Lambda Function

We'll create the function using the CLI.

This allows us to add the code and set an IAM role all in one go, so we'll actually code it up first, and then create the function (uploading the code at the same time).

We start with vanilla Javascript - no npm or modules used.

IAM Role

First, let's update the Policy attached to the IAM Role created by the web UI when we created the Golang function. This way we can re-use it, instead of having to create a new Role and Policy each time.

1 {
2 "Version": "2012-10-17",
3 "Statement": [
4 {
5 "Effect": "Allow",
6 "Action": "logs:CreateLogGroup",
7 "Resource": "arn:aws:logs:us-east-2:601364042938:*"
8 },
9 {
10 "Effect": "Allow",
11 "Action": [
12 "logs:CreateLogStream",
13 "logs:PutLogEvents"
14 ],
15 "Resource": [
16- "arn:aws:logs:us-east-2:601364042938:log-group:/aws/lambda/foo_func_go:*"
17+ "arn:aws:logs:us-east-2:601364042938:log-group:/aws/lambda/foo_func*:*"
18 ]
19 }
20 ]
21 }

We made this so it would work for all the functions we'll create in this module, which are named foo_func_<something>.

The Function

Let's create a directory to work in for this function:

1mkdir foo_func_nodejs
2cd foo_func_nodejs

Then we create a super basic function in index.js:

1exports.handler = async function(event, context) {
2 console.log("EVENT:
3" + JSON.stringify(event, null, 2))
4 return context.logStreamName
5}

Then we can package this up and create the function!

1zip index.zip index.js
2 
3# https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/create-function.html
4aws --profile cloudcasts lambda create-function \
5 --function-name foo_func_nodejs \
6 --role arn:aws:iam::601364042938:role/service-role/foo_func_go-role-h6pfawno \
7 --runtime nodejs14.x \
8 --handler index.handler \
9 --memory-size 512 \
10 --zip-file fileb://index.zip

Note the --handler is the filename and name of the exported variable index.handler.

Then we can invoke it!

1aws --profile cloudcasts lambda invoke \
2 --function-name foo_func_nodejs \
3 --invocation-type RequestResponse \
4 --cli-binary-format raw-in-base64-out \
5 --payload '{"name": "Chris", "message": "People like you!"}' \
6 output.json
7 
8cat output.json
9# Some CloudWatch log stream name
10# We check the CloudWatch logs to see the console.log() output

Don't miss out

Sign up to learn when new content is released! Courses are in production now.