我正在使用AWS Lambda设计无服务器应用程序。 在其中一个以某种方式处理请求的函数上有一段代码。 我将以相同的方式创建另一个与请求数据进行相同处理的函数。
问题是,如果我更改其中一个Lambda函数的处理函数,我将不得不复制该函数并粘贴其他Lambda函数。 每次我做出改变,我都必须这样做。 如果我想在两个以上的Lambda函数中执行相同的处理功能,这将更加麻烦。
有没有办法在Lambda函数之间共享代码片段,所以我可能会尊重DRY原则? 谢谢。
I am designing a serverless application with AWS Lambda. There's a piece of code on one of the functions that processes the request in 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 in the other Lambda function. Everytime I make a change I will have to do this. This will be yet 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.
最满意答案
一种解决方案是使用Terraform同步您的基础架构和lambda函数。 使用Terraform,您将能够像这样定义每个lambda函数:
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}" }在lambda.zip (包含lambda.py的zip文件)中,您将定义每个lambda函数以及所有lambdas所需的任何常用函数:
def aCommonFunc(input): # return something here def func1(event, context): return { "message": aCommonFunc("hello, world") } def func2(event, context): return { "message": aCommonFunc("another string") }部署新的lambdas集合将涉及编写一个压缩python文件的脚本,然后运行terraform apply 。
虽然这确实可以预先添加更多工作,但随着项目的增长,它可以让您随着时间的推移更有效地跟踪和重新创建Lambdas。
你可以在这里看到一个完整的例子。
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.pyThen from your Lambda Function's code you can reference it like this:
from common.lib import ...更多推荐
发布评论