We are trying to create below mentioned JSON in terraform. Basically list of map objects
Currently we are trying to use for…in loop which is iterating over a list of map (i.e. list(map(string)). Can someone please share some code for dynamically generating this list using inline for loop ?
{
"MyApp": [
{
"key1": "value1" // this is the map object
},
{
"key2": "value2" // this is another map object
}
]
}
My code:
variable "my_list" {
description = ""
type = list(map(string))
default = [
{
key = key1
value = value1
},
{
key = key2
value = value2
}
]
}
event_pattern = jsonencode({
"MyApp": [ for item in my_list : item["key"] => item["value"]]
})
This is throwing me syntax error '(', ']' or if expected, got '=>'. Can you please help me get the right way to achieving this JSON.
You are using a list comprehension, not a map, so you can’t use the => mapping syntax. I think you’re asking how to create a map for each value, in which case you need to use { and } for a map literal. The final piece is probably the key value, which must be wrapped in () so that it is evaluated rather than taken as a literal value.
Together that would look like:
event_pattern = jsonencode({
"MyApp": [ for item in var.my_list : {(item["key"]): item["value"]} ]
})