There are a lot of built-in functions available in Terraform to use. These built-in functions can improve your code and its readability.
So let's get started with some of the built-in functions that can be beneficial for you while writing terraform code.
1. Can Function
can function evaluates the given expression and returns a boolean value. Return value would be 'true', if the expression produces a result without any errors otherwise it will return 'false'.
The primary purpose of can function is to turn an error condition into a boolean validation result when writing custom variable validation rules.
Let's take a look at a few examples to understand the working of can function.
In both the variables mentioned in the above example, if regex produces an error, the can function will return false value and then error_message will be displayed by Terraform.
2. Try Function
try function evaluates all of its argument expressions in turn and returns the result of the first one that does not produce any errors.
Let's take an example and see the result by passing different types of value for the variable.
Case 01
Let's say we are passing the variable's value as a single string. The first expression will be evaluated successfully and it will be converted into a single-element list containing that string.
Case 02
Let's say we are passing the variable's value as a tuple/set. The first expression will produce an error. But the second expression will convert it into a list containing the elements, including the implicit type conversion, if required and possible.
Case 03
Let's say we are passing the variable's value as an object. So, the first expression will throw an error as type conversion is not possible. Then the next expression will be checked. In this case, next will also throw an error as type conversion is not possible. Then the third expression will be evaluated. In our example, it will be successful and its value will be produced as a result.
Note: If no expression produces the success result, call to "try" function will fail. So make sure, at least one expression must produce a successful result in order to use the try function.