Whitespace stripping behavior in Terraform template directives

Putting a tilde (~) at the beginning or end of Terraform template directives "consumes" whitespace. For example:

Users:
%{ for name in users ~}
${name},
%{~ endfor ~}

If users = ["alice", "bob"], this results in:

Users:
alice,bob,

While simple in theory, it can also be a little difficult to work with in practice. For example, if we add a space before ${name} like this:

Users:
%{ for name in users ~}
 ${name},
%{~ endfor ~}

Then the result is:

Users:
 alice, bob,

You might expect the ~ at the end of %{ for name in users ~} to strip the space before ${name}, but it doesn't. This is because the ~ ONLY affects whitespace adjacent to the directive itself--not the whitespace inside the content lines.

Great, are empty lines also considered content lines then?

Users:
%{ for name in users ~}
 ${name},
%{~ endfor ~}



There should be 3 empty lines above me.

Nope, this results two empty lines following the ~}.

Users:
 alice, bob,


There should be 3 empty lines above me.

That's because Terraform treats empty lines differently than other content, and removes ONLY the first empty line immediately before/after the directive.

TL;DR


References