Home > Mobile >  Parsing json in terraform locals
Parsing json in terraform locals

Time:02-06

I have another question about JSON parsing. Imagine I have this JSON:

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

I can extract all the groups like this:

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

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

Now, I’m trying to create a MAP. Each group is a key of the map and values of the maps are the different dogs in that group. So I would like to create a map like this:

afternoon = [feet] evening= [foo, bar] morning= [foo] saturday= [bar]

I'm trying with something like this and I tried several options... But I can't make it work.

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

Later on, I would like to use that map to provision some resources. Is this eventually possible?

CodePudding user response:

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 }]])
}

The value for local groups will be a list of tuples and it will look something like this:

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

Now we have to create a map from this list:

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

This will produce the following output:

my_map= {
  "afternoon" = [
    "feet",
  ]
  "evening" = [
    "foo",
    "bar",
  ]
  "morning" = [
    "foo",
  ]
  "saturday" = [
    "bar",
  ]
  •  Tags:  
  • Related