如何在 Terraform 中反转和分组地图的值

How to invert and group values of a map in Terraform

我无法转换下一张地图:

变量定义:

variable "users_test" {
  type        = map(any)
  description = "Users List associated to a bucket"
}

变量值:

users_test = {
  robot1 = "bucket-a",
  robot2 = "bucket-a",

  robot3 = "bucket-b",

  robot4 = "bucket-c",
  robot5 = "bucket-c",

  robot6 = "bucket-d",
  robot7 = "bucket-d",
  robot8 = "bucket-d",
}

变成这样的东西:

inverted_user_test = {
  "bucket-a" => [robot1, robot2],
  "bucket-b" => [robot3],
  "bucket-c" => [robot4, robot5],
  "bucket-d" => [robot6, robot7, robot8],
}

想法是将桶值分组,然后使用 for_each 循环进行迭代。

我试过 transpose 但它需要一个字符串列表作为输入:

output "inverted_users_test" {
  value = transpose(var.users_test)
}
 Error: Invalid function argument
│ 
│   on buckets_policies.tf line 152, in output "inverted_users_test":
│  152:   value = transpose(var.users_test)
│     ├────────────────
│     │ var.users_test is map of string with 15 elements
│ 
│ Invalid value for "values" parameter: incorrect map element type: list of string required.

您可以使用 ellipsis (...) 运算符编写一个 for 循环:

output "inverted_users_test" {
  value = {
    for key, value in var.users_test: value => key...
  }
}

输出将是:

inverted_users_test = {
  "bucket-a" = [
    "robot1",
    "robot2",
  ]
  "bucket-b" = [
    "robot3",
  ]
  "bucket-c" = [
    "robot4",
    "robot5",
  ]
  "bucket-d" = [
    "robot6",
    "robot7",
    "robot8",
  ]
}