Is it possible to share a piece of code betwen AWS Lambda functions? Is it possible to share a piece of code betwen AWS Lambda functions? python-3.x python-3.x

Is it possible to share a piece of code betwen AWS Lambda functions?


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:

bundle.zip/  python/    common/      __init__.py      lib.py

Then from your Lambda Function's code you can reference it like this:

from common.lib import ...


One solution is to use Terraform to synchronize your infrastructure and lambda functions. With Terraform, you'll be able to define each lambda function like so:

resource "aws_lambda_function" "func1_lambda" {    function_name = "func1_lambda"    handler = "func1"    runtime = "python2.7"    filename = "lambda.zip"    source_code_hash = "${base64sha256(file("lambda.zip"))}"    role = "${aws_iam_role.lambda_exec_role.arn}"}resource "aws_lambda_function" "func2_lambda" {    function_name = "func2_lambda"    handler = "func2"    runtime = "python2.7"    filename = "lambda.zip"    source_code_hash = "${base64sha256(file("lambda.zip"))}"    role = "${aws_iam_role.lambda_exec_role.arn}"}

Inside lambda.zip (a zip file containing lambda.py), you would define each lambda function as well as any common functions needed by all lambdas:

def aCommonFunc(input):    # return something heredef func1(event, context):    return { "message": aCommonFunc("hello, world") }def func2(event, context):    return { "message": aCommonFunc("another string") }

Deploying your new set of lambdas would involve writing a script that zips up your python files and then runs terraform apply.

While this does add more work up-front, it will allow you to track and re-create your Lambdas more efficiently over time as your project grows.

You can see a full example here.