-
Notifications
You must be signed in to change notification settings - Fork 642
Description
This is copied from hashicorp/terraform#34870 because I think the hcl project is a better place for it.
Use Cases
Suppose I have an optional variable like:
variable "test" {
type = object({
field1 = string
# and some other fields
})
default = null
)and then somewhere else I need to use use the value of var.test.field, but use a default value of var.test is null.
I would like to be able to do something like:
something = coalesce(var.test?.field1, "default") # the default may actually depend on other variables
Attempted Solutions
I can of course do something like:
something = var.test != null ? var.test.field1 : "default"but that is awkward and hard to read. It becomes even more so if there are multiple levels of possibly null objects that need to be traversed, especially since && isn't short circuiting.
Another option is to use try:
something = try(var.test.field1, "default")the problem with this is that if I misspell something in var.test.field1, it will silently use the default instead of giving me an error.
Proposal
Add a .? operator similar to javascript's optional chaining feature.
Or maybe add a function like lookup, except use the default value if the first argument is null.
Or have a variant of try that will still fail for any other error than trying to look up a field on a null value.