链接到在 Terraform 中使用 count 创建的资源

amb*_*960 3 terraform

如何链接到使用 count 创建的资源?count或者如果我想将额外的资源链接到它们,我不应该创建它们吗?按照下面的方式执行此操作,count在初始资源中使用并for_each在链接资源中使用会出现以下错误:

The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type number.
Run Code Online (Sandbox Code Playgroud)

我明白为什么会发生这个错误,但我也对这里的最佳实践感到困惑。

resource "aws_wafv2_web_acl" "waf_acl_regional" {
  count       = var.env == "prod" ? 1 : 0
  name        = "${var.project}-${var.env}"
  description = "A simple WAF ACL for ${var.env} environment."
  scope       = "REGIONAL"

  default_action {
    allow {}
  }

  rule {
    ...
  }

  visibility_config {
    ...
  }
}

resource "aws_wafv2_web_acl_association" "example" {
  for_each     = aws_wafv2_web_acl.waf_acl_regional
  resource_arn = aws_lb.hasura.arn
  web_acl_arn  = each.value.arn
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Mar*_*o E 5

您已指示aws_wafv2_web_acl资源使用count元参数 [1],顾名思义,它使用数字。它创建一个数组,您可以通过引用数组的元素来访问元素。在你的情况下,那就是aws_wafv2_web_acl.waf_acl_regional[0]. 另一方面,for_each元参数 [2] 使用键/值对。这意味着为了获取值,您必须有一个将用作对值的引用的键。例如,这将是类似的aws_wafv2_web_acl.waf_acl_regional["prod"]。这进一步意味着var.env必须是mapor类型set[3]。这些类型是 Terraform 中的复杂类型。


[1] https://www.terraform.io/language/meta-arguments/count

[2] https://www.terraform.io/language/meta-arguments/for_each

[3] https://www.terraform.io/language/expressions/type-constraints#complex-types