9

I would like to convert a simple list of string in terraform to a map with the keys as indexes.

I want to go from something like this:

locals {
  keycloak_secret = [
    "account-console",
    "admin-cli",
    "broker",
    "internal",
    "realm-management",
    "security-admin-console",
  ]
}

To something like

map({0:"account-console", 1:"admin-cli"}, ...) 

My goal is to take advantage of the new functionality of terraform 0.13 to use loop over map on terraform module.

I didn't find any solution, may something help me, thank you.

severin.julien
  • 1,314
  • 15
  • 27
  • Is there a reason you need the index here? Would you not be better off with just converting the list into a set so you can loop over it with `for_each`? – ydaetskcoR Aug 14 '20 at 15:03
  • @ydaetskcoR I didn't know it was possible. Do you have an exemple please ? I'm always trying to learn more. – severin.julien Aug 15 '20 at 10:14

2 Answers2

19

If I understand correctly, you want to convert your list into map. If so, then you can do this as follows:

locals {
  keycloak_secret_map  = {for idx, val in local.keycloak_secret: idx => val}  
}

which produces:

{
  "0" = "account-console"
  "1" = "admin-cli"
  "2" = "broker"
  "3" = "internal"
  "4" = "realm-management"
  "5" = "security-admin-console"
}
Marcin
  • 215,873
  • 14
  • 235
  • 294
1

I've come up with another solution, which is uglier than @Marcin 's answer.

locals = {
    keycloak_secret_map = for secret_name in local.keycloak_secret : index(local.keycloak_secret, secret_name) => secret_name
}

Which gives

{
  0 = "account-console"
  1 = "admin-cli"
  2 = "broker"
  3 = "internal"
  4 = "realm-management"
  5 = "security-admin-console"
}
severin.julien
  • 1,314
  • 15
  • 27
  • If you admit it's the same but uglier then what value does this answer add over the existing one? – ydaetskcoR Aug 14 '20 at 15:02
  • 5
    @ydaetskcoR So people can see that there's other way to do things. the answer is interesting because it can help you do others transformation that you wouldn't thought was possible in the first place. – severin.julien Aug 15 '20 at 10:12