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

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 11. About 25 minutes, intermediate. Source: https://devops.rajeev.pro/courses/terraform/11-data-sources-templates

## What you will learn

- Explain the difference between a resource and a data source
- Look up existing infrastructure, such as the latest Ubuntu AMI, with a data source
- Render a config file from a template with variables, loops and whitespace control
- Explain why provisioners are a last resort, and name a better tool for each use

> **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. <br />**Code walkthrough:** the aws_ami lookup: explained, not run. <br />**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.

> **Figure.** Left, a data source such as data aws_ami ubuntu: it reads and never creates, runs during plan, and looks up things like the latest Ubuntu AMI, an existing VPC by tag, a file or a secret, used as data.aws_ami.ubuntu.id. Middle, templatefile with nginx.conf.tftpl, a for loop over backends rendered into server lines at plan time. Right, provisioners such as local-exec and remote-exec: they run a command on create, are not shown in the plan, are not idempotent and a failure taints the resource; better are cloud-init or user_data, an image built with Packer, or Ansible afterwards.
>
> Read with data sources, generate with templates, and keep provisioners for when nothing else fits.

## 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:

```hcl
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:

```hcl
data "local_file" "existing_ip" {
  filename = "${path.module}/existing-ip.txt"
}

locals {
  backends = [trimspace(data.local_file.existing_ip.content), "10.0.2.21"]
}
```

```text
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`:

```text
upstream ${app} {
%{ for ip in backends ~}
  server ${ip}:${port};
%{ endfor ~}
}
```

```hcl
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
  })
}
```

```sh
$ cat out/nginx.conf
upstream shop {
  server 10.0.1.15:8080;
  server 10.0.2.21:8080;
}
```

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`):

```hcl
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"
  }
}
```

```text
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 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.

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

- You need: existing-ip.txt containing 10.0.1.15
- You'll have: templates/nginx.conf.tftpl

```sh
$ 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
```

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

- Read a file with `data "local_file"` and use its content in a resource.
- Write a .tftpl template with a for loop and render it with templatefile().
- Add a local-exec provisioner to a terraform_data resource and watch it run on apply.
- Change the template's input and see the provisioner run again through triggers_replace.
- Do the mini mission and keep `templates/nginx.conf.tftpl`.

## Quiz

1. What is the difference between a resource and a data source?
   - There is none
   - **A resource is created and managed by Terraform; a data source only reads something that already exists** (answer)
   - Data sources are faster resources
   Why: Data sources (data blocks) never create, change or delete anything. They look up information, such as an AMI ID or an existing VPC, for resources to use.

2. In a template, what does `%{ for ip in backends ~}` do?
   - Prints the text literally
   - **Starts a loop over backends; the ~ removes the newline after the directive so the output has no blank lines** (answer)
   - Declares a variable
   Why: Template directives use %{ }. The tilde strips whitespace on that side, which keeps generated config files tidy.

3. Why does Terraform recommend avoiding provisioners?
   - They're slow
   - **They run commands outside the plan, aren't idempotent, and a failure leaves the resource tainted; purpose-built tools do the job better** (answer)
   - They only work on Windows
   Why: Terraform can't preview or reverse what a script does. Use cloud-init or user_data, a pre-built image, or a configuration tool like Ansible instead.

## Resources

- [Data sources](https://developer.hashicorp.com/terraform/language/data-sources) (HashiCorp)
- [templatefile function](https://developer.hashicorp.com/terraform/language/functions/templatefile) (HashiCorp)
- [String templates (directives and whitespace)](https://developer.hashicorp.com/terraform/language/expressions/strings#string-templates) (HashiCorp)
- [Provisioners (and why they are a last resort)](https://developer.hashicorp.com/terraform/language/resources/provisioners/syntax) (HashiCorp)
- [aws_ami data source](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/ami) (Terraform Registry)
