将地图列表重组为 terraform 中的一张地图

Restructure list of maps to one map in terraform

在我的 terraform 代码中,我想将以下地图列表合并为一张地图。 地图的初始列表如下所示。有没有办法做到这一点?如果没有,是否可以以某种方式在 for_each 中使用原始地图列表?据我所知,它只接受一组字符串或映射。我尝试重组它,但没有成功。

[  
  {
    "repo1" = {
      "description" = "repo1 for something"
      "enforce_branch_policies" = true
      "name" = "repo1"
    }
  }
  {
    "repo2" = {
      "description" = "repo2 for something"
      "enforce_branch_policies" = true
      "name" = "repo2"
    }
  }
]

预期地图:

{
  "repo1" = {
    "description" = "repo1 for something"
    "enforce_branch_policies" = true
    "name" = "repo1"
   }
  "repo2" = {
     "description" = "repo2 for something"
     "enforce_branch_policies" = true
     "name" = "repo2"
   }
}

这个答案假定在两张地图之间的问题中缺少 ,;否则就是语法错误。

如果你想在 for_each 元参数中使用这个结构,那么你可以注意到它是 list(map(object))) 类型。然后我们可以使用for表达式重构为适合迭代的map(object)

# assumes value is stored in local.repos; modify for your personal config code accordingly
# repo stores the `map(object)` for each element in the list
# the keys and values functions return the keys and values as lists respectively
# the [0] syntax accesses the key and value for each repo map
for_each = { for repo in local.repos : keys(repo)[0] => values(repo)[0] }

这会产生预期值:

{
  repo1 = {
    description             = "repo1 for something"
    enforce_branch_policies = true
    name                    = "repo1"
  }
  repo2 = {
    description             = "repo2 for something"
    enforce_branch_policies = true
    name                    = "repo2"
  }
}

虽然您也可以使用 toset() 函数将此处的类型从 list 转换为 set,但 return 不是 for_each 参数值。

您可以使用 the ... symbol 将列表直接扩展到 merge() 函数。

repo_map = merge(local.repo_list...)