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/
4 
5# Zip it up
6cd layer # Note we zip it from this `layer` directory
7zip -r9q layer.zip .

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://layer.zip \
6 --compatible-runtimes nodejs14.x
7 
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.zip index.js
3 
4# Update the function
5aws --profile cloudcasts lambda update-function-code \
6 --function-name foo_func_nodejs \
7 --zip-file fileb://index.zip \
8 --publish
9 
10# Invoke the function
11aws --profile cloudcasts lambda invoke \
12 --function-name foo_func_nodejs \
13 --invocation-type RequestResponse \
14 output.json
15 
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.