Explaining `coalesce` Function in Terraform
The aim of this page📝 is to explain the concept of the `coalesce` function in Terraform based on the particular example of setting a default value for a variable.
1 min readSep 29, 2023
- The
coalesce
function in Terraform takes any number of arguments and returns the first one that isn't null or an empty string. - This function is useful for setting default values for variables.
- If the first argument to
coalesce
is set (i.e., it's not null or an empty string), that value will be used. - If the first argument isn’t set,
coalesce
will check the second argument, and so on, until it finds a set value. - If none of the arguments are set,
coalesce
will return null. - The concept of
COALESCE
is indeed borrowed from SQL. It's a common function in many programming languages and environments, especially those that deal with databases. The function is used to handle null or missing values, which is a common issue in data management. By providing a way to specify default values,COALESCE
helps ensure data integrity and consistency. This concept has been adapted to Terraform for similar purposes in managing infrastructure configurations.
CODE
Here is a particular example I have experienced:
locals {
latency_threshold = coalesce(var.override_latency_threshold, 300)
}
In this code:
- A local value named
latency_threshold
is being defined. - The
coalesce
function is being used to check the value ofvar.override_latency_threshold
- If
var.override_latency_threshold
is set, its value will be used forlatency_threshold
. - If
var.override_latency_threshold
isn't set,300
will be used as a default value.