如何在无服务器环境中将api端点参数传递给lambda函数



我在API网关后面创建了一个lambda函数,我也在尝试为它实现健康检查,但现在我需要通过两个步骤来完成:

  1. 运行serverless deploy,以便为api网关吐出端点
  2. 手动将端点插入healthcheck.environment.api_endpoint参数,然后再次运行serverless deploy

functions:
app:
handler: wsgi_handler.handler
events:
- http:
method: ANY
path: /
- http:
method: ANY
path: '{proxy+}'
healthcheck:
environment:
api_endpoint: '<how to reference the api endpoint?>'
handler: healthcheck.handler
events:
- schedule: rate(1 minute)
custom:
wsgi:
app: app.app
pythonBin: python3
packRequirements: false
pythonRequirements:
dockerizePip: non-linux

有没有办法在创建时获得对api网关的引用,以便将其作为环境变量传递给healthcheck应用程序?我能想到的另一种选择是,基本上只为健康检查目的创建一个特定的serverless.yaml。

我注意到我可以在lambda中重建端点,并像这样获取id:

healthcheck:
environment:
api_endpoint: !Ref ApiGatewayRestApi
region: ${env:region}
handler: healthcheck.handler
events:
- schedule: rate(1 minute)

然后重建:

def handler(event, context):
api_id = os.environ['api_endpoint']
region = os.environ['region']
endpoint = f"https://{api_id}.execute-api.{region}.amazonaws.com/dev"

只要有一点云信息,就可以直接注入!这样就不需要每次在lambda处理程序中计算它。

api_endpoint: {
'Fn::Join': [
'',
[
{ Ref: 'WebsocketsApi' },
'.execute-api.',
{ Ref: 'AWS::Region' },
'.',
{ Ref: 'AWS::URLSuffix' },
"/${opt:stage, self:provider.stage, 'dev'}",
],
],
},

(这是一个websocket API示例(

您的API是通过同一个/另一个Cloudformation Stack创建的吗?如果是这样,您可以直接引用is(同一堆栈(或通过CloudFormation变量导出。

https://carova.io/snippets/serverless-aws-cloudformation-output-stack-variables

https://carova.io/snippets/serverless-aws-reference-other-cloudformation-stack-variables

如果您在CloudFormation之外创建它,即在aws控制台中创建,那么您需要将id添加到模板中。很可能是根据阶段创建不同的环境变量。

最新更新