hashicorp / hashicorp/hcl

[Feature Request]: nullable chaining Operation

Open
#783 1 comment 2 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
5.8k
Forks
657
Avg merge
20h 36m
Merged PRs (30d)
6

Description

This is copied from https://github.com/hashicorp/terraform/issues/34870 because I think the hcl project is a better place for it.

### Use Cases

Suppose I have an optional variable like:
```terraform
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:

```terraform
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:

```terraform
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining).

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.

Contributor guide

No contributing guide indexed for this repository

Research direction

Start with the proposed nullable-chaining behavior and compare the alternatives described in the issue: a .? operator, a null-aware lookup function, or a restricted try variant. No files, tests, or entry points are named, so the first step is locating the HCL expression traversal and evaluation code. Done means selecting and specifying one consistent behavior, including how null values differ from misspelled attributes and other errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.