Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing code in AWS Lambda

What is the prefered way to share code between AWS Lambda functions?

I have a structure like this:

  • functions
    • a
      • node_modules
      • index.js
      • package.json
    • b
      • node_modules
      • index.js
      • package.json
    • c
      • node_modules
      • index.js
      • package.json

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.

like image 798
K.. Avatar asked May 06 '18 19:05

K..


People also ask

Can Lambda deploy deployment code?

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.

How can additional code or content be provided for your Lambda?

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.

Can AWS Lambda have multiple functions?

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.


Video Answer


2 Answers

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
like image 195
H6. Avatar answered Oct 24 '22 08:10

H6.


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.

like image 5
dmigo Avatar answered Oct 24 '22 08:10

dmigo