Search code examples
aws-cloudformationaws-samaws-sam-cli

How to ignore certain file e.g. .env when building AWS SAM Lambda Layer?


I am using AWS SAM to build lambda layer, which works well.

However, I do double checked that, that layer built includes my local .env file, which I do not want to include into the layer content. Any option to exclude/ignore certain files?

I checked (https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/building-layers.html) and (https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-layerversion.html) Not explain this user case.

Resources:
  PrismaClientLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: prisma-client-layer
      ContentUri: orm/
      CompatibleRuntimes:
        - nodejs18.x
    Metadata:
      BuildMethod: nodejs18.x 

Solution

  • Ensure your .env file is not in the orm folder.

    When using CodeUri we have the following:

    If a path to a local folder is provided, for the content to be transformed properly the template must go through the workflow that includes sam build followed by either sam deploy or sam package. By default, relative paths are resolved with respect to the AWS SAM template's location.

    For Node.js, during the execution of sam build the initial steps SAM CLI uses for Layer bundling are:

    1. npm pack -q file:<project-path>/orm
    2. Extract the tgz file into a temporary folder /tmp/tmp38x93h8u/unpacked
    3. Create the destination folder at <project-folder>/.aws-sam/build/PrismaClientLayer/nodejs
    4. Copy all unpacked files from item 2 to item 3 folder
    5. Inside the .aws-sam/build/PrismaClientLayer/nodejs it will run npm install -q --no-audit --no-save --unsafe-perm --production
    6. Copy node_modules dependencies from .aws-sam/build/PrismaClientLayer/nodejs/node_modules to .aws-sam/deps/<build-hash>/node_modules

    enter image description here

    You can debug the process using aws build --debug.

    Default behaviour: Files inside orm folder are copied to the destination Layer.

    You can have more control over the process by using:

    Metadata:
      BuildMethod: makefile
    

    You will need a Makefile inside the orm folder to build / copy and do whatever you need to output files into the correct layer destination (which is .aws-sam/build/PrismaClientLayer/nodejs in this scenario)