Sharing code in AWS Lambda

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.


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.