Convert list to map with index in Terraform

点点圈 提交于 2021-01-07 01:43:59

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/63409307/convert-list-to-map-with-index-in-terraform

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!