首页 > 解决方案 > 转换字符串 = 列表Terraform 中的地图

问题描述

我在 terraform 中有一张地图,其中键是字符串,值是字符串列表。它看起来像:

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

我需要将其转换为类似的东西:

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

玩弄terraform console我已经能够使用以下方法获得一些接近的东西: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})]])

然而,这给了我:


[
  {
    "12345-foobar" = {
      "account_id" = "12345"
      "team" = "foobar"
    }
  },
  {
    "67890-foobar" = {
      "account_id" = "67890"
      "team" = "foobar"
    }
  },
]

标签: terraform

解决方案


我得到了它:

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()接受偶数个参数,将它们解释为key, value, key, value, ...这样,解决方案是创建一个参数列表并一次将它们全部传递给map()


控制台的结果:

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

推荐阅读