Okay, take the following snippet of terraform:
variable "my_var1" {
type = string
default = null
}
variable "my_var2" {
type = string
default = null
}
output "my_out" {
value = jsonencode({
my_attribute1 = var.my_var1
my_attribute2 = var.my_var2
})
}
I'd like it such that if either my_var1 & my_var2 are not specified, they don't appear in my_out whatsoever. (I.e. the output would be {}) However instead the output is currently:
my_out = {"my_attribute1":null,"my_attribute2":null}
Is there a way to do this? (preferably without having to switch to string interpolation within json text directly)
I was able to get something working leveraging the for expression along with locals:
variable "my_var1" {
type = string
default = null
}
variable "my_var2" {
type = string
default = null
}
locals {
attributes = {
my_attribute1 = var.my_var1
my_attribute2 = var.my_var2
}
}
output "my_out" {
value = jsonencode({ for k, v in local.attributes : k => v if v != null })
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With