How can I test an AWS SAM application with Lambda Layers locally?
Asked Answered
Q

1

2

I'm creating an API using AWS SAM with an API Gateway to pass requests to multiple Lambda handler functions.

I share code between them so I'd like to use Lambda Layers to avoid rewriting redundant code.

I'm initially starting out by testing my lambda layers locally, before creating any actual AWS resources. It seems that when I run my API locally, with sam local start-api, my functions can't see the code in the layers. My guess is that's because layers have to be stored in S3 for SAM to be able to see them, otherwise, they won't be able to pull them down and add them to the Lambda function.

Is there a way to share code between SAM Lambda functions while testing locally, before creating any AWS resources?

Thanks for your help!

Quean answered 3/5, 2021 at 14:50 Comment(3)
sam deploy themChant
But then they wouldn't be local, right?Quean
Yup. AFAICT, there's no mention of a layer being run locally. One builds, deploys, then get their other function to connected to it via the template directives.Chant
T
1

For those who come across this, I was able to solve the problem by making the following changes:

1- Modified template.yaml:

I added the following layer definition:

...
MyLayer:
  Type: AWS::Serverless::LayerVersion
  Properties:
    ContentUri: core/
    CompatibleRuntimes:
      - python3.9
  Metadata:
    BuildMethod: python3.9   # This ensures AWS SAM builds this layer
...

Here, core is the directory containing my custom modules.

2- Directory Structure:

This is how my project is structured:

├── README.md
├── __init__.py
├── core
│   └── wrapper
│       ├── __init__.py
│       └── handler.py
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   ├── decorators.py
│   └── requirements.txt
├── index.html
├── samconfig.toml
└── template.yaml

3- Import in app.py:

Here's how I imported the HandlerResponse from the wrapper in app.py:

from wrapper.handler import HandlerResponse

4- Building and Running:

After updating the template.yaml, I ran the following commands:

sam build --use-container
sam local start-api

Finally they will create inside .aws-sam/build the folder with your layer:

enter image description here

I hope this helps someone else facing the same issue!

Tindall answered 22/8, 2023 at 3:9 Comment(1)
I have followed your steps but I get an error Unable to import module 'lambda_handler': No module named 'api_handlers'. api_handlers are equivalent to your wrapper packageBlastocyst

© 2022 - 2024 — McMap. All rights reserved.