我有如下地形设置:
resource "aws_apigatewayv2_route" "signup_route" {
api_id = "${aws_apigatewayv2_api.signup_redirect.id}"
route_key = "POST /signup"
target = "integrations/${aws_apigatewayv2_integration.lambda_integration.id}"
}
resource "aws_apigatewayv2_stage" "staging_stage" {
api_id = "${aws_apigatewayv2_api.signup_redirect.id}"
name = "staging"
auto_deploy = true
route_settings {
route_key = "POST /signup"
logging_level = "INFO"
detailed_metrics_enabled = true
}
}
我在部署时出现以下错误:
Error: error creating API Gateway v2 stage: NotFoundException: Unable to find Route by key POST /signup within the provided RouteSettings
该阶段似乎是在创建路线之前部署的。如何将对stage的依赖添加为对route
的依赖?
在Terraform中创建依赖项的最佳方法是编写对您想要依赖的资源的引用
resource "aws_apigatewayv2_route" "signup_route" {
api_id = "${aws_apigatewayv2_api.signup_redirect.id}"
route_key = "POST /signup"
target = "integrations/${aws_apigatewayv2_integration.lambda_integration.id}"
}
resource "aws_apigatewayv2_stage" "staging_stage" {
api_id = aws_apigatewayv2_api.signup_redirect.id
name = "staging"
auto_deploy = true
route_settings {
route_key = aws_apigatewayv2_route.signup_route.route_key
logging_level = "INFO"
detailed_metrics_enabled = true
}
}
因为route_settings
中的route_key
指的是aws_apigatewayv2_route.signup_route
,Terraform会将其视为对该资源的依赖。让依赖项像这样隐含是很好的,因为它可以让你专注于描述数据如何从一个资源传播到另一个资源,如果你后来删除了这个route_settings
块,那么它隐含的依赖项将自动删除,而不需要记住更新其他声明。
然而,在某些情况下,底层系统的设计使这种明确的数据流依赖性变得不可能。其中一个例子是AWS IAM角色,其中附加到角色的策略与角色本身是分开的,因此数据流推断的自然依赖关系是,策略和将承担角色的对象都依赖于角色,而承担角色的物体自然不依赖于策略。在这种情况下,我们往往需要添加额外的显式依赖depends_on
,以确保系统在应用其策略之前不会尝试承担该角色:
resource "aws_iam_role" "for_lambda" {
name = "lambda_function"
assume_role_policy = jsonencode({
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
})
}
resource "aws_iam_role_policy" "for_lambda" {
# (policy that the lambda function needs to do its work)
}
resource "aws_lambda_function" "example" {
name = "example"
# ...
# This reference makes the function depend on the role,
# but the role isn't ready to use until the associated
# policy has been attached to it too.
role = aws_iam_role.for_lambda.arn
# ...so we need to explicitly declare this hidden dependency:
depends_on = [aws_iam_role_policy.for_lambda]
}
在资源依赖关系中有更多关于依赖关系如何在Terraform中工作的信息。
看起来aws_apigatewayv2_route
不会导出任何我们可以使用的有用属性。但是depends_on
在这种情况下不起作用吗?-
resource "aws_apigatewayv2_stage" "staging_stage" {
depends_on = [aws_apigatewayv2_route.signup_route]
...
https://www.terraform.io/docs/configuration/resources.html#depends_on-显式资源依赖
=====
(在这里编辑,因为我还没有足够的代表来评论另一个答案(我没有意识到你可以使用来自一个资源的输入作为属性。这真是太棒了,而且绝对是要走的路。