Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Lambda packaging with dependencies

Further outlining is in the context of NodeJS and Monorepo (based on Lerna).

I have AWS stack with several AWS Lambda inside deployed by means of AWS CloudFormation. Some of the lambdas are simple (the single small module) and could be inlined:

https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Code.html#static-from-wbr-inlinecode

const someLambda = new Function(this, 'some-lambda', {
  code: Code.fromInline(fs.readFileSync(require.resolve(<relative path to lambda module>), 'utf-8')),
  handler: 'index.handler',
  runtime: Runtime.NODEJS_12_X
});

Some have no dependencies and packaged as follows:

const someLambda = new Function(this, 'some-lambda', {
  code: Code.fromAsset(<relative path to folder with lambda>),
  handler: 'index.handler',
  runtime: Runtime.NODEJS_12_X
});

But in case of relatively huge lambdas with dependencies, as I understand, we only way to package (proposed by API) is @aws-cdk/aws-lambda-nodejs:

import * as lambdaNJS from "@aws-cdk/aws-lambda-nodejs";

export function createNodeJSFunction(
  scope: cdk.Construct, id: string, nodejsFunctionProps: Partial<NodejsFunctionProps>
) {
  const params: NodejsFunctionProps = Object.assign({
    parcelEnvironment: { NODE_ENV: 'production' },
  }, nodejsFunctionProps);

  return new lambdaNJS.NodejsFunction(scope, id, params);
}

For standalone packages, it works well, but in case of the monorepo it just hangs on synth of the stack. I just looking for alternatives, cause I believe it is not a good idea to bundle (parcel) BE sources.

like image 853
Alexander Alexandrov Avatar asked Aug 31 '26 18:08

Alexander Alexandrov


1 Answers

I've created the following primitive library to zip only required node_modules despite packages hoisting.

https://github.com/redneckz/slice-node-modules

Usage (from monorepo root):

$ npx @redneckz/slice-node-modules \
  -e packages/some-lambda/lib/index.js \
  --exclude 'aws-*' \
  --zip some-lambda.zip

--exclude 'aws-*' - AWS runtime is included by default, so no need to package it.

like image 195
Alexander Alexandrov Avatar answered Sep 02 '26 09:09

Alexander Alexandrov