如何在Serverless中将API网关端点传递给健康检查Lambda函数
你可以通过 Serverless Framework 内置的 CloudFormation 资源引用能力实现单次部署,无需分两次执行命令或拆分配置文件。
Serverless 框架默认创建的 REST API 资源在 CloudFormation 中的逻辑 ID 固定为 ApiGatewayRestApi,你可以直接通过 CloudFormation 内置函数拼接完整的 API 端点,修改后的配置参考如下:
functions: app: handler: wsgi_handler.handler events: - http: method: ANY path: / - http: method: ANY path: '{proxy+}' healthcheck: environment: # 自动引用当前栈创建的API网关端点,无需手动填写 api_endpoint: Fn::Sub: "https://${ApiGatewayRestApi}.execute-api.${AWS::Region}.amazonaws.com/${sls:stage}" handler: healthcheck.handler events: - schedule: rate(1 minute) custom: wsgi: app: app.app pythonBin: python3 packRequirements: false pythonRequirements: dockerizePip: non-linux
配置说明:
${ApiGatewayRestApi}会自动解析为当前部署栈生成的 API 网关ID${AWS::Region}是 CloudFormation 内置变量,自动取当前部署的区域${sls:stage}是 Serverless 内置变量,自动取当前的部署阶段(默认是dev)
如果你使用的是 HTTP API 而非 REST API(事件配置用httpApi而非http),只需要把配置中的ApiGatewayRestApi替换为HttpApi即可。
内容的提问来源于stack exchange,提问作者Simon Ernesto Cardenas Zarate
相关产品推荐
相关产品推荐

