Home > Enterprise >  How to invert and group values of a map in Terraform
How to invert and group values of a map in Terraform

Time:06-02

I'm stuck trying to convert the next map:

Variable definition:

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

Variable values:

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",
}

Into something like this:

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

The idea is to group the bucket values to afterward iterate over using a for_each loop.

I tried transpose but it needs a list of strings as input:

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.

CodePudding user response:

You could write a for loop with ellipsis (...) operator:

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

The output will be:

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