Lambda Layers

Updating the function was kind of slow! We can use Layers to help there.

Layers are just a .zip archive of extra STUFF (files) you can have Lambda add to your function automatically. This lets you keep the function itself smaller, and faster to update.

They require a certain directory structure, based on the runtime.

For example, for a NodeJS runtime, it needs files to be in a nodejs directory:

1# We need a certain directory structure...
2mkdir -p layer/nodejs
3cp -r node_modules package* layer/nodejs/
5# Zip it up
6cd layer # Note we zip it from this `layer` directory
7zip -r9q .

Once it's zipped up (note the file paths used), we can create the layer, and update the function to use it:

1# Create the layer
2aws --profile cloudcasts lambda publish-layer-version \
3 --layer-name "foo_nodejs_modules" \
4 --description "AWS S3 Node Modules" \
5 --zip-file fileb:// \
6 --compatible-runtimes nodejs14.x
8# Update the function
9aws --profile cloudcasts lambda update-function-configuration \
10 --function-name foo_func_nodejs \
11 --layers "arn:aws:lambda:us-east-2:601364042938:layer:foo_nodejs_modules:2"

The function is now using the layer.

Let's repackage our function (it's now just the index.js file) and re-upload it so the function is back to being tiny:

1# Create a new .zip of the app (just the `index.js` file!)
2zip -r9 index.js
4# Update the function
5aws --profile cloudcasts lambda update-function-code \
6 --function-name foo_func_nodejs \
7 --zip-file fileb:// \
8 --publish
10# Invoke the function
11aws --profile cloudcasts lambda invoke \
12 --function-name foo_func_nodejs \
13 --invocation-type RequestResponse \
14 output.json
16cat output.json

And it (still) worked! Our function is tiny, the layer has the larger stuff. This makes updating the function must quicker.

Don't miss out

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