How to Use Coalesce Function in Terraform: Simple Guide
In Terraform, the
coalesce function returns the first non-null value from its arguments. Use it to provide fallback values when some variables might be null or undefined.Syntax
The coalesce function takes one or more arguments and returns the first argument that is not null. If all arguments are null, it returns null.
- Arguments: One or more values or expressions.
- Returns: The first non-null argument.
terraform
coalesce(value1, value2, ..., valueN)
Example
This example shows how to use coalesce to set a variable with a fallback value if the first variable is null.
terraform
variable "primary_value" { type = string default = null } variable "fallback_value" { type = string default = "default-string" } output "result" { value = coalesce(var.primary_value, var.fallback_value) }
Output
result = "default-string"
Common Pitfalls
Common mistakes when using coalesce include:
- Passing no arguments, which causes an error.
- Expecting
coalesceto return empty strings or zero values as non-null (onlynullis skipped). - Using
coalescewith incompatible types in arguments.
Always ensure at least one argument is provided and that types match.
terraform
/* Wrong: no arguments */ output "wrong" { value = coalesce() } /* Right: at least one argument */ output "right" { value = coalesce(null, "fallback") }
Quick Reference
| Function | Description | Example |
|---|---|---|
| coalesce | Returns first non-null value | coalesce(null, "a", "b") → "a" |
| Arguments | One or more values | coalesce(val1, val2, val3) |
| Returns | First non-null or null | Returns null if all are null |
Key Takeaways
Use coalesce to pick the first non-null value from multiple options.
Always provide at least one argument to coalesce to avoid errors.
coalesce skips only null values, not empty strings or zeros.
Ensure all arguments to coalesce have compatible types.
Use coalesce to set fallback values cleanly in Terraform configurations.