Templates and structured encoding
Render a readable inventory with template directives
Use interpolation for individual values and template directives when the text itself needs a choice or repetition. This fictional inventory produces a status line and a line for each service. It does not configure any external system.
variable "enabled" { type = bool default = true}
variable "services" { type = list(string) default = ["catalog", "billing"]}
output "report" { value = <<-REPORT Status: %{ if var.enabled }enabled%{ else }disabled%{ endif } %{ for service in var.services ~} - ${service} %{ endfor ~} REPORT}With defaults, the expected text is Status: enabled\n- catalog\n- billing\n. With an empty service list, only the status line remains. Changing enabled to false changes the status label, not the list. The if directive selects a text branch; the for directive visits each list item and joins the rendered fragments into one string. A for expression that constructs a collection is a separate concept covered in the next chapter.
Understand whitespace and empty input
A tilde immediately inside a template marker trims nearby literal whitespace: an opening-side marker affects the preceding text; a closing-side marker affects the following text. This matters when an otherwise invisible newline changes a generated document.
"A %{~ if true }B%{ endif }" # AB"%{ if true ~} X%{ endif }" # XThe first removes the space after A; the second removes the space before X. Trim markers do not remove arbitrary whitespace from computed values. In the inventory fixture, the closing-side markers on the loop opening and ending prevent extra blank lines around the iteration. Preserve the newline after each service. For meaningful indentation or exact bytes, test the escaped output, including an empty collection.
Move a longer template to a separate file
When text is easier to edit separately, keep a reviewed UTF-8 file beside the module. Create summary.tftpl with these two lines and a final newline:
Service: ${service}Owner: ${owner}Then use a separate main.tf:
variable "owner" { type = string default = "team-blue"}
output "summary" { value = templatefile("${path.module}/summary.tftpl", { service = "catalog" owner = var.owner })}The predicted string is Service: catalog\nOwner: team-blue\n. path.module identifies the module directory; the object passed as the second argument supplies the template's named inputs. A file template cannot directly see arbitrary var or local references from the caller. Supply what it needs. templatefile reads a file already present when Terraform starts, not one created by a resource during the same run. A missing file, invalid UTF-8 or missing template variable can fail evaluation. The function returns text; it does not write a file or execute its contents.
Encode data rather than hand-building JSON or YAML
For a machine-readable document, begin with a Terraform value. Encoding functions handle quotation and delimiters for you. The following two outputs describe the same fictional tags in different formats:
locals { tags = { owner = "team-blue" note = "label: \"catalog\"" }}
output "tags_json" { value = jsonencode(local.tags)}
output "tags_yaml" { value = yamlencode(local.tags)}The expected JSON document, shown in a readable key order, is:
{ "note": "label: \"catalog\"", "owner": "team-blue"}JSON encoding returns compact text. YAML encoding produces YAML text representing the same two strings. Judge the result by parsing the document and comparing its fields, not by assuming an exact YAML layout or relying on object-key order. Numbers and booleans remain corresponding data values when encoded as such. Some distinctions between Terraform collection types disappear after conversion, so encoding and decoding are not a promise of exact type identity. Use the format required by the consumer.
Choose the safest representation
For a single label, use interpolation. For a small human-readable report, use an inline template. For a longer report shared across calls, use a reviewed file template. For a JSON or YAML data contract, prefer the encoder directly unless the surrounding document actually requires a separate template.
An incorrect approach is to concatenate quoted input into JSON by hand. A name containing a quotation mark or newline may break that document. Encoding a map avoids that syntax problem, but does not validate the consumer's schema or sanitize input for a shell, SQL query or HTML page. Never execute rendered text as code or expose credentials in a template output. Rendering may happen as its inputs become known during evaluation, rather than at a fixed source-file execution step. Practice with the two tags and an empty inventory, then continue to collections and for expressions. All examples are predictions awaiting runtime verification.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Templates and structured encoding — knowledge check
Check text rendering and encoding behavior.
What does a template for directive produce?
What does an empty service list produce when enabled is false?
When must a templatefile input file exist?
Which function safely serializes a Terraform object to JSON text?
Does valid encoded JSON guarantee that a remote application accepts the data?