Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform optional jsonencode properties

Tags:

json

terraform

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)

like image 969
Aaron N. Brock Avatar asked Jun 20 '26 03:06

Aaron N. Brock


1 Answers

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 })
}
like image 55
Aaron N. Brock Avatar answered Jun 21 '26 22:06

Aaron N. Brock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!