hashicorp / terraform

Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
https://www.terraform.io/
Other
42.6k stars 9.54k forks source link

add functions ifnull, ifempty, ifnullorempty, isempty, isnullorempty #34018

Open joaocc opened 1 year ago

joaocc commented 1 year ago

Terraform Version

1.6.x

Use Cases

The terraform language is quite rich and very powerful. However, for those accustomed to other similar languages, some useful functions could be added to make development life easier, and without breaking any kind of existing code. It does also allow the use of some development idioms that are currently out of bounds.

Attempted Solutions

There are workarounds for them, but they are quite verbose, force expressions to be repeated (eg, when using ?: to do a ifnull) and/or are harder to manage

Proposal

Add the following functions to the library:

References

No response

apparentlymart commented 1 year ago

Thanks for these feature requests, @joaocc.

Some of these overlap with existing functions or language features, though not perfectly in all cases:

In general I'm not a fan of features that would encourage treating null and "empty" as the same, since that seems likely to confuse the meanings of those concepts. null in Terraform represents the total absense of a value, which is intentionally a distinct idea from a non-null value that happens to be "empty" if such a concept is available for its type. This special meaning of null is important because it's how Terraform represents the value of a totally-unset argument, allowing default values to be used instead, whereas "empty values" should not be treated in that way.

There are historical inconsistencies like the coalesce function I mentioned above (which treats "" the same as null) and the default treatment of input variables (when they don't have nullable = false set), but both of those design warts are things we'd like to fix in a future language edition and doing so will become harder if we introduce more features that persist that ambiguity.

Given all that, my own version of this proposal would be:

With that said, we are also planning to introduce the ability for providers plugins to contribute their own functions to the Terraform language in a future Terraform version, and so at that point it would be possible in principle to write a provider that offers additional combinations, if you really want them. For the core language we try to focus on a single "main" usage pattern and then offer composable building blocks (as few as possible) to deal with situations that diverge from that main usage pattern, but provider developers will be able to make different design tradeoffs.