Functions with Dependencies

We're going to update our NodeJS function to talk to the S3 API and list the files within a bucket.

To do that, we need to:

  1. Update the functions IAM permissions (we've been editing its Execution Role) to allow this
  2. Pull in an NPM package to get the S3 Client and list the contents of the bucket
  3. Update the lambda function to include the function AND its dependencies

IAM Permissions

Let's once again update the Role's Policy to include the required S3 permissions:

1{
2 "Version": "2012-10-17",
3 "Statement": [
4 {
5 "Sid": "VisualEditor0",
6 "Effect": "Allow",
7 "Action": "logs:CreateLogGroup",
8 "Resource": "arn:aws:logs:us-east-2:601364042938:*"
9 },
10 {
11 "Sid": "VisualEditor1",
12 "Effect": "Allow",
13 "Action": [
14 "logs:CreateLogStream",
15 "logs:PutLogEvents"
16 ],
17 "Resource": "arn:aws:logs:us-east-2:601364042938:log-group:/aws/lambda/foo_func*:*"
18 },
19 {
20 "Sid": "VisualEditor2",
21 "Effect": "Allow",
22 "Action": [
23 "s3:GetObject",
24 "s3:ListBucket"
25 ],
26 "Resource": [
27 "arn:aws:s3:::cloudcasts-artifacts/*",
28 "arn:aws:s3:::cloudcasts-artifacts"
29 ]
30 }
31 ]
32}

Update the Code

We then can update the NodeJS function with the S3 Client library, and call the needed commands.

Grab the AWS SDK for S3, resulting in package.json, package-lock.json, and the node_modules directory.

1npm install @aws-sdk/client-s3

Then we update the function:

1const { S3Client, ListObjectsCommand } = require("@aws-sdk/client-s3")
2 
3const s3Client = new S3Client({
4 region: 'us-east-2',
5 version: 'latest',
6});
7 
8const Bucket = 'cloudcasts-artifacts'
9 
10exports.handler = async function(event, context) {
11 
12 const response = await s3Client.send(new ListObjectsCommand({
13 Bucket: Bucket
14 }))
15 
16 console.log(response)
17 
18 return context.logStreamName
19}

Now we have a node_modules directory to package up along with the function.

1# From within the foo_func_nodejs directory
2rm index.zip
3 
4zip -r9 index.zip .
5 
6aws --profile cloudcasts lambda update-function-code \
7 --function-name foo_func_nodejs \
8 --zip-file fileb://index.zip \
9 --publish
10 
11aws --profile cloudcasts lambda invoke \
12 --function-name foo_func_nodejs \
13 --invocation-type RequestResponse \
14 output.json
15 
16# Confirm output
17cat output.json

We then check the CloudWatch logs to confirm is logged out the response we expect.

Uploading the code base was kind of slow! The next video shows how to improve that.

Don't miss out

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