Multiple AWS Lambda functions using the same libraries
I am writing AWS Lambda for my android. I have several lambda functions in python on AWS that require the same libraries. For example, I need to access a database, so I use the pymysql library in all my lambda functions. But I'm not sure if I'm doing this the right way.
Do I need to include these libraries in every feature bundle I deploy, or is there a better way I can reference the libraries I used in the previous function?
I am following Tutorial: Access Amazon RDS in Amazon VPC . I have 2 functions. I download each function separately with its dependencies in a zip. Zip contains code and libraries. Libraries take up most of the space, making the zip size large. Now the second function also requires the same libraries as repeating zip with the same libraries.
Also helpful are links to where this is mentioned in the docs. I haven't found it anywhere in the documentation.
source to share
Now that Lambda Layers are released, you can easily exchange libraries and code between your lambda functions.
You can create a zip file for a layer in much the same way as you can create a zip file for a function.
To share a package pymysql
, you need to create a Lambda layer based on the following function:
pymysql-bundle.zip/ python/lib/python3.7/site-packages/pymysql
Then, from your Lambda Function code, you can reference it like this:
from pymysql import ...
source to share
You can share your code using AWS Lambda Layers . For example, define them using AWS::Lambda::LayerVersion
or AWS::Serverless::LayerVersion
. You can then reference them in your Python Lambda functions. Here with AWS SAM :
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: function_code/
Handler: app.lambda_handler
Runtime: python3.6
Layers:
- !Ref MySharedLayer
MySharedLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: SharedLayerName
Description: Some shared code
ContentUri: layer_code/
CompatibleRuntimes:
- python3.6
RetentionPolicy: Retain
Each lambda function will have common code available in /opt
. It can then be used in functions.
source to share