SAM Lambda Layer module not found for shared nodejs code

919 Views Asked by At

I'm defining multiple lambda functions in a single template.yaml. These functions have some common code, but not published modules. I assumed I could turn this common stuff into a versioned layer. With a directory to the effect as follows:

  • Project
    • LambdaFunc1
      • package.json
      • node_modules
      • func1.js
    • LambdaFunc2
      • package.json
      • node_modules
      • func2.js
    • common-stuff
      • package.json
      • my-common.js
    • template.yaml
    • node_modules

After testing, I copy common-stuff into the Projects/node_modules directory and my other LambdaFuncs resolve require('common-stuff') based on Node moving up the directory structure for not found modules.

To have SAM do the build/package/deploy, I noticed SAM doesn't touch the common-stuff however creates an .aws-sam/build structure with the two other Lambda functions. I had to create a structure for SAM's CodeURI to zip up.

Package/common-stuff/packaged/nodejs/node_modules/common-stuff/ with my package.json and my-common.js. My package.json uses name: "common-stuff", main: "my-common.js"

There are no other files - nothing under nodejs as I'm only packaging the modules. This appears to me the reason for Layers. I have verified SAM packages a zip file containing nodejs/node_modules/common-stuff/... by downloading the Layer zip file.

In the Lambda function template def, I add the permission to allow 'lambda:GetLayerVersion'. When I view the Lambda function in the console, I see this permission along with the others.

Interestingly, aws lambda get-layer-version-policy --layer-name MyLayer --version-number 8 --output text returns an error that there are no policies attached. My guess is that is because I've directly added it to the function, as I see it on the Lambda function with the correct Allow/GetLayerVersion.

This would seem to satisfy what I've read, however Node doesn't find the module. CloudWatch logs just say it can't find the module, nothing about permissions or syntax. Also, these functions worked until I added the Layer approach.

'sam local start-api' doesn't work either, same error. When I look in the Windows 10 default layer cache directory C:\Users\me\AppData\Roaming\AWS SAM\ there is an empty layers-pkg directory.

Is there some other magic I'm missing? Is there a better approach for sharing common code across Node Lambda functions?

I can't tell if AWS can't get the Layer, or the zip structure is wrong, or the require('common-stuff') is different (hope not).

Scott

0

There are 0 best solutions below