Terraform template conditional

Hi @lethargosapatheia,

The important thing to notice here is that in Terraform templates there are two separate “parsing modes”:

The parser starts in literal mode where anything you’ve written is taken as a literal string to include directly in the output. When it encounters the ${ sequence, which represents string interpolation, it changes to expression parsing mode where the syntax is exactly the same as you’d use when assigning a value to an argument inside a resource block (for example).

The %{ sequence is also valid only in the literal mode, because it’s a template language marker rather than an expression marker. A template for sequence is for repeated string concatenation, which is not suitable for describing elements of an object as you are doing inside this yamlencode call.

I think the expression language equivalent of what you wrote here would be to set the write_files attribute to be the result of the concat function, building a list from multiple parts. Then your first argument to concat will be the list of unconditional elements, while your second argument will be a conditional expression (the condition ? result : result syntax) which chooses between a list with one element or a list with zero elements, to decide dynamically whether to include that last item.

1 Like