首页 > 解决方案 > 如何在 Terraform 中为 `aws_apigatewayv2_route` 添加对 `aws_apigatewayv2_stage` 的依赖?

问题描述

我的地形设置如下:

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

似乎在创建路线之前部署了舞台。如何添加对阶段的依赖以依赖route

标签: terraformterraform-provider-aws

解决方案


在 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_keyinroute_settings指的是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]
}

在Resource Dependencies中有更多关于依赖关系如何在 Terraform 中工作的信息。


推荐阅读