When I create an AWS Lambda Layer, all the contents / modules of my zip file go to /opt/
when the AWS Lambda executes. This easily becomes cumbersome and frustrating because I have to use absolute imports on all my lambdas. Example:
import json
import os
import importlib.util
spec = importlib.util.spec_from_file_location("dynamodb_layer.customer", "/opt/dynamodb_layer/customer.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def fetch(event, context):
CustomerManager = module.CustomerManager
customer_manager = CustomerManager()
body = customer_manager.list_customers(event["queryStringParameters"]["acquirer"])
response = {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": json.dumps(body)
}
return response
So I was wondering, is it possible to add these /opt/paths to the PATH environment variable by beforehand through serverless.yml? In that way, I could just from dynamodb_layer.customer import CustomerManager
, instead of that freakish ugliness.
I've Lambda layer for Python3.6 runtime. My my_package.zip structure is:
my_package.zip
- python
- lib
- python3.6
- site-packages
- customer
All dependencies are in build
folder in project root:
e.g. build/python/lib/python3.6/site-packages/customer
Relevant section of my serverless.yml
layers:
my_package:
path: build
compatibleRuntimes:
- python3.6
In my Lambda I import my package like I would do any other package:
import customer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With