1

I have a map in terraform where the keys are strings and the values are a list of strings. It looks something like:

locals {
  admin_account_ids_by_team_name = {
    "foobar" = ["12345", "67890"]
  }
}

I need to transform this into something like:

{
  "foobar-12345" = { account_id = "12345", team_name = "foobar" }
  "foobar-67890" = { account_id = "67890", team_name = "foobar" }
}

Playing around in a terraform console I've been able to get something close using: flatten([for team, account_ids in { "foobar" = ["12345", "67890"] } : [for account_id in account_ids : map("${account_id}-${team}", { account_id = account_id, team = team})]])

This however gives me:


[
  {
    "12345-foobar" = {
      "account_id" = "12345"
      "team" = "foobar"
    }
  },
  {
    "67890-foobar" = {
      "account_id" = "67890"
      "team" = "foobar"
    }
  },
]
1
  • If these values are hardcoded into your locals, you could always hardcode that other map also. Structure transformations are more useful for dynamic input variables. Commented Oct 19, 2020 at 19:08

1 Answer 1

3

I got it:

map(
  flatten([
    for team, account_ids in { "foobar" = ["12345", "67890"] } : [
      for account_id in account_ids : [ 
        "${account_id}-${team}", 
        { account_id = account_id, team = team }
      ]
    ]
  ])...
)

map() takes an even number of arguments, interpreting them as key, value, key, value, ... so the solution is to create a list of arguments and pass them all to map() at once.


Results from the console:

> map(flatten([for team, account_ids in { "foobar" = ["12345", "67890"], "zazu" = ["2468", "1357"] } : [for account_id in account_ids : [ "${account_id}-${team}", { account_id = account_id, team = team }]]])...)
{
  "12345-foobar" = {
    "account_id" = "12345"
    "team" = "foobar"
  }
  "1357-zazu" = {
    "account_id" = "1357"
    "team" = "zazu"
  }
  "2468-zazu" = {
    "account_id" = "2468"
    "team" = "zazu"
  }
  "67890-foobar" = {
    "account_id" = "67890"
    "team" = "foobar"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.