根据使用计数创建的值获取资源

Get resources based on a value created using count

我正在使用 Terraform v12.19 和 aws 提供程序 v2.34.0。 想象一下,我生成了一个带有计数值的资源:

resource "aws_iam_role" "role" {
  count = length(var.somevariable)
  name = var.somevariable[count.index]
}

稍后,我想以这种方式引用一个特定的资源实例,e。 g.:

resource "aws_iam_role_policy_attachment" "polatt" {
  role       = aws_iam_role.role["TheRoleNameIWant"].id
  policy_arn = "arn:aws:iam::aws:policy/..."
}

我不知道索引,只能依靠变量提供的名称。那是因为变量的值是由外部源提供的,顺序可能会改变...

知道怎么做吗?

您应该可以使用 index terraform 函数完成此操作。

这是一个使用 null_resources 进行测试的最小示例

locals {
  role_names = [
    "role-a",
    "role-b",
    "role-c",
    "role-d",
  ]

  target_role_name = "role-c"
}

resource "null_resource" "hi" {
  count = length(local.role_names)
}

output "target_resource" {
  value = null_resource.hi[index(local.role_names, local.target_role_name)].id
}

output "all_resources" {
  value = [for r in null_resource.hi : r.id]
}

这个输出,例如

all_resources = [
  "4350570701002192774",
  "9173388682753384584",
  "1634695740603384613",
  "2098863759573339880",
]
target_resource = 1634695740603384613

所以我想你的例子看起来像

resource "aws_iam_role_policy_attachment" "polatt" {
  role       = aws_iam_role.role[index(var.somevariable, "TheRoleNameIWant")].id
  policy_arn = "arn:aws:iam::aws:policy/..."
}

更新

您在下面的评论中提到您实际上有一个比名称列表更复杂的数据结构。我只是想提一下,您可以从 JSON 结构中派生名称。

假设您有如下内容

variable "role_values" {
  value = [
    {
      name = "foo",
      other = "details",
      fields = 3
    },
    {
      name = "bar",
      other = "yet more details",
      fields = 3
    }
  ]
}

您可以使用本地和较新的 for 循环 TF 0.12 提供

locals {
  role_names = [for role in var.role_values: role.name]
}

这样您就不必将名称存储两次。