11

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.

disco crazy
  • 31,313
  • 12
  • 80
  • 83
K..
  • 4,044
  • 6
  • 40
  • 85

4 Answers4

5

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.

dmigo
  • 2,849
  • 4
  • 41
  • 62
5

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
disco crazy
  • 31,313
  • 12
  • 80
  • 83
  • 3
    How do you then use the function inside your lambda function? I tried just importing `SharedLayer` but it doesn't seem to work. – Anas Nov 09 '20 at 21:12
1

Try serverless framework, you can use the include/exclude artifacts without having to write your own scripts.

checkout serverless.com

I also use private node packages, but they need to be installed before sls deploy.

0

The problem with Lambda is, you have to deploy a ZIP-file, so all your code needs to be accesible from one root directory.

I solved this with a script that copies my shared code to all the Lambda-function directories before I archive every single function and upload them.

Symlinks are probably also possible.

K..
  • 4,044
  • 6
  • 40
  • 85
  • 1
    I tried symlinks and they didn't work for me, though there does seem to be a pull request that would add support for symlinks to the aws-cli. Hopefully it gets merged someday. https://github.com/aws/aws-cli/pull/2901 – chrislebaron Nov 07 '18 at 20:37
  • It is merged now. – K.. Apr 18 '19 at 11:57