python - 通过 API Gateway 触发 Lambda 的特定功能
问题描述
我正在用 boto3 学习 Lambda 和 Python。我在下面的第 1 点中有 AWS Lambda 代码,它使用 boto3 来停止一些 ECS 服务,我通过 API Gateway url 触发了这个 Lambda curl -X POST https://blablabla.execute-api.xx-west-1.amazonaws.com/test/
,它工作正常。
我知道我在处理程序下编码良好的所有内容都可以工作,但我不能一次全部放在处理程序下以停止/启动各种服务,而是我想在同一个 Lambda 中添加不同的代码来执行以下操作: ) 启动 ECS 服务,b) 启动 RDS DB,c) 停止 RDS DB,就像我在下面的第 2 点中尝试建议的那样。
我知道 boto3 代码应该是什么样子,所以我想在我在 boto3 参数下方的第 2 点中列出的这些函数下添加,然后在 API Gateway 中创建一个资源(或其他东西)来链接 Lambda 中的函数,因此,使用相同的 url 我可以触发特定功能,请参见下面第 3 点中的示例。
在 API Gateway(资源)中,我只能添加一个“PUT 方法”(每个资源),这是我用来触发 Lambda 的方法,我之所以提到这一点是因为我想创建单独的 Lambda,然后添加一个资源每个 PUT 方法,所以在我可以为 url 添加具有不同结尾的阶段之后,但似乎我不能,也许有一种方法,但我只是不知道。
也许我错了,我可以把所有东西都放在处理程序下?
我有什么选择来完成这个?
1)
import json
import boto3
import pprint
region = 'xx-west-1'
cluster_name = "dummy-XX102020"
service_name = "some-test"
def lambda_handler(event, context):
ecs_client = boto3.client('ecs', region_name=region)
ecs_client.update_service(
cluster=cluster_name,
service=service_name,
desiredCount=0
)
print(ecs_client)
asg_client = boto3.client('application-autoscaling', region_name=region)
asg_client.register_scalable_target(
ServiceNamespace='ecs',
ResourceId='service' + '/' + cluster_name + '/' + service_name,
ScalableDimension='ecs:service:DesiredCount',
MinCapacity=0,
MaxCapacity=0,
)
print(asg_client)
response = {
"statusCode": 200,
"body": json.dumps('Executed successfully')
}
return response
def start_ecs(I don't know what to put here)
my code here
def start_rds(I don't know what to put here)
my code here
def stop_rds(I don't know what to put here)
my code here
curl -X POST https://blablabla.execute-api.xx-west-1.amazonaws.com/start_ecs/
curl -X POST https://blablabla.execute-api.xx-west-1.amazonaws.com/start_rds/
curl -X POST https://blablabla.execute-api.xx-west-1.amazonaws.com/stop_rds/
解决方案
我使用 API Gateway 阶段来触发不同的 lambda 函数。您可以将lambda_function_name
(在我的情况下为 lbfunc)作为变量放入阶段并在集成请求中使用此变量Lambda Function ${stageVariables.lambda_function_name}
您可以在此处查看 AWS API Gateway 阶段: https ://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-stages.html
有了这个,您可以拥有一个具有不同阶段触发不同 lambda 函数的 rest-api。
就我而言,我将它用于生产和开发,所以它看起来像这样:
https://blablabla.execute-api.eu-west-1.amazonaws.com/prod-v1/
推荐阅读
- php - 一般来说,什么是域文件夹?它是什么意思/包含什么?
- sql - 如何在postgresql中结合简单的with语句和递归语句
- typescript - TypeORM: FieldResolver return type err: 你需要提供显式类型
- jquery - 编辑表单:使用 grouped_select,如何在 Rails 中将先前选择的值显示为默认值?
- spring-boot -
启动 ApplicationContext 时出错。要显示条件报告,请在启用“调试”的情况下重新运行您的应用程序 - linux - 使用规范文件中的 rpmbuild 创建 rpm 包时出错
- java - java中的哪个日期模式可以产生这个日期结果?(秒后七位数)
- c# - wpf caliburn micro中的Listview双击问题
- ios - 在 iOS 13 中覆盖 traitCollection
- reactjs - 如何使用反应异步在材质 ui 网格列表中添加虚拟化?