I want to do something like this, but take the values from variables.
This works:
locals {
map = {
val1 = [
{
somedata = “”
}
],
val2 = [
{
somedata = “”
}
]
}
test = [for obj in local.map: try(obj.val1,"") if try(obj.val1,"")!=""]
}
But how can I do this taking val1 or val2 from the variables:
These don’t work
test = [for obj in local.map: try(obj.(var.containsval1),"") if try(obj.(var.containsval1),"")!=""]
or smth like this
test = [for obj in local.map: try(obj."${var.containsval1}","") if try(obj."${var.containsval1}","")!=""]
Hi @lukopas,
I’m not sure I fully understand what you are asking with such a contrived example but if I am understanding correctly I think you are looking for the “indexing” syntax, which allows looking up an element of a collection or attribute of an object using the value of some other arbitrary expression:
var.map[var.key]
The above, assuming that var.map
is a map and var.key
is a string, will return the value of the element of the map whose key is equal to map.key
, or raise an error if there is no such element. You can then optionally combine that with the try
function if you want to react to that error by returning some other placeholder value instead.
Data is in JSON file that I don’t see, it looks like this
[
{
“somevalue”: [
{
“stuff”: “data”,
},
{
“stuff”: “data”,
},
{
“stuff”: “data
}
]
},
{
“someothervalue”: [
{
“stuff”: “data”,
},
{
“stuff”: “data”,
},
{
“stuff”: “data
}
]
}
I need to do this (extract specific part of this json)
map= try(jsondecode(file(try(”…/terraform/configs/settings_new.json”,""))), {})
test = [for obj in local.map: try(obj.somevalue,"") if try(obj.somevalue,"")!=""]
But As i don’t know if it is somevalue or someohervalue or something else. I have it in variable
variable “CONFIG_INDEX” {
description = “value to extract string”
}
SO lets us say that CONFIG_INDEX = somevalue
So my code should look like this but it oesn’t work:
map= try(jsondecode(file(try("…/terraform/configs/settings_new.json",""))), {})
test = [for obj in local.map: try(obj.(var.CONGIF_INDEX),"") if try(obj.(var.CONFIG_INDEX),"")!=""]
How can I do something like this?
Ok I accidentally found a way
To access variable value as dot attribute you can do this
test = [for obj in local.map: try(obj[var.CONGIF_INDEX],"") if try(obj[var.CONFIG_INDEX],"")!=""]
THERE MUST BE NO DOT after loop element, otherwise it doesn’t work.
LoopElement[var.VariableContainingValue]