Reputation: 79
I was wondering if someone could help me munge some terraform data :) I am querying an API and getting back a response like this once I pass it through jsonencode:
api_response = [
{
description = "vnet-01"
site = {
id = 24
name = "Azure - northeu"
}
id = 2291
prefix = "10.10.160.0/24"
},
{
description = "vnet-01"
site = {
id = 24
name = "Azure - northeu"
}
id = 2311
prefix = "10.10.161.0/24"
},
{
description = "vnet-02"
site = {
id = 24
name = "Azure - westeu"
}
id = 2310
prefix = "10.20.168.0/21"
},
]
So essentially, I get back a list(map(object)).
What I really want to do here is to take the API response and parse it out into a local that will be easier to handle, as I will be using this data to create resources and also make further API calls down the line. I'd basically like to create something like this map(object) format below:
prefix_info = {
"vnet-01" = {
address_space = ["10.180.160.0/24","10.180.161.0/24"]
site_name = "Azure - northeu"
}
"vnet-02" = {
address_space = ["10.180.168.0/21"]
site_name = "Azure - westeu"
}
}
It would be nicer to have a single map of objects, but if necessary this could be split out into multiple locals (for instance, I don't know but appending a new prefix to the list of prefixes could be a challenge whilst also keeping the site consistent?)
I've read various things with for_each / dynamics etc. and also used them previously when creating resources, but those constructs aren't really available to me when trying to assign locals (to the best of my knowledge, at least).
Upvotes: 0
Views: 2402
Reputation: 5822
locals {
prefix_info = {for response in local.api_response: response["description"] => { "address_space": [response["prefix"]], "site_name": response["site"]["name"] }}
}
EDIT:
God it's ugly, but this is not exactly the kind of thing HCL excels at:
prefix_info1 = { for response in local.api_response : response["description"] => response... }
prefix_info2 = { for name, ls in local.prefix_info1 : name => { "address_space" : [for obj in ls : obj["prefix"]], "site_name" : distinct([for obj in ls : obj["site"]["name"]]).0 } }
Upvotes: 0