Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional chaining operation #34870

Open
tmccombs opened this issue Mar 20, 2024 · 1 comment
Open

Optional chaining operation #34870

tmccombs opened this issue Mar 20, 2024 · 1 comment
Labels
enhancement new new issue not yet triaged

Comments

@tmccombs
Copy link
Contributor

Terraform Version

1.7.2

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.

References

No response

@tmccombs tmccombs added enhancement new new issue not yet triaged labels Mar 20, 2024
@crw
Copy link
Collaborator

crw commented Mar 21, 2024

Thanks for this feature request! If you are viewing this issue and would like to indicate your interest, please use the 👍 reaction on the issue description to upvote this issue. We also welcome additional use case descriptions. Thanks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement new new issue not yet triaged
Projects
None yet
Development

No branches or pull requests

2 participants