trojan
trojan

Reputation: 71

Multiple AWS Lambda functions using the same libraries

I am writing AWS Lambda functions for my android app backend. I have multiple Lambda functions in python on AWS which requires the same libraries. For example, I need to access the database so I use pymysql library in all my lambda functions. But I am not sure whether I am doing it right.

Do I have to include these libraries in every function package that I deploy or is there a better way by which I can reference the libraries I have used in the previous function?

I am following Tutorial: Accessing Amazon RDS in an Amazon VPC. I have 2 functions. I am uploading each function separately with its dependencies in a zip. Zip contains the code and libraries. Libraries takes most of the space making zip size big. Now the second function also requires the same libraries so again making a zip with same libraries feels wrong.

Also some links to where this is mentioned in docs is helpful. I did not find it anywhere in documentation.

Upvotes: 7

Views: 3757

Answers (2)

H6_
H6_

Reputation: 32808

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 to them in your Python Lambda functions. Here using 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 the shared code available in /opt. It can be then used in the functions.

Upvotes: 4

dmigo
dmigo

Reputation: 3029

Now that the Lambda Layers are released you can easily share libraries and code between your Lambda Functions.

You can create a zip file for the Layer pretty much the same way as you can do so for a Function.
To share pymysql package you will need to create a Lambda Layer on base of the following function:

pymysql-bundle.zip/
  python/lib/python3.7/site-packages/pymysql

Then from your Lambda Function's code you can reference it like this:

from pymysql import ...

Upvotes: 0

Related Questions