在 terraform locals 中解析 json

问题描述 投票:0回答:1

我有这个 JSON:

{
    "all_dogs" :[
        {
            "name": "foo", 
            "groups": ["morning", "evening"]
        }, 
        {
            "name": "bar",
            "groups": ["evening", "saturday"]
        }, 
        {
            "name": "feet", 
            "groups": ["afternoon"]
        }
    ]
}

我可以像这样提取所有组:

locals {
  all_dogs = jsondecode(file("${path.module}/dogs.json"))

  all_groups = toset(flatten(local.all_dogs.all_dogs[*].groups))
}

现在,我正在尝试创建一个地图。每个组都是地图的键,地图的值是该组中的不同狗。 所以我想创建一个这样的地图:

下午=[脚] 晚上= [富,酒吧] 早上= [富] 星期六= [酒吧]

我正在尝试这样的事情,我尝试了几种选择......但我无法让它工作。

output "ex" {
  value = flatten([
    for group in local.all_groups: [
      for dog in local.all_dogs : {
        group = group 
        dog = dog 
      }
    ]
    ]
  )
}

稍后,我想使用该地图来提供一些资源。这最终可能吗?

json terraform
1个回答
1
投票
locals {
  all_dogs = jsondecode(file("${path.module}/dogs.json"))

  groups = flatten([for d in local.all_dogs.all_dogs : [for g in d.groups : { key : g, value : d.name }]])
}

本地

groups
的值将是一个元组列表,它看起来像这样:

groups = [
  {
    "key" = "morning"
    "value" = "foo"
  },
  {
    "key" = "evening"
    "value" = "foo"
  },
  {
    "key" = "evening"
    "value" = "bar"
  },
  {
    "key" = "saturday"
    "value" = "bar"
  },
  {
    "key" = "afternoon"
    "value" = "feet"
  },
]

现在我们必须从此列表创建一个

map

output "my_map" {
  value = {
    for g in local.groups : g.key => g.value...
  }
}

这将产生以下输出:

my_map= {
  "afternoon" = [
    "feet",
  ]
  "evening" = [
    "foo",
    "bar",
  ]
  "morning" = [
    "foo",
  ]
  "saturday" = [
    "bar",
  ]
© www.soinside.com 2019 - 2024. All rights reserved.