错误 aws_alb_target_group 设置了“计数”,必须在特定实例上访问其属性

Mai*_*aik 3 amazon-web-services terraform aws-alb

我正在使用Terraform v0.12.26和设置并aws_alb_target_group作为:

resource "aws_alb_target_group" "my-group" {
  count = "${length(local.target_groups)}"
  name = "${var.namespace}-my-group-${
    element(local.target_groups, count.index)
  }"

  port     = 8081
  protocol = "HTTP"
  vpc_id   = var.vpc_id

  health_check {
    healthy_threshold   = var.health_check_healthy_threshold
    unhealthy_threshold = var.health_check_unhealthy_threshold
    timeout             = var.health_check_timeout
    interval            = var.health_check_interval
    path                = var.path
  }

  tags = {
    Name = var.namespace
  }

  lifecycle {
    create_before_destroy = true
  }
}
Run Code Online (Sandbox Code Playgroud)

当地人长这样:

locals {
  target_groups = [
    "green",
    "blue",
  ]
}
Run Code Online (Sandbox Code Playgroud)

当我运行terraform apply它返回以下错误:

Error: Missing resource instance key

  on ../../modules/aws_alb/outputs.tf line 3, in output "target_groups_arn":
   3:     aws_alb_target_group.http.arn,

Because aws_alb_target_group.http has "count" set, its attributes must be
accessed on specific instances.

For example, to correlate with indices of a referring resource, use:
    aws_alb_target_group.http[count.index]
Run Code Online (Sandbox Code Playgroud)

我遵循了这个实现

知道如何修复它吗?

输出

output "target_groups_arn" {
  value = [
    aws_alb_target_group.http.arn,
  ]
}
Run Code Online (Sandbox Code Playgroud)

Ala*_*Dea 5

由于aws_alb_target_group.http是一个计数资源,您需要通过索引或所有这些实例作为列表[*](又名Splat Expressions)引用特定实例,如下所示:

output "target_groups_arn" {
  value = aws_alb_target_group.http[*].arn,
}
Run Code Online (Sandbox Code Playgroud)

target_groups_arn输出将是TG ARNS的列表。

  • 如果您的 count 参数仅提供一个实例,则您可能需要使用 `[0]` 而不是 `[*]`,因为您会收到此错误 --> "arn is tuple with 1 element" (4认同)
  • 我明白。有时, count 与三元运算符和布尔变量一起使用,以有条件地提供/销毁单个资源: `count = var.enable_resource ? 1 : 0` 在这种情况下,您提供的答案将给出我之前的评论中所述的错误。 (4认同)
  • 您描述的情况不在问题中,因此您的评论偏离主题并造成混乱。 (2认同)