Templates and templatefile
Render scripts and config files from variables with templatefile and the ${} and %{} template syntax, and skip the archived template_file data source.
Built-in functions in practiceConditionals and for expressions
Templates and templatefile
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `templatefile(path, vars)` reads a file, fills `${...}` expressions from the variables you pass, and returns a string. Common uses are user-data scripts, config files and policies.
- Template directives such as `%{ for x in xs ~} ... %{ endfor ~}` and `%{ if ... }` add loops and conditions inside the text, and `~` trims whitespace.
- The template file must exist before Terraform starts. It cannot be generated by another resource in the same run.
- For JSON or YAML output, build the data in HCL and wrap it in `jsonencode` or `yamlencode` instead of writing braces by hand.
- The old `template_file` data source comes from an archived provider with no release since 2020 and no Apple Silicon build. Use the function.
The 40-line shell script
A launch template needs a start-up script. It installs a package, writes a config file with the database address, and adds an /etc/hosts line per cache node. The first version is a heredoc inside the .tf file, with quotes escaped and $$ where the shell needs a literal dollar sign. A second environment needs three cache nodes instead of two. Now someone is editing a loop by hand in a string.
The fix is to keep the script as a real file and let Terraform fill in the blanks. That is a template, and the function is templatefile.
The syntax
A template is plain text with two special forms, both the same syntax that Terraform uses for strings everywhere:
${ expression }is replaced by the value.%{ directive }controls the output:%{ if cond }…%{ endif }and%{ for x in xs }…%{ endfor }.
The docs give this example, using ~ to trim whitespace:
%{ for addr in ip_addrs ~}
backend ${addr}:${port}
%{ endfor ~}
Called from HCL, written from the docs and not run:
user_data = templatefile("${path.module}/user-data.tftpl", {
name = "web"
hosts = [
{ ip = "10.0.1.4", name = "db" },
{ ip = "10.0.1.5", name = "cache" },
]
})
The second argument is an object, and each key becomes a variable inside the template. The docs recommend naming template files *.tftpl, though nothing requires it.
What a render looks like
To see directives behave, I wrote a tiny renderer for just ${name}, ${h.attr} and a for loop, and fed it a script like the one above. It is a stand-in, not Terraform, so it handles none of the many features the real engine has:
#!/bin/bash
echo "web" > /etc/role
echo "10.0.1.4 db" >> /etc/hosts
echo "10.0.1.5 cache" >> /etc/hosts
The template had one echo ... >> /etc/hosts line inside a %{ for h in hosts ~} loop, and the render produced one per entry. Add a third node to the list and a third line appears, with no change to the template.
Limits worth knowing
From the templatefile docs:
- The file must exist when the run starts. Functions are not in the dependency graph, so a file generated during the run cannot be read.
- The file must be valid UTF-8.
- You cannot call
templatefilerecursively from inside a template. - Variable names in the second argument must start with a letter and use letters, digits and underscores.
There is a related function from Terraform 1.9, templatestring, which the v1.9 changelog describes as like templatefile but for templates obtained dynamically, such as from a data source result. Use it when the template text is not a file.
Do not template JSON by hand
A policy document in a .tftpl file with ${} inside braces looks fine until a list is empty and leaves a trailing comma, which breaks the JSON and shows up only at apply. The docs’ advice for JSON or YAML output is to build the data in HCL and wrap it:
policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Action = ["s3:GetObject"]
Resource = "${aws_s3_bucket.logs.arn}/*"
}]
})
Same caveat: written from the docs, not run. Terraform guarantees valid JSON, and the data keeps references that the dependency graph can follow. Reserve templates for text formats without a data model, such as shell scripts, nginx configs and cloud-init.
Skip the old data source
Older guides use data "template_file" from the template provider. I looked it up. The registry shows the last release of hashicorp/template as 2.2.0, published on 8 October 2020, and its darwin builds list only amd64. The repository README says it is archived: new releases will not be published and issues are not monitored. Ned in the Cloud’s video, which this lesson clips, explains the difference in its first half, from 2021. On Apple Silicon the old provider cannot be installed at all, since there is no arm64 build. For any new code, use the function. The OpenTofu registry mirrors providers, but I did not check what it offers for template.
Where templates cause trouble
- Secrets in rendered text. User-data is stored in the launch template and often visible in the console. Fetch secrets at boot from a secret store instead of rendering them in.
- Long scripts. If a template grows past a screen, the thing it configures probably wants a proper configuration tool. This is where Ansible, from the devops roadmap, earns its place.
- Hidden changes. The rendered string is part of the resource. Edit the template and the plan shows a change to the rendered argument, which for user-data may mean replacing instances.
About the video
The embed is the second half of Ned in the Cloud’s “Using templatefile in Terraform”, February 2021, from “Templatefile syntax” to just before the outro (14:10 to 20:30). The first half covers the old template_file data source, which I cut. The video is nearly six years old. The function has not changed in the parts the docs describe, but the other points in this lesson, the archived provider and the 1.9 function, are mine and not in the video. English was judged from title, channel and an English auto-caption track.
Where this fits
So far everything Terraform used came from you. The next lesson reads things that already exist in the world: data sources.
Check yourself
Why can't `templatefile` read a file that another resource in the same configuration writes?
Functions are not part of the dependency graph. The docs say the file must exist on disk when the run starts, so a file generated during the run cannot be used.
You render a JSON policy with `templatefile`. What is a safer way to produce it?
Build the structure in HCL and pass it to `jsonencode(...)`. The docs recommend that over hand-written braces and commas, which easily produce invalid JSON.
What does the `~` in `%{ for h in hosts ~}` do?
It trims whitespace and the newline next to the directive, so each loop iteration renders as one clean line instead of leaving blank lines.
A tutorial uses `data "template_file"`. What do you do?
Replace it with `templatefile(...)`. The template provider is archived, its last release was in 2020, and it publishes no darwin_arm64 build.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.