Question:
I am designing a serverless application with AWS Lambda. There’s a piece of code on one of the functions that process the request in a certain way. I am going to make another function that’s going to make the same processing with the request data, in the same way.
The problem is that, if I change the processing function in one of the Lambda functions, I’m going to have to copy the function and paste it into the other Lambda function. Every time I make a change I will have to do this. This will be even more cumbersome if I want to do the same processing function in more than two Lambda functions.
Is there a way to share pieces of code between Lambda functions, so I may respect DRY principles? Thanks.
Answer:
Now you can use Layers to share libraries and code between your Functions.
It is possible to base more then one Function on one Layer.
You can create a zip file for the Layer pretty much the same way as you can do so for a Function. The only thing will be that all the common packages go to python/lib/python3.7/site-packages
directory inside of zip and all your code goes to python
directory.
So if you have file structure like this:
1 2 3 4 5 6 |
bundle.zip/ python/ common/ __init__.py lib.py |
Then from your Lambda Function’s code you can reference it like this:
1 2 |
from common.lib import ... |