When building a serverless application using Lambda or dynamoDB with AWS SAM, the code commonly used in various projects may come out. It would be convenient if things that could be shared could be shared quickly and called when needed, so I immediately put it into practice.
AWS Lambda has a layer function, and you can set the library you want to use in the Lambda code. I tried to find out how to set the code and libraries that depend on Layer as a project of AWS SAM.
I found some ways to zip up the libraries needed for Layer and save them in S3 and configure them from the AWS console, but I couldn't quite get the method to deploy them as an AWS SAM project, so I wrote it as a memorandum. I will leave it.
We will assume that you have already installed the AWS SAM CLI. This explanation uses Python 3.6.
The directory for storing the code and libraries you want to use as a layer is determined for each language. Include AWS Lambda library dependencies in layers (https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/configuration-layers.html#configuration-layers-path)
For python, if you do not store it in python
or python / lib / python3.6 / site-packages
, the following reference error will be displayed.
Unable to import module 'app': cannot import name 'layer_code'
Add the directory to store the layer to the SAM project created by the sam init
command.
sam-app
├── README.md
├── app
│ ├── __init__.py
│ ├── app.py
│ └── requirements.txt
├── events
│ └── event.json
├── layer //Add a layer storage directory here
│ └── python //Language name directory
│ └── sample
│ └── sample_layer.py //Code you want to use as a layer
└── template.yaml
template.yaml
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: hello-world-sample-function
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.6
Layers:
- !Ref LayerSampleLayer #Point 1
Events:
(abridgement)
#Layer definition
LayerSampleLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: layer-sample-layer
Description: Hello World Sample Application Resource Layer
ContentUri: layer #Point 2
There are two points in writing template.yaml.
Add the Layers
item to the Lambda function definition and set it to refer to the Layer definition.
In the layer definition, set the folder path that stores the layer code. → To be exact, set the parent directory of the language name directory
If you set the layer in template.yaml, you can use it as if it is in the same layer as app.py.
The settings will not be reflected unless you do sam build
once.
app.py
#Browse the file added as a layer
from sample import sample_layer
def lambda_handler(event, context):
res = sample_layer.hello()
return res
sample_layer.py
def hello():
return "hello Layer!"
What is the AWS Serverless Application Model (AWS SAM)](https://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/what-is-sam.html) AWS Lambda Layers
Recommended Posts