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

For setting a default value in something like Jinja2 I would use something like

Hey {{ first_name|default(“there”, true) }}

How would I achieve this in a Terraform template file?

Hi @nabarunchatterjee,

The Terraform language doesn’t have a dedicated operator for this, but there are some different options to get a similar result:

  • You can write out an explicit conditional check. This is definitely much longer, but it makes the result clear about exactly what conditions the default value should be used in, such as if first_name is null:

    Hey ${ first_name != null ? first_name : "there" }
  • If you want to use the default value when the given value is either null or an empty string, you can use the coalesce function to write that more compactly:

    Hey ${ coalesce(first_name, "there") }

One significant difference between Terraform language and Jinja2 is in the handling of undeclared variables: IIRC Jinja2 will handle an undefined first_name reference by returning an undefined value, while Terraform considers that to be an error. Therefore in order for something like the above to work, you need to make sure that first_name is always available to your template, even if it’s explicitly set to "" or null.

Thanks @apparentlymart. That was helpful.