Created
January 11, 2019 12:41
-
-
Save EricsonWillians/f20dfa37a5ce68aa6edfd4b15358e30b to your computer and use it in GitHub Desktop.
Custom module import example using AWS Lambda Layers (Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
When a custom lambda layer (zipped folder) is added, all lambda functions that use it put it on "/opt/LAYER". | |
In theory, "/opt/LAYER" should be added to the $PATH environment variable, but that didn't happen. | |
In any case, this is an example of how to import in an "absolute" fashion. | |
sample_lib/layer_test.py (That's the structure of the layer, which has a class named X.) | |
""" | |
import json | |
import os | |
import importlib.util | |
spec = importlib.util.spec_from_file_location("sample_lib.layer_test", "/opt/sample_lib/layer_test.py") | |
foo = importlib.util.module_from_spec(spec) | |
spec.loader.exec_module(foo) | |
def fetch(event, context): | |
directories = os.popen("find /opt/* -type d -maxdepth 4").read().split("\n") | |
body = { | |
'directories': directories, | |
'imported': foo.X()() | |
} | |
response = { | |
"statusCode": 200, | |
"headers": { | |
"Access-Control-Allow-Origin": "*" | |
}, | |
"body": json.dumps(body) | |
} | |
return response | |
# X | |
class X: | |
def __call__(self): | |
return("Yay, layers work!") | |
""" | |
The invoke response is: | |
{"statusCode": 200, "headers": {"Access-Control-Allow-Origin": "*"}, "body": "{\"directories\": [\"/opt/sample_lib\", \"\"], \"imported\": \"Yay, layers work!\"}"} | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment