Combine multiple map in 1 map with list inside, with if statement [SOLVED]

Hi, im trying to make it possible to assign multiple users to 1 role in AWS using terraform, what im now have is below,

test6 = [
    {
        user_arn  = (known after apply)
        user_name = "admin-user-01"
        user_role = "admin_group_role"
    },
    {
        user_arn  = (known after apply)
        user_name = "admin-user-01"
        user_role = "support_group_role"
    },
    {
        user_arn  = (known after apply)
        user_name = "support-user-01"
        user_role = "support_group_role"
    },

now i need to make it look like

another_list = [
{
        user_role = "admin_group_role"
        user_arns = [("a list of only admin-user's arns")]
},
{
        user_role = "support_group_role"
        user_arns = [("a list of support's + admins arns")]
}

Should be doable, but im new into the terraform, and im struggling with it for 2 days already ;PP , so any help will be appreciated.

I guess you could do something complicated with flatten and distinct - here is a simplified model, omitting the references to (known after apply) values:

locals {
  test6 = [
    {
      user_name = "admin-user-01"
      user_role = "admin_group_role"
    },
    {
      user_name = "admin-user-01"
      user_role = "support_group_role"
    },
    {
      user_name = "support-user-01"
      user_role = "support_group_role"
    }
  ]

  combined = [for role in distinct([for entry in local.test6 : entry["user_role"]]) :
    {
      user_role = role,
      user_names = flatten([for entry in local.test6 :
        entry["user_role"] == role ? [entry["user_name"]] : []
      ])
    }
  ]
}
$ terraform console
> local.combined
[
  {
    "user_names" = [
      "admin-user-01",
    ]
    "user_role" = "admin_group_role"
  },
  {
    "user_names" = [
      "admin-user-01",
      "support-user-01",
    ]
    "user_role" = "support_group_role"
  },
]

This kind of thing is probably fine if your number of users and groups will remain small, but beware it scaling poorly if you move towards hundreds/thousands of users/groups.

It’s also pretty non-intuitive to read.

You might do better pre-processing or redefining your input to terraform into something more like

{
  "admin_group_role" = [
    "admin-user-01",
  ]
  "support_group_role" = [
    "admin-user-01",
    "support-user-01",
  ]
}

which could drive simpler code on the Terraform side.

1 Like

Nice, it works perfectly, thank you very much.