简体   繁体   中英

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?

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM