【问题标题】:Transform String = List<String> Map in Terraform在 Terraform 中转换 String = List<String> Map
【发布时间】:2020-10-20 04:28:09
【问题描述】:

我在 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"
    }
  },
]

【问题讨论】:

  • 如果这些值被硬编码到你的本地,你也可以总是硬编码其他的map。结构转换对于动态输入变量更有用。

标签: terraform


【解决方案1】:

我明白了:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 2015-11-21
    • 2021-12-21
    相关资源
    最近更新 更多