try() function #40
Replies: 1 comment
-
It looks like there is already a similar behavior in the way simple expressions are evaluated. They return null in the event the expression is invalid. This allows using chained Because of this behavior of returning null for some invalid expressions, We could possibly convert erroring expressions not wrapped in |
Beta Was this translation helpful? Give feedback.
-
A mechanism is needed to access deep mapping and list values that may not exist, resulting in a default value.
I have found that the try() function in Terraform is quite robust in what it can accomplish.
It can be used to attempt to deeply access various data structures that may not exist and return the first one that does not cause an error. This can also be used for general error catching around other expressions that may fail for other reasons.
This would potentially compete with the current
contains()
functions use cases.The syntax would be
any try(&expression, &...)
, only evaluating the next expression if the previous fails. The return is the result of the first successful expression or the error of the last expression.Examples:
search({"a":1}, try(&b, `5`)
->5
search({"a":1}, try(&a, `5`)
->1
search({"a": {"b": {"c": ["x", "y", "z"]}}}, try(&a.b.c[1], "foo")
->"y"
search({"a": {"b": {"c": ["x", "y", "z"]}}}, try(&a.b.c[3], "foo")
->"foo"
search({"a": {"b": {"c": ["x", "y", "z"], "d": 7}}}, try(&a.b.c[3], &a.b.d, "foo")
->7
Beta Was this translation helpful? Give feedback.
All reactions