Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to install dependencies of lambda functions upon cdk build with AWS CDK

When using AWS SAM I used to run build command which would go through all of my Lambda function packages and install their dependencies (run npm install on them).

How can I achieve the same behavior with AWS CDK? It doesn't seem to do it automatically, or am I missing something?

like image 864
Milan Avatar asked Jul 25 '19 08:07

Milan


Video Answer


3 Answers

You can do this pretty easily with a local build script like this:

    const websiteRedirectFunction = new lambda.Function(
      this,
      "RedirectFunction",
      {
        code: lambda.Code.fromAsset(path.resolve(__dirname, "../../redirect"), {
          bundling: {
            command: [
              "bash",
              "-c",
              "npm install && npm run build && cp -rT /asset-input/dist/ /asset-output/",
            ],
            image: lambda.Runtime.NODEJS_12_X.bundlingDockerImage,
            user: "root",
          },
        }),
        handler: "index.redirect",
        tracing: lambda.Tracing.ACTIVE,
        runtime: lambda.Runtime.NODEJS_12_X,
      }
    );

Assuming you have a folder that you want to build and upload the handler and node_modules for Lambda.

From the docs:

When using lambda.Code.fromAsset(path) it is possible to bundle the code by running a command in a Docker container. The asset path will be mounted at /asset-input. The Docker container is responsible for putting content at /asset-output. The content at /asset-output will be zipped and used as Lambda code.

like image 141
seanWLawrence Avatar answered Oct 17 '22 02:10

seanWLawrence


There is (currently experimental) module inside aws-cdk which solves the problem for Python.

See more here.

like image 40
blahblah Avatar answered Oct 17 '22 00:10

blahblah


This functionality really is missing. You'll need to write your own packaging. Keep in mind that lambda dependencies must be built on a system with the same architecture as the target system in AWS (Linux) if any of the dependencies (such as Numpy) uses a shared library with native C code.

There's a Docker image available which aims to provide an environment as close to AWS as possible: lambci/lambda:build-python3.7

So if you're building on any non-Linux architecture, you might need this for some more complex lambda functions.

EDIT: I opensourced my Python code for lambda packaging: https://gitlab.com/josef.stach/aws-cdk-lambda-asset

like image 4
0x32e0edfb Avatar answered Oct 17 '22 00:10

0x32e0edfb