Data sources, templates and provisioners
Read things Terraform does not manage with data sources, render config files with templatefile(), and use provisioners only as a last resort, with better alternatives for each case.
By the end of this lesson you'll be able to
0 of 4 completeVerified lab: the local_file data source, templatefile() and the local-exec provisioner. Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: the aws_ami lookup: explained, not run.
Cloud lab: the aws_ami lookup needs an AWS account.
Not everything your configuration needs is something it creates. The AMI to boot from, the VPC another team owns, a value in a file: Terraform reads these with data sources. This lesson also covers rendering config files from templates, and the escape hatch you should rarely open: provisioners.
Data sources
A data source is a data block. It asks a provider for information and never changes anything.
On AWS, the most common one looks up the newest Ubuntu image, so you never hard-code an AMI ID that
differs per region and goes stale:
data "aws_ami" "ubuntu" { most_recent = true owners = ["099720109477"] # Canonical, the publisher of Ubuntu filter { name = "name" values = ["ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*"] } } resource "aws_instance" "web" { ami = data.aws_ami.ubuntu.id instance_type = "t3.micro" }
Data sources are read during plan (shown as <= read) and referenced as data.<type>.<name>.<attribute>.
Other everyday ones: aws_vpc (find a VPC by tag), aws_caller_identity (the current account ID),
aws_availability_zones, and aws_secretsmanager_secret_version. The AWS one wasn't run for this
course; it needs an AWS account. The lab used the same idea with a file another process maintains:
data "local_file" "existing_ip" { filename = "${path.module}/existing-ip.txt" } locals { backends = [trimspace(data.local_file.existing_ip.content), "10.0.2.21"] }
data.local_file.existing_ip: Reading... data.local_file.existing_ip: Read complete after 0s [id=ae9de36abcad3a6a0a991a35123807b5ca805fbf]
existing-ip.txt holds 10.0.1.15, so local.backends becomes ["10.0.1.15", "10.0.2.21"]. If
the thing a data source looks for doesn't exist, the plan fails, which is a useful early check.
Templates with templatefile
Config files for servers (Nginx, systemd units, cloud-init) often depend on values Terraform knows:
IP addresses, ports, names. templatefile(path, vars) renders a template file with those values.
The convention is the .tftpl extension. Here is templates/nginx.conf.tftpl:
upstream ${app} { %{ for ip in backends ~} server ${ip}:${port}; %{ endfor ~} }
resource "local_file" "nginx" { filename = "${path.module}/out/nginx.conf" content = templatefile("${path.module}/templates/nginx.conf.tftpl", { app = "shop" backends = local.backends port = 8080 }) }
$ cat out/nginx.conf upstream shop { server 10.0.1.15:8080; server 10.0.2.21:8080; }
cat out/nginx.confcatprint a file
How the template works:
${...}inserts a value:${app}becameshop.%{ for ... }...%{ endfor }repeats the lines in between for each item.%{ if ... },%{ else }and%{ endif }work the same way.~inside a directive strips the whitespace (including the newline) on that side. Without the two tildes, the output would have blank lines around eachserverline.- Every variable the template uses must be passed in the map. A missing one fails the plan with a clear error.
A typical real use is user_data = templatefile("cloud-init.yaml.tftpl", {...}) on an EC2 instance,
so the server configures itself at first boot.
Provisioners and why to avoid them
A provisioner runs a command when a resource is created (or destroyed): local-exec on the
machine running Terraform, remote-exec over SSH on the new server, and file to copy files. The
lab ran one on a terraform_data resource (the built-in replacement for the old null_resource):
resource "terraform_data" "reload" { triggers_replace = local_file.nginx.content provisioner "local-exec" { command = "echo would reload nginx with $(wc -l < ${local_file.nginx.filename}) lines" } }
terraform_data.reload: Creating... terraform_data.reload: Provisioning with 'local-exec'... terraform_data.reload (local-exec): Executing: ["/bin/sh" "-c" "echo would reload nginx with $(wc -l < ./out/nginx.conf) lines"] terraform_data.reload (local-exec): would reload nginx with 4 lines terraform_data.reload: Creation complete after 0s [id=9b2949ed-6915-755f-7805-0163304b4bf9]
triggers_replace makes the resource (and so the command) run again whenever the Nginx config
changes. It works, so why does HashiCorp's own documentation call provisioners a last resort?
- The plan can't show what they'll do. "Run a script" is all Terraform knows.
- They aren't idempotent. They run on create, not on every apply, so later changes don't happen.
- A failure taints the resource. The next apply destroys and recreates it.
remote-execneeds network access and SSH keys from wherever Terraform runs, often your CI.
Better tools for each job:
| You want to... | Use instead |
|---|---|
| Install packages when a server boots | user_data with cloud-init |
| Ship a server already set up | An image built with Packer |
| Configure servers continuously | Ansible, or a config management tool |
| Run a database migration on deploy | Your CI/CD pipeline, after apply |
Use a provisioner only when no provider resource, image or pipeline step can do the job.
Generate an Nginx upstream from a list of servers
Read one backend IP from a file with a data source, add a second IP in a local, and render templates/nginx.conf.tftpl with an upstream block listing both on port 8080. Add a third IP and confirm the rendered file changes on the next apply.
templates/nginx.conf.tftplReveal one safe solution
$ echo "10.0.1.15" > existing-ip.txt $ terraform apply -auto-approve && cat out/nginx.conf $ # add "10.0.3.9" to local.backends, then: $ terraform apply -auto-approve && cat out/nginx.conf
echo "10.0.1.15" > existing-ip.txtechoprint text>write output to a file, replacing it
terraform apply -auto-approve && cat out/nginx.confterraforminfrastructure as codeapplymake the changes-auto-approveskip the yes prompt&&run the next command only if this one workedcatprint a file
The second render should have three server lines. If you see blank lines between them, a ~ is
missing from one of the %{ } directives.
Try it yourself
0 of 5 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
What is the difference between a resource and a data source?
Official reading for this lesson
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.