Here is a sample of my json data that adequately mocks my use case.
{
"environmentName":"",
"environmentDetails1":"",
"environmentDetails2":"",
"environmentDetails3":"",
"servers":[
{
"type":"windows",
"vmName":"server1",
"cpus":1,
"ram":11111,
"diskThinProvisioned":true,
"disk":{
"diskSize":11111,
"diskLabel":"diskLabel"
},
"networks":[
{
"ipAddress":"1.1.1.1",
"netmask":"111.111.111"
}
]
},
{
"type":"linux",
"vmName":"server2",
"cpus":1,
"ram":11111,
"diskThinProvisioned":true,
"disk":{
"diskSize":11111,
"diskLabel":"diskLabel"
},
"networks":[
{
"ipAddress":"1.1.1.1",
"netmask":"111.111.111"
}
]
}
]
}
I intend on using the http
data source once I have this working but for now, I’m using the
local_file
data source to fetch my json file.
data "local_file" "getJsonFile" {
filename = "${path.module}/configData.json"
}
I have a local variable defined that will perform the decoding of my json data.
locals {
configData = jsondecode(data.local_file.getJsonFile.content)
}
Note: The data type returned from the the jsondecode results is an object
.
Next I would like to iterate over the servers array in a for_each
loop. In my json data example, I have two servers but in reality, that array may hold dozens.
Naturally, If I wanted to iterate over any collection in a for_each
loop, I would simply select my traversal object (my collection). However, If I access the servers like configData.servers
the data type is now a tuple
. From my reading and testing, you must use a map or a set of strings in a for_each loop. I’ve spent a absurd amount of time using Terraforms type conversion functions in conjunction with changing the entire format of my json data to make this work. Nothing has worked for me so far which Is why I’m reaching out here for some assistance. Any help would be greatly appreciated!
A major bonus for any insight on how to add a filter either in the local variable configData
or in the for_each loop itself where I can distinguish the different server types. For example: if server.type == "linux"
or if server.type == "windows"