Having this input variable
variable "input_var"{
type = map(object({
str_attribute = string
num_attribute = number
sub_obj = optional(object({
id = number
other_property = string
}))
}))
}
How can I loop over all map elements and filter them while taking only the ones that complies to both sub_obj != null
and
id != 0
? And how to make it a map where I keep both the original key and value?
I have tried several things but nothing usable. Latest iteration is:
for_each = [for k,v in var.input_var: tomap({k = v}) if v.sub_obj.id !=0]
This does not work first because if sub_obj
is null an error occurs and I was unable to find any information about logical operators, like and
in this case, such that I could use it as sub_obj != null and sub_obj.id !=0
.
And second because it does not create a map, which makes sense as tomap
would create a map from all objects added as arguments.
CodePudding user response:
To construct a map
instead of a list
you should use the constructor {}
.
For a safe check on the value of var.input_var.sub_obj.id
inequality with 0, you can use the coalesce
(similar to null coalescing operators) or try
functions.
Combining the two we arrive at:
# option one
for_each = { for k,v in var.input_var: k => v if coalesce(sub_obj.id, 0) != 0 }
# option two
for_each = { for k,v in var.input_var: k => v if try(sub_obj.id != 0, false) }