我正在尝试为两个阶段的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
}
}
https://aws.amazon.com/blogs/compute/using-api-gateway-stage-variables-to-manage-lambda-functions
根据这一页,我认为这应该是可能实现的。
我已经添加了一个stage_variable来定义每个阶段使用的Lambda函数,但是我不确定如何实际地将这个值纳入集成,我假设它是通过aws_apigatewayv2_integration/integration_uri设置完成的,但是我找不到任何使用stage_variable的例子(仅设置)在文档中:
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/apigatewayv2_stage
欢迎指教
感谢您将需要分解调用臂,以便可以对其进行模板化。API网关使用的模板语言与terraform的模板语言非常相似——两者都使用${expression}
。要在terraform中使用API网关阶段变量,请使用双$$
转义美元符号-因此您的语句将看起来像$${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"
}