How to use terraform's coalesce() function

2 min read | by Jordi Prats

Terraform's coalesce() function can com handy when we have optional arguments coming from several sources and we want to pick one using some preference.

This function can take any number of arguments, returning the first that isn't null or an empty string. We can test it out using terraform console:

$ echo 'coalesce(null, "", "test")' | terraform console
"test"

We can also use coalesce to pick the first non-empty string out of a list using the ... operator as follows:

$ echo 'coalesce([null, "", "test" ]...)' | terraform console
"test"

We just need to tale into account that all of the arguments must be of the same type. With any mismatched arguments, terraform will try to convert them to the most general of the types:

$ echo 'coalesce([1, "test" ]...)' | terraform console
"1"

If it's unable to convert it's types it will return an error as follows:

$ echo 'coalesce([["example"], "test" ]...)' | terraform console
╷
│ Error: Error in function call
│ 
│   on <console-input> line 1:
│   (source code not available)
│ 
│ Call to function "coalesce" failed: all arguments must have the same type.
╵

Posted on 10/03/2022

Categories