How to set a default value for a variable in a Terraform template?

The top-level variables are statically checked because otherwise Terraform would give poor feedback about typos in the common case, and we saw this cause people confusion during early use of templatefile.

However, if you assign an object value into one of your template variables then you can use all of the usual tricks to concisely deal with attributes being null or being absent completely, such as the coalesce and try functions. This is similar to how in a normal Terraform configuration file you can’t refer to a variable that wasn’t declared, but you can dynamically test if a nested attribute of that variable is set.

The design of this part of Terraform prioritizes the common case of relatively simple templates with a fixed set of variables that are always used. For more complex situations you can use nested objects as an escape hatch.

1 Like