Josh Demail
Josh Demail

Reputation: 123

How to import external python modules to your AWS Lambda functions, in serverless framework?

root
    - module_1
        - utils.py
    - module_2 
        - handler.py (Lambda Function) (Requires functions from utils.py)
        - serverless.yml
    - module_3
        - handler.py (Lambda Function)
        - serverless.yml

How to import the classes and the methods in the utils.py, loacted in a completely different directory?

Upvotes: 1

Views: 922

Answers (2)

lalit gangwar
lalit gangwar

Reputation: 401

create lambda layer for this kind of thing so that you can use same module into other lambda functions as well, it is more scalable. You can pack it with your lambda function also as start, best practice it to use lambda layer. Add layer with your lambda function and you can import desired module.

Upvotes: 1

Josh Demail
Josh Demail

Reputation: 123

As you know, the serverless framework zips all the contents in the directory in which it is present and deploys it to the cloud. But our Lambda uses functions and classes from a completely different directory, so when we deploy the function, it doesn't include those files.

How can we accomplish that?

Well, we can copy that module and paste it in that Lambda function directory so that it is included while deploying the Lambda.

It is not feasible, let's say when that module is needed by 10 different Lambda modules

root
    - module_1
        - utils.py
    - module_2 
        - handler.py (Lambda Function) (Requires functions from utils.py)
        - serverless.yml
        .
        .
        .
        
    - module_10
        - handler.py (Lambda Function) (Requires functions from utils.py)
        - serverless.yml

A single change in utils.py, has to be made in 10 different places, ugh....

No worries, serverless has got a plugin which comes to your rescue

serverless-package-external

This plugin will help you to solve your issuse. Have a good day!

Upvotes: 2

Related Questions