Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 692
trojan Avatar asked Oct 30 '22 04:10

trojan


1 Answers

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.

like image 102
H6. Avatar answered Nov 15 '22 07:11

H6.