DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

TerraformLesson 11 of 17
Your progress · 0%
On this page
  1. Data sources
  2. Templates with templatefile
  3. Provisioners and why to avoid them
↖ Course roadmap
Lesson 11 · Data sources & templates

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.

25 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 4 complete
Lab status

Verified 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.

Read with data sources, generate with templates, and keep provisioners for when nothing else fits.© Diagram: DevOps Academy

Read with data sources, generate with templates, and keep provisioners for when nothing else fits.© Diagram: DevOps Academy

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.conf
  • catprint a file

How the template works:

  • ${...} inserts a value: ${app} became shop.
  • %{ 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 each server line.
  • 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?

  1. The plan can't show what they'll do. "Run a script" is all Terraform knows.
  2. They aren't idempotent. They run on create, not on every apply, so later changes don't happen.
  3. A failure taints the resource. The next apply destroys and recreates it.
  4. remote-exec needs 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 bootsuser_data with cloud-init
Ship a server already set upAn image built with Packer
Configure servers continuouslyAnsible, or a config management tool
Run a database migration on deployYour CI/CD pipeline, after apply

Use a provisioner only when no provider resource, image or pipeline step can do the job.

⌘
Mini mission

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.

Input: existing-ip.txt containing 10.0.1.15Output: templates/nginx.conf.tftpl
Reveal 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.txt
  • echoprint text
  • >write output to a file, replacing it
terraform apply -auto-approve && cat out/nginx.conf
  • terraforminfrastructure as code
  • applymake the changes
  • -auto-approveskip the yes prompt
  • &&run the next command only if this one worked
  • catprint 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 done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 3

What is the difference between a resource and a data source?

Go deeper

Official reading for this lesson

  • DocsData sourcesHashiCorp ↗
  • Docstemplatefile functionHashiCorp ↗
  • DocsString templates (directives and whitespace)HashiCorp ↗
  • DocsProvisioners (and why they are a last resort)HashiCorp ↗
  • Docsaws_ami data sourceTerraform Registry ↗

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.

← PreviousModules: reusable infrastructureNext lesson →Environments: workspaces or folders