What is the prefered way to share code between AWS Lambda functions?
I have a structure like this:
This let every function keep its own node_modules and I can package the whole thing with the CLI.
But what about custom code that needs to be shared?
I can require("../mylibrary")
but the package command would still not include it.
A CodeDeploy deployment group on an AWS Lambda compute platform identifies a collection of one or more AppSpec files. Each AppSpec file can deploy one Lambda function version. A deployment group also defines a set of configuration options for future deployments, such as alarms and rollback configurations.
Lambda layers provide a convenient way to package libraries and other dependencies that you can use with your Lambda functions. Using layers reduces the size of uploaded deployment archives and makes it faster to deploy your code. A layer is a . zip file archive that can contain additional code or data.
Serverless applications usually consist of multiple Lambda functions. Each Lambda function can use only one runtime but you can use multiple runtimes across multiple functions. This enables you to choose the best runtime for the task of the function.
As dmigo mentioned already it's possible with Lambda layers. Here is some SAM template code for using the Lambda Layer Code:
Globals:
Function:
Runtime: nodejs8.10
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: a/
Handler: index.handler
Layers:
- !Ref MySharedLayer
MySharedLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: SharedLayer
Description: Some code to share with the other lambda functions
ContentUri: layer/
CompatibleRuntimes:
- nodejs8.10
RetentionPolicy: Retain
Now you can use Layers to share libraries and code between your Functions. You can create a Layer from a zip file the same way you do that for a Function.
The layer package will look more or less like this:
my-layer.zip
└ nodejs/node_modules/mylibrary
If you create your Functions on top of this Layer then in the code it can be referenced like this:
const shared = require('mylibrary');
It is worth noticing that Layers support versioning and relate to Functions as many-to-many. Which makes them second npm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With