Reputation: 339
I have a module that outputs two values, key
and value
. The module contains a third value is_needed
, which is a boolean. I can run this module any number of times and get a map of the outputs. Is there a way to conditionally add values to a map based on the is_needed
boolean?
For example, I can create a map with all of the values like this:
locals {
map_of_values = tomap({
for instance in module.my_module : instance.key => instance.value
})
}
Can I create a map with only some of the values? Something akin to this pseudo-code:
locals {
map_of_needed_values = tomap({
for instance in module.my_module if is_needed: instance.key => instance.value
})
}
Upvotes: 2
Views: 2045
Reputation: 501
Yes. In fact your pseudo code is very close to the correct syntax.
locals {
map_of_needed_values = tomap({
for instance in module.my_module :
instance.key => instance.value if instance.is_needed
})
}
Here's a full block of functioning code that will help you see it all working. I was not completely sure of the structure of your module.my_module
outputs, so I guessed.
variable "my_module" {
default = {
"instance_1" = {
"key" = "hello"
"value" = "world"
"is_needed" = false
}
"instance_2" = {
"key" = "foo"
"value" = "bar"
"is_needed" = true
}
}
}
locals {
map_of_needed_values = tomap({
for instance in var.my_module :
instance.key => instance.value if instance.is_needed
})
}
output "map_of_needed_values" { value = local.map_of_needed_values }
Upvotes: 5