使用 terraform 时如何指定 api gateway 阶段调用的 lambda 函数?

Dan*_*Dan 6 aws-lambda terraform aws-api-gateway

我正在尝试为具有两个阶段的 AWS API 网关创建 IaC;开发和生产,每个阶段调用不同的 Lambda 函数。

我希望最终结果是:

  • 如果用户进入开发阶段,他们将调用开发 Lambda 函数
  • 如果用户进入生产阶段,他们将调用生产 Lambda 函数

我的代码目前看起来像这样,我删除了一些与问题无关的资源:

resource "aws_apigatewayv2_api" "app_http_api_gateway" {
  name          = "app-http-api"
  protocol_type = "HTTP"
}

resource "aws_apigatewayv2_integration" "app_http_api_integration" {
  api_id                    = aws_apigatewayv2_api.app_http_api_gateway.id
  integration_type          = "AWS_PROXY"
  connection_type           = "INTERNET"
  description               = "Lambda integration"
  integration_method        = "POST"
  # Unsure how to apply stage_variables here
  integration_uri           = aws_lambda_function.app_lambda_development.invoke_arn
  passthrough_behavior      = "WHEN_NO_MATCH"
}

resource "aws_apigatewayv2_route" "app_http_api_gateway_resource_route" {
  api_id    = aws_apigatewayv2_api.app_http_api_gateway.id
  route_key = "ANY /{resource}"
  target    = "integrations/${aws_apigatewayv2_integration.app_http_api_integration.id}"
}

resource "aws_apigatewayv2_stage" "app_http_api_gateway_development" {
  api_id            = aws_apigatewayv2_api.app_http_api_gateway.id
  name              = "development"
  auto_deploy       = true
  stage_variables   = {
    lambda_function = aws_lambda_function.app_lambda_development.function_name
  }
}

resource "aws_apigatewayv2_stage" "app_http_api_gateway_production" {
  api_id            = aws_apigatewayv2_api.app_http_api_gateway.id
  name              = "production"
  auto_deploy       = true
  stage_variables   = {
    lambda_function = aws_lambda_function.app_lambda_production.function_name
  }
}
Run Code Online (Sandbox Code Playgroud)

https://aws.amazon.com/blogs/compute/using-api-gateway-stage-variables-to-manage-lambda-functions

根据这个页面,我认为应该可以实现这一目标。

我添加了一个 stage_variable 来定义用于每个阶段的 Lambda 函数,但是我不确定如何实际将此值纳入集成中,我假设它是通过 aws_apigatewayv2_integration/integration_uri 设置完成的,但我找不到任何示例文档中使用的 stageVariables(仅设置):

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/apigatewayv2_stage

任何建议表示赞赏

谢谢

Dan*_*ego 3

您将需要分解调用 arn,以便可以对其进行模板化。API 网关使用的模板语言与 terraform 的非常相似——两者都使用${expression}. 要在 terraform 中使用 API 网关阶段变量,请使用 double$$转义美元符号 - 因此您的语句将类似于$${stageVariables.myVariableName}.

resource "aws_apigatewayv2_integration" "app_http_api_integration" {
api_id                    = aws_apigatewayv2_api.app_http_api_gateway.id
integration_type          = "AWS_PROXY"
connection_type           = "INTERNET"
description               = "Lambda integration"
integration_method        = "POST"
# Unsure how to apply stage_variables here
integration_uri           = "arn:aws:apigateway:${local.my_region}:lambda:path/2015-03-31/functions/$${stageVariables.lambda_name}/invocations"
passthrough_behavior      = "WHEN_NO_MATCH"
}
Run Code Online (Sandbox Code Playgroud)