Across the three previous lessons you have deployed EcoMarket on AWS, Azure and Google Cloud. There is a network, a database, an images bucket, a load balancer and instance groups that boot and register themselves. And yet the platform does not serve a single order, because the last piece is missing: nobody has installed the application on those machines yet. This lesson closes that gap, and it does so by first asking the right question, which is not "how do I install the application from Terraform?" but "should I install it from Terraform?".

The short answer is no, almost never. Terraform is a provisioning tool: it creates, modifies and destroys infrastructure resources, and its model is declarative and convergent. Installing packages, copying files and starting services inside a machine is configuration, a different problem with tools of its own. The boundary between the two is this lesson's real subject, and understanding it properly avoids an entire category of fragile code that works on day one and fails on day two.

  1. The boundary between provisioning and configuring

They are two problems with different properties, and it helps to see them side by side:

Provisioning (Terraform) Configuring (cloud-init, Ansible, Packer)
Object Infrastructure resources: networks, disks, databases The inside of a machine: packages, files, services
Model Declarative with state: it knows what exists and computes the diff Declarative without state (Ansible) or imperative (a script)
Who knows the real state Terraform, in its tfstate Nobody remembers: it is checked at run time
Idempotence Guaranteed by the provider Depends on how you write each task
Visibility of the change The plan, before applying None beforehand, except Ansible's dry-run mode
Typical frequency Weeks or months Days or hours
What happens if it fails halfway Partial state, tainted resources A machine in an indeterminate state

The row that decides everything is the third. Terraform knows what it created because it has it written down in the state. When you run a script inside a machine, Terraform does not know what that script did, cannot check whether it is still true and cannot plan a change on top of it. All it records is "I ran something, and it did not error".

Hence HashiCorp's official recommendation, worth quoting literally because it is unusually blunt for product documentation:

"Provisioners are a Last Resort. […] we recommend trying to solve your problem with other techniques first, and use provisioners only if there is no other option."

It does not say "avoid them if you can": it says they are a last resort and that you should try other techniques first. This lesson teaches what those other techniques are, and only afterwards the provisioners, with their risks stated up front.

  1. The four strategies, and when to use each

flowchart TB
    Q{"How does the application<br/>reach the machine?"}

    Q --> A["<b>1. Prebuilt image</b><br/>Packer / golden AMI<br/><i>Everything already installed</i>"]
    Q --> B["<b>2. user_data / cloud-init</b><br/>A script at boot<br/><i>Terraform passes it in</i>"]
    Q --> C["<b>3. Configuration management</b><br/>Ansible, Chef, Puppet<br/><i>Afterwards, from outside</i>"]
    Q --> D["<b>4. Provisioners</b><br/>remote-exec, file<br/><i>Terraform logs in over SSH</i>"]

    A --> A1["Boot: seconds<br/>Idempotent: yes<br/>Reproducible: fully"]
    B --> B1["Boot: minutes<br/>Idempotent: only at creation<br/>Reproducible: high"]
    C --> C1["Boot: +minutes<br/>Idempotent: yes<br/>Reproducible: high"]
    D --> D1["Boot: +minutes<br/>Idempotent: NO<br/>Reproducible: low"]

    style A fill:#dcfce7,stroke:#16a34a
    style B fill:#dbeafe,stroke:#2563eb
    style C fill:#fef3c7,stroke:#d97706
    style D fill:#fee2e2,stroke:#dc2626
Strategy When it is the right one When it is not Adoption cost
1. Prebuilt image (Packer) Production, auto scaling, fast boots, regulated environments When starting a project; if the application changes hourly High: an image build pipeline
2. user_data / cloud-init Light configuration: installing an agent, mounting a disk, downloading the artefact and starting it Complex logic, dependencies between machines, later reconfiguration Low: it is just a file
3. Ansible or another configuration tool Heterogeneous fleets, continuous reconfiguration, long-lived servers Ephemeral instances born and killed by auto scaling Medium: an inventory and an execution flow
4. Terraform provisioners A registry with no API, an exit operation on destroy, a one-off test Anything the other three can do Low to write, very high to maintain

The combination EcoMarket uses in production is 1 + 2: an image built with Packer that already carries the system, the runtime, the monitoring agent and the application, plus a minimal user_data that only injects environment-specific configuration (which database to connect to, which bucket to use). Boot time drops from three minutes to twenty seconds, and that number matters: it is how long auto scaling takes to respond to a traffic peak.

In dev, while iterating, strategy 2 on its own is enough and does not require setting up an image pipeline. That is the path this lesson takes.

  1. What cloud-init is and how the three clouds consume it

cloud-init is the de facto standard for initialising cloud instances. It is a package preinstalled on practically every official Linux image (Ubuntu, Debian, Amazon Linux, RHEL, SUSE), it runs on first boot, reads the configuration from the cloud's metadata service and applies it.

The important part: it is the same program in all three clouds. What changes is the name of the attribute you use to pass it the configuration.

Cloud Resource attribute Encoding Size limit
AWS user_data (or user_data_base64) Plain text or base64 16 KB
Azure custom_data Always base64 64 KB
GCP metadata.user-data (cloud-config) or metadata_startup_script (script) Plain text 256 KB

AWS's 16 KB limit is the most restrictive and it is reached sooner than you would think. The fix when you exceed it is not to compress the script: it is to have the script download what it needs from a bucket, which is better design anyway.

And a warning about GCP, which has two distinct mechanisms that get confused:

# GCP, option A: startup script (NOT cloud-init, a script Google runs)
resource "google_compute_instance" "web" {
  metadata_startup_script = file("${path.module}/templates/startup.sh")
}

# GCP, option B: real cloud-init, through the user-data key
resource "google_compute_instance" "web" {
  metadata = {
    user-data = file("${path.module}/templates/cloud-config.yaml")
  }
}

metadata_startup_script is run by Google's guest agent on every boot, not just the first. user-data with #cloud-config is processed by cloud-init with the standard semantics. If you want portability between clouds, use option B.

And the detail that surprises most people: cloud-init runs once, on the instance's first boot. Rebooting the machine does not run it again. Changing the user_data of an existing instance does nothing, unless it is recreated, which is what section 7 is about.

  1. The #cloud-config format in depth

A #cloud-config file is YAML with a magic first line. cloud-init identifies the format by that line, so if it is missing, the file is silently ignored, one of the most frustrating failures to debug.

Here is ecomarket-web's boot configuration, with all the relevant modules:

#cloud-config
# ↑ THIS LINE IS MANDATORY AND MUST BE FIRST. Without it, nothing happens.

# 1. Refresh the package index and the installed packages.
package_update: true
package_upgrade: false      # true adds several minutes to the boot

# 2. Install whatever is needed.
packages:
  - postgresql-client-16
  - jq
  - unzip
  - ca-certificates

# 3. Create users with no password, key access only.
users:
  - name: ecomarket
    gecos: "Application service user"
    shell: /usr/sbin/nologin      # cannot log in: it is a service user
    system: true
    lock_passwd: true

# 4. Write configuration files.
write_files:
  - path: /etc/ecomarket/app.env
    owner: root:ecomarket
    permissions: '0640'           # not even world-readable
    content: |
      ECOMARKET_ENVIRONMENT=dev
      ECOMARKET_DB_HOST=ecomarket-dev-postgres.abc123.eu-west-1.rds.amazonaws.com
      ECOMARKET_DB_PORT=5432
      ECOMARKET_DB_NAME=ecomarket
      ECOMARKET_BUCKET=ecomarket-dev-images-brave-otter
      ECOMARKET_REGION=eu-west-1
      ECOMARKET_DB_SECRET=ecomarket-dev/db/master

  - path: /etc/systemd/system/ecomarket-web.service
    owner: root:root
    permissions: '0644'
    content: |
      [Unit]
      Description=EcoMarket Web
      After=network-online.target
      Wants=network-online.target

      [Service]
      Type=simple
      User=ecomarket
      EnvironmentFile=/etc/ecomarket/app.env
      ExecStart=/opt/ecomarket/bin/ecomarket-web
      Restart=always
      RestartSec=5

      [Install]
      WantedBy=multi-user.target

# 5. Run commands, in order, at the end.
runcmd:
  - [ mkdir, -p, /opt/ecomarket ]
  # The artefact is downloaded from the bucket using the instance ROLE.
  # No credentials: the role from 05-02 already grants read access.
  - aws s3 cp s3://ecomarket-dev-artifacts/web/v2.4.1.tar.gz /tmp/app.tar.gz
  - tar -xzf /tmp/app.tar.gz -C /opt/ecomarket
  - chown -R ecomarket:ecomarket /opt/ecomarket
  - systemctl daemon-reload
  - systemctl enable --now ecomarket-web

# 6. What to do when it finishes.
final_message: "EcoMarket web ready after $UPTIME seconds"

The most-used cloud-init modules, with their behaviour:

Module What for Notes
package_update / package_upgrade Refreshing indexes and upgrading package_upgrade: true can add minutes to the boot
packages Installing packages Uses the distribution's package manager. Fails if the repository is unreachable
users Creating users and keys lock_passwd: true and shell: /usr/sbin/nologin for service users
write_files Writing files Supports encoding: b64 or gzip+base64 for binaries
runcmd Commands at the end of the first boot List or string form. It runs only once
bootcmd Commands very early, on every boot For things that must always happen, such as mounting an ephemeral disk
disk_setup / mounts Partitioning and mounting disks Preferable to doing it with runcmd
ca_certs Adding your own certificate authorities Common in companies with TLS inspection
power_state Shutting down or rebooting at the end Useful in image build pipelines

Two differences worth nailing down, because they are constantly confused:

  • runcmd runs once (on the first boot); bootcmd runs on every boot, and very early. Mounting an ephemeral disk goes in bootcmd; installing the application, in runcmd.
  • write_files happens before runcmd, so you can write a script and run it afterwards. It is a clean pattern for long logic:
write_files:
  - path: /usr/local/bin/prepare-ecomarket.sh
    permissions: '0755'
    content: |
      #!/usr/bin/env bash
      set -euo pipefail
      # ... thirty lines of readable logic, with error handling
runcmd:
  - /usr/local/bin/prepare-ecomarket.sh

  1. Generating the script with templatefile() and Terraform values

The file in the previous section has hand-written values that Terraform already knows: the PostgreSQL endpoint, the bucket name, the environment. Writing them by hand is exactly what this course has spent five modules avoiding. The templatefile() function, which you know from 04-02, injects them:

# modules/app/main.tf
locals {
  startup_configuration = templatefile("${path.module}/templates/cloud-config.yaml.tftpl", {
    environment      = var.environment
    region           = var.region
    db_host          = var.db_endpoint         # from module.data.endpoint
    db_port          = 5432
    db_name          = "ecomarket"
    bucket           = var.bucket_id           # from module.data.bucket_id
    db_secret        = var.db_secret_name      # the NAME, not the value
    app_version      = var.app_version
    artifacts_bucket = var.artifacts_bucket
  })
}

And the template, with the placeholders:

#cloud-config
package_update: true

packages:
  - postgresql-client-16
  - jq

write_files:
  - path: /etc/ecomarket/app.env
    owner: root:ecomarket
    permissions: '0640'
    content: |
      ECOMARKET_ENVIRONMENT=${environment}
      ECOMARKET_REGION=${region}
      ECOMARKET_DB_HOST=${db_host}
      ECOMARKET_DB_PORT=${db_port}
      ECOMARKET_DB_NAME=${db_name}
      ECOMARKET_BUCKET=${bucket}
      # The NAME of the secret, not its value. The app resolves it with its role.
      ECOMARKET_DB_SECRET=${db_secret}

  - path: /usr/local/bin/start-ecomarket.sh
    permissions: '0755'
    content: |
      #!/usr/bin/env bash
      set -euo pipefail

      # The password is read HERE, on the machine, with the instance's
      # identity. It never travels in the user_data.
      PASSWORD=$(aws secretsmanager get-secret-value \
        --secret-id "$ECOMARKET_DB_SECRET" \
        --query SecretString --output text | jq -r .password)

      export PGPASSWORD="$PASSWORD"
      psql -h "$ECOMARKET_DB_HOST" -U ecomarket -d ecomarket -c 'SELECT 1' >/dev/null
      echo "PostgreSQL connection verified"

runcmd:
  - mkdir -p /opt/ecomarket
  - aws s3 cp s3://${artifacts_bucket}/web/${app_version}.tar.gz /tmp/app.tar.gz
  - tar -xzf /tmp/app.tar.gz -C /opt/ecomarket
  - systemctl daemon-reload
  - systemctl enable --now ecomarket-web

And the same content served to the three clouds, which is where the value of using standard cloud-init shows:

# AWS
resource "aws_launch_template" "web" {
  user_data = base64encode(local.startup_configuration)
}

# Azure
resource "azurerm_linux_virtual_machine_scale_set" "web" {
  custom_data = base64encode(local.startup_configuration)
}

# GCP
resource "google_compute_instance_template" "web" {
  metadata = {
    user-data = local.startup_configuration
  }
}

One template, three clouds. That is the practical argument for using #cloud-config instead of a shell script in each provider's own style.

Three templatefile() details that bite with YAML:

  1. The shell's $ clashes with interpolation. Inside the template, ${VARIABLE} belongs to Terraform. To get a literal $ into the file, escape it by doubling the dollar: $${VARIABLE}. In the example above, $ECOMARKET_DB_SECRET works because it has no braces; if it did, you would have to write $${ECOMARKET_DB_SECRET}.
  2. YAML indentation is significant and a multi-line interpolation breaks it. If you insert a multi-line value inside an indented block, use indent(): ${indent(6, content)}.
  3. Validate the result before applying. Malformed YAML makes cloud-init ignore it silently:
# Render the template without applying anything
terraform console <<< 'templatefile("modules/app/templates/cloud-config.yaml.tftpl", {
  environment = "dev", region = "eu-west-1", db_host = "x", db_port = 5432,
  db_name = "ecomarket", bucket = "b", db_secret = "s",
  app_version = "v1", artifacts_bucket = "a"
})' > /tmp/rendered.yaml

# Check that it is valid YAML
python3 -c "import yaml,sys; yaml.safe_load(open('/tmp/rendered.yaml'))" && echo "YAML OK"

# And, better still, validate it with cloud-init itself
cloud-init schema --config-file /tmp/rendered.yaml

That last command is the one that deserves a place in your workflow: cloud-init schema validates the file against the official schema and tells you exactly which key is wrong. It can be run in the pipeline.

  1. Why secrets never travel in user_data

This section is the most important in the lesson in security terms.

Security warning. Never put a secret in user_data, custom_data or an instance's metadata. This is not a debatable best practice: it is direct exposure, by two simultaneous routes.

Route 1: metadata is readable from inside the machine, by any process.

# AWS, from inside the instance (IMDSv2)
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 60")
curl -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/user-data

# Azure
curl -H "Metadata:true" \
  "http://169.254.169.254/metadata/instance/compute/customData?api-version=2021-02-01"

# GCP
curl -H "Metadata-Flavor: Google" \
  http://metadata.google.internal/computeMetadata/v1/instance/attributes/user-data

Any process on the machine can make those requests: the application, a poorly isolated container, a process compromised through a vulnerability, an intern with read access. In AWS, moreover, it is also on disk: /var/lib/cloud/instance/user-data.txt.

Route 2: it ends up in Terraform's state and in the plan.

The user_data attribute is part of the resource, so it is in the tfstate in the clear, as you have known since 03-01. And it is in the plan.tfplan file you save with -out. Whoever can read the state, reads the secret.

The correct pattern, in all three clouds: user_data carries the REFERENCE, the machine resolves the VALUE with its identity.

flowchart LR
    TF["Terraform"] -->|"user_data:<br/>the secret's name<br/><b>not its value</b>"| VM["Instance"]
    TF -->|"creates"| ID["Role / managed<br/>identity /<br/>service account"]
    ID -.->|"attached"| VM
    VM -->|"1. obtains temporary<br/>credentials"| MD["Metadata"]
    VM -->|"2. requests the secret<br/>with those credentials"| SEC[("Secrets Manager /<br/>Key Vault /<br/>Secret Manager")]
    SEC -->|"3. value"| VM

    style SEC fill:#dcfce7,stroke:#16a34a
    style TF fill:#dbeafe,stroke:#2563eb

And the code, one per cloud, that the instance runs at boot:

# AWS — with the instance role from 05-02
PASSWORD=$(aws secretsmanager get-secret-value \
  --secret-id "ecomarket-dev/db/master" \
  --query SecretString --output text | jq -r .password)

# Azure — with the managed identity from 05-03
TOKEN=$(curl -s -H "Metadata:true" \
  "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://vault.azure.net" \
  | jq -r .access_token)
PASSWORD=$(curl -s -H "Authorization: Bearer $TOKEN" \
  "https://ecomarket-dev-kv.vault.azure.net/secrets/password-postgres?api-version=7.4" \
  | jq -r .value)

# GCP — with the service account from 05-04
PASSWORD=$(gcloud secrets versions access latest --secret=ecomarket-dev-db-password)

None of the three snippets contains a credential. The instance authenticates with the identity you gave it in the previous lessons, and that identity has permission to read exactly that secret and nothing else. It is the whole reason for the IAM work in 05-02, 05-03 and 05-04, and it goes deeper in Security Best Practices.

There is a partial exception worth knowing so it is not mistaken for a permission: an SSH public key can go in the metadata, because it is public. A private key, never.

  1. user_data_replace_on_change and its effect on the plan

Here there is an asymmetry that catches people out: changing the user_data of an existing instance does, by default, absolutely nothing useful.

  # aws_instance.web will be updated in-place
  ~ resource "aws_instance" "web" {
        id        = "i-0abc123def456"
      ~ user_data = "8a7b6c5d" -> "1f2e3d4c"
        # (30 unchanged attributes hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.

The plan says "updated in-place" and the apply succeeds. But remember section 3: cloud-init runs only once, on the first boot. The machine has been up for days. The new user_data is recorded in the metadata and never runs. You have changed the code, the plan reflected it, the apply went fine and nothing changed on the machine. It is one of the most treacherous divergences between what Terraform says and what happens.

AWS offers an attribute to close that gap:

resource "aws_instance" "web" {
  ami           = data.aws_ami.base.id
  instance_type = var.web_class

  user_data                   = local.startup_configuration
  user_data_replace_on_change = true      # ← the change forces replacement
}

With it, the plan starts telling the truth:

  # aws_instance.web must be replaced
-/+ resource "aws_instance" "web" {
      ~ id        = "i-0abc123def456" -> (known after apply)
      ~ user_data = "8a7b6c5d" -> "1f2e3d4c" # forces replacement
    }

Plan: 1 to add, 0 to change, 1 to destroy.

Now the # forces replacement you learned to look for in 05-01 appears, and you know exactly what will happen: the instance is destroyed and a new one is created, which will indeed run the new user_data.

A table of behaviour across the three clouds, and the right strategy in each case:

Scenario Default behaviour What to do
AWS, standalone instance Updates in place, runs nothing user_data_replace_on_change = true
AWS, launch template + auto scaling group Creates a new template version; existing instances stay as they are instance_refresh on the group (seen in 05-02)
Azure, virtual machine Updates in place ignore_changes = [custom_data] and renew by another route, or force replacement with -replace
Azure, scale set A new model configuration upgrade_mode = "Rolling"
GCP, instance with metadata_startup_script Updates the metadata; the script does run on the next reboot Reboot, or recreate
GCP, template + managed group The template is immutable: a new one is created update_policy with type = "PROACTIVE"

The operational conclusion is the same in all three: with scaling groups, the right mechanism is not forcing instance replacement but the group's gradual renewal, which replaces machines in a controlled way with no downtime. That is why instance_refresh, upgrade_mode = "Rolling" and update_policy = PROACTIVE appeared in the three previous lessons.

  1. Debugging cloud-init when it does not work

Sooner or later an instance will boot with no application on it. The diagnosis is systematic:

# 1. Has cloud-init finished, and with what result?
cloud-init status --long
# status: done       ← all good
# status: error      ← something failed: go to point 3
# status: running    ← still going: wait

# Block until it finishes (useful in verification scripts)
cloud-init status --wait

# 2. How long did each phase take? Very useful for optimising the boot.
cloud-init analyze blame | head -20
cloud-init analyze show

# 3. THE IMPORTANT LOG: the output of the commands.
sudo tail -100 /var/log/cloud-init-output.log

# 4. cloud-init's internal log: which modules ran and in what order.
sudo tail -100 /var/log/cloud-init.log
sudo grep -iE "error|warn|fail|traceback" /var/log/cloud-init.log

# 5. What configuration did the instance actually receive?
sudo cat /var/lib/cloud/instance/user-data.txt
sudo cat /var/lib/cloud/instance/cloud-config.txt   # already parsed

# 6. Validate the syntax of the file it received
sudo cloud-init schema --system

The two files to tell apart, because that is the key to the diagnosis:

File Contains When to look at it
/var/log/cloud-init-output.log The standard output and error of everything that ran Nearly always. This is where the failing command's message is
/var/log/cloud-init.log The internal log: which modules, in which phase, with what result When the configuration seems to have been ignored entirely
/var/lib/cloud/instance/user-data.txt What actually reached the machine When you suspect the template

The failure catalogue, ordered by frequency:

Symptom Most likely cause Check
Absolutely nothing happens The #cloud-config line is missing, or the YAML is invalid cloud-init schema --system
Package not found The index is stale or there is no Internet egress Is package_update: true set? Is there NAT or private API access?
The artefact download fails The instance has no permissions or no egress Try the command by hand; check the role
Everything runs but the service is down An error in the program itself journalctl -u ecomarket-web -n 50
It works by hand but not at boot Different environment variables or paths: cloud-init runs as root and without a profile Use absolute paths and EnvironmentFile
The scaling group kills the instances in a loop The grace period is shorter than the boot time Raise health_check_grace_period / initial_delay_sec
Changing user_data has no effect It is an existing instance Section 7

The penultimate row deserves emphasis because it presents as an infrastructure problem and is a configuration one: if cloud-init takes 150 seconds and the load balancer declares the instance unhealthy at 90, the group kills it, starts another one, and the cycle repeats indefinitely. The grace period must be at least twice the real boot time, and cloud-init analyze blame tells you what that time is.

And a simple way to have the truth to hand without logging into the machine: have the script publish its own result.

runcmd:
  - /usr/local/bin/start-ecomarket.sh 2>&1 | tee /var/log/ecomarket-startup.log
  # Publish the log to the bucket, with the instance's role.
  - aws s3 cp /var/log/cloud-init-output.log s3://${logs_bucket}/startup/$(hostname).log

In an auto scaling fleet, where troubled instances are destroyed before you can connect to them, this is the difference between being able to diagnose and not being able to.

  1. Terraform's provisioners: local-exec, remote-exec and file

We reach the tool HashiCorp calls a last resort. There are three of them:

local-exec: running something on the machine running Terraform

resource "aws_instance" "web" {
  # ...

  provisioner "local-exec" {
    # It runs on YOUR machine (or on the pipeline runner), not on the instance.
    command     = "./scripts/register-in-inventory.sh ${self.private_ip} ${var.environment}"
    working_dir = path.module

    environment = {
      ENVIRONMENT = var.environment
      # Sensitive values are not printed in the log, but they do reach
      # the child process. And they stay in the state if they come from an attribute.
      API_TOKEN   = var.inventory_token
    }

    # By default it uses the system shell. That can be changed:
    interpreter = ["/bin/bash", "-c"]
  }
}

The three arguments that matter:

Argument What it does When to use it
working_dir The directory it runs from Nearly always: without it, the directory depends on where Terraform was invoked
environment Environment variables for the process To pass values without putting them on the command line (where they would be visible in ps)
interpreter The program that runs the command For Python, PowerShell, or to guarantee bash on systems where sh is dash

self inside a provisioner refers to the resource that contains it. It is the only way to reach its attributes there, because an ordinary self-reference would create a cycle.

remote-exec: running something inside the machine that was created

resource "aws_instance" "bastion" {
  # ...

  connection {
    type        = "ssh"
    host        = self.private_ip       # private! It needs a reachable network
    user        = "ubuntu"
    private_key = file(var.private_key_path)
    timeout     = "5m"

    # Hopping through a bastion, if the machine is in a private subnet.
    bastion_host        = var.bastion_ip
    bastion_user        = "ubuntu"
    bastion_private_key = file(var.bastion_key_path)
  }

  provisioner "remote-exec" {
    inline = [
      "sudo cloud-init status --wait",
      "sudo systemctl is-active ecomarket-web",
    ]
  }
}

inline versus script versus scripts:

Form What it does When
inline = [...] A list of commands run in sequence Two or three simple commands
script = "path" Copies a local script to the machine and runs it Logic longer than a few lines
scripts = [...] Several scripts, in order Several phases

The connection block is where remote-exec's real problem lies, and it deserves to be seen clearly: for Terraform to get into the machine, the SSH port (or WinRM on Windows) has to be reachable from wherever Terraform runs. In EcoMarket's case that means either putting the instances in a public subnet with port 22 open, or setting up a bastion, or running Terraform inside the VPC. All three options are worse than not needing any of this.

file: copying a file to the machine

provisioner "file" {
  source      = "${path.module}/files/internal-certificate.crt"
  destination = "/tmp/internal-certificate.crt"

  # It also accepts generated content, instead of a local file:
  # content = templatefile(...)
}

It requires the same connection block and has an important practical limitation: it copies as the connection's user, which is normally not root, so you have to copy to /tmp and move it afterwards with remote-exec. It is a dance that cloud-init's write_files solves without friction.

  1. The when = destroy provisioner and its rules

A provisioner can run when the resource is destroyed, rather than when it is created:

resource "aws_instance" "web" {
  # ...

  provisioner "local-exec" {
    when       = destroy
    command    = "./scripts/deregister.sh ${self.private_ip}"
    on_failure = continue     # if it fails, carry on destroying anyway
  }
}

It is the most defensible use case for provisioners: exit operations that have no Terraform API, such as releasing a per-instance licence, removing the node from a legacy inventory or closing a record in an old system.

And it has four strict rules that fail if they are not met:

Rule Why
It can only reference self, count.index and each.key At destroy time, var. and local. could have changed or disappeared; Terraform forbids it so that the behaviour is predictable
The resource block must still exist in the code Terraform needs to read the provisioner in order to run it. If you delete the block, the provisioner goes with it
It runs before the resource is destroyed Logically: afterwards there would be nothing to connect to
If it fails, the destruction stops unless on_failure = continue It can leave you with a resource you cannot destroy until you fix the script

The second rule produces the most common error:

╷
│ Error: Invalid reference from destroy provisioner
│
│ Destroy-time provisioners and their connection configurations may only
│ reference attributes of the related resource, via 'self', 'count.index',
│ or 'each.key'.
╵

And it also poses a paradox: if you have to remove the resource from the code, how does its destroy provisioner ever run? The answer is the removed block you saw in 03-05, which now makes full sense:

# The resource block is no longer in the code, but its exit logic is.
removed {
  from = aws_instance.web

  lifecycle {
    destroy = true      # yes, destroy it (and run its exit provisioner)
  }

  # And here you can declare the destroy provisioner that would otherwise be lost.
  provisioner "local-exec" {
    when    = destroy
    command = "./scripts/deregister.sh"
  }
}

This was exactly what 03-05 was hinting at when it said destroy = true serves to "declare the exit logic that would otherwise disappear along with the code". The circle closes here.

  1. terraform_data and null_resource as a re-run hook

Sometimes you want to run something that is not tied to any specific resource, or that must re-run when a certain value changes. That is the gap these two resources fill.

null_resource is the classic one; terraform_data is its modern replacement, introduced in Terraform 1.4, and it requires no provider:

# MODERN FORM: terraform_data, no null provider.
resource "terraform_data" "db_migration" {
  # When this value changes, the resource is REPLACED and the provisioner
  # runs again.
  triggers_replace = [
    var.db_schema_version,
    aws_db_instance.main.id,
  ]

  # Values available afterwards as self.input
  input = {
    host        = aws_db_instance.main.address
    environment = var.environment
  }

  provisioner "local-exec" {
    command = "./scripts/migrate-schema.sh ${self.input.host} ${self.input.environment}"
  }
}
# OLD FORM: null_resource, requires the hashicorp/null provider.
resource "null_resource" "db_migration" {
  triggers = {
    version = var.db_schema_version
    db      = aws_db_instance.main.id
  }

  provisioner "local-exec" {
    command = "./scripts/migrate-schema.sh"
  }
}
null_resource terraform_data
Provider required hashicorp/null None: it is built in
Trigger attribute triggers (map of strings) triggers_replace (any type)
Storing values Only in triggers input → output, of any type
Use without a provisioner Not very useful Yes: useful to force replacements of other resources
Recommendation Legacy code Use it in new code

terraform_data has an elegant use with no provisioner at all: forcing another resource's replacement when something that resource does not observe changes.

resource "terraform_data" "configuration_version" {
  input = var.configuration_version
}

resource "aws_instance" "web" {
  # ...
  lifecycle {
    replace_triggered_by = [terraform_data.configuration_version]
  }
}

That is one hundred per cent declarative, it runs nothing outside Terraform and it shows up cleanly in the plan as a replacement. It is the preferable pattern whenever it fits.

Warning. triggers_replace with timestamp() or uuid() inside it makes the resource replace on every plan, which produces a plan that is never empty and destroys your ability to detect real changes. It is a frequent antipattern for "forcing it to always run". If you need something to run on every deployment, that does not belong in Terraform: it belongs in the pipeline (module 8).

  1. Why provisioners break the declarative model

Now that you know how to use them, here is the complete list of why you should avoid them, in the form of a risk table:

Problem What it means in practice Concrete consequence
They are not reflected in state Terraform records "I ran it", not what it did If somebody undoes the change by hand, no plan detects it. Invisible drift
They are not idempotent Running twice can give different results A retry after a partial failure can duplicate things
They do not appear in the plan The plan does not say what the script will do You review a plan that does not tell the truth
On failure, they taint the resource The resource is left tainted and the next apply destroys and recreates it A transient network error destroys and recreates a healthy machine
They force you to open SSH or WinRM You have to expose the port or set up a bastion The security posture is weakened forever for a one-off operation
They need access credentials The private key reaches Terraform It ends up in the state or in a variable you have to guard
They depend on the runner's environment local-exec uses the binaries, PATH and network of whoever runs it It works on your laptop and fails in the pipeline
They couple the lifecycle The configuration is only applied at creation Reconfiguring requires destroying and recreating the machine
They cannot be tested There is no way to simulate them They are discovered at apply, on the real machine

The first row is the most serious and deserves an example. Suppose a remote-exec installs a certificate on the machine. Somebody deletes it three weeks later. terraform plan says "No changes", because from Terraform's point of view everything is as it should be: the instance exists with the right attributes. The drift is real and it is invisible.

Compare that with what Ansible does: it has no state, but it checks reality on every run. Run it again and it sees the certificate is missing and puts it back. That is the correct model for configuration, and it is the reason behind HashiCorp's recommendation.

The complete decision tree, to keep to hand:

flowchart TD
    A{"I need to do something<br/>on the machine"} --> B{"Can it go in<br/>the image?"}
    B -->|Yes| C["<b>Packer</b><br/>It is the best option:<br/>fast, reproducible,<br/>testable"]
    B -->|No| D{"Is it first-boot<br/>configuration?"}
    D -->|Yes| E["<b>cloud-init</b><br/>user_data with<br/>templatefile()"]
    D -->|No| F{"Do live machines<br/>need reconfiguring?"}
    F -->|Yes| G["<b>Ansible</b> or another<br/>configuration tool,<br/>after Terraform"]
    F -->|No| H{"Is there a resource<br/>or provider that does it?"}
    H -->|Yes| I["<b>Use that resource</b><br/>Declarative, in the plan,<br/>in the state"]
    H -->|No| J["<b>Provisioner</b><br/>Document WHY<br/>there was no alternative"]

    style C fill:#dcfce7,stroke:#16a34a
    style E fill:#dbeafe,stroke:#2563eb
    style G fill:#fef3c7,stroke:#d97706
    style J fill:#fee2e2,stroke:#dc2626

Branch H deserves attention because it gets overlooked: many things people do with local-exec have a resource that does them properly. Calling aws cli to create a DNS record when aws_route53_record exists; invoking kubectl apply when the kubernetes provider exists; running gh api when the github provider exists. Before writing a local-exec, search the registry for a provider.

  1. The Ansible alternative, done properly

When configuration management genuinely is needed, the mistake is to put Ansible inside Terraform with a local-exec. The right way is for each tool to do its own job and for them to communicate through a well-defined artefact.

The wrong way, the one you see in many tutorials:

# DO NOT DO IT LIKE THIS
resource "aws_instance" "web" {
  # ...
  provisioner "local-exec" {
    command = "sleep 60 && ansible-playbook -i ${self.private_ip}, playbook.yml"
  }
}

Four problems in two lines: the arbitrary sleep, the dependence on ansible being installed on whoever runs it, the impossibility of re-running Ansible without touching Terraform, and the fact that a playbook failure taints the instance and causes a perfectly healthy machine to be destroyed.

The right way, option A: Terraform publishes outputs and Ansible consumes them with a dynamic inventory.

# infra/app/outputs.tf
output "ansible_inventory" {
  description = "Data for the Ansible inventory."

  value = {
    environment = var.environment
    region      = var.region

    web = {
      hosts = module.app.web_private_ips
      vars = {
        db_host     = module.data.endpoint
        bucket      = module.data.bucket_name
        db_secret   = module.data.secret_name
        app_version = var.app_version
      }
    }
  }
}
# A two-phase deployment, each tool doing its own job.

# Phase 1: infrastructure
terraform apply -var-file=dev.tfvars

# Phase 2: configuration
terraform output -json ansible_inventory > inventory.json
ansible-playbook -i inventory/terraform.py playbook-ecomarket.yml

Option B, better still for auto scaling fleets: a dynamic inventory based on tags. Ansible has plugins that query the cloud's API directly:

# inventory/aws_ec2.yml
plugin: amazon.aws.aws_ec2
regions:
  - eu-west-1
filters:
  "tag:Project": ecomarket
  "tag:Environment": dev
  instance-state-name: running
keyed_groups:
  - key: tags.Tier
    prefix: tier
  - key: placement.availability_zone
    prefix: az
compose:
  ansible_host: private_ip_address
ansible-inventory -i inventory/aws_ec2.yml --graph
ansible-playbook -i inventory/aws_ec2.yml playbook-ecomarket.yml

This option is the correct one for EcoMarket and the reason is concrete: with auto scaling, instances are born and die continuously. An inventory generated by Terraform is stale the moment the group scales. A tag-based dynamic inventory always sees the real fleet, and it is the practical justification for all the tagging EcoMarket has been carrying since module 2.

The final comparison:

Aspect Ansible inside Terraform (local-exec) Ansible after Terraform
Re-running the configuration without touching infrastructure Impossible without forcing replacements One command
A playbook failure Taints the resource: destroys and recreates the machine The playbook fails, the machine stays up
Seeing what will change beforehand No --check --diff
Where Ansible runs On whoever runs Terraform Wherever you like: pipeline, control tower, laptop
Instances created by auto scaling It never configures them It sees them in the next inventory
Separation of responsibilities None Clean

The auto scaling row is decisive: a machine born because traffic rose never went through Terraform, so no provisioner ever touched it. If the configuration lives in a provisioner, that machine boots unconfigured. It is the argument that settles the debate in any elastic architecture.

  1. Declarative health checking instead of "waiting for it to boot"

The lesson's last pattern replaces the urge to add a sleep. The question "how do I wait for the application to be ready?" has a declarative answer, and it is better than any wait.

What people usually do:

# ANTIPATTERN
resource "terraform_data" "wait" {
  provisioner "local-exec" {
    command = "sleep 120"
  }
}

It is fragile (sometimes 120 seconds is too much, sometimes too little), it checks nothing and it lengthens every apply.

What you should do: make the health check part of the infrastructure, which is where it belongs. You already have it written in all three clouds:

# AWS: the target group checks /health and the auto scaling group
# replaces whatever does not respond.
resource "aws_lb_target_group" "web" {
  health_check {
    path                = "/health"
    healthy_threshold   = 2
    unhealthy_threshold = 3
    interval            = 30
  }
}

resource "aws_autoscaling_group" "web" {
  health_check_type         = "ELB"
  health_check_grace_period = 180
  # ...
}
# GCP: auto-healing, made explicit.
resource "google_compute_region_instance_group_manager" "web" {
  auto_healing_policies {
    health_check      = google_compute_health_check.web.id
    initial_delay_sec = 180
  }
}

With that, nobody has to wait: if an instance does not boot properly, the platform replaces it on its own, and it will keep doing so at three in the morning when nobody is running Terraform. A sleep in an apply only protects during that apply.

And if on top of that you need the apply itself to verify that the service responds before calling it a success, the right instrument is a postcondition or a check block, not a script:

data "http" "web_health" {
  url = "https://${module.app.load_balancer_dns}/health"

  retry {
    attempts     = 10
    min_delay_ms = 5000
  }
}

check "platform_responds" {
  assert {
    condition     = data.http.web_health.status_code == 200
    error_message = "The platform is not returning 200 on /health after the deployment."
  }
}

This is declarative, it appears in the plan, it retries sensibly instead of waiting blindly and it taints no resource if it fails: it warns. Preconditions, postconditions and check blocks are studied in depth in 06-05, which is the last lesson of the next module.

Common Mistakes and Tips

Forgetting the #cloud-config line. Without it, cloud-init silently ignores the file and the instance boots bare. It is failure number one.

Breaking the YAML indentation when interpolating. A multi-line value inserted inside an indented block invalidates the file. Use indent() and validate with cloud-init schema before applying.

Confusing Terraform's ${} with the shell's ${}. Inside a template, ${VAR} is resolved by Terraform. For a literal $, double it: $${VAR}.

Putting a secret in user_data. It is left readable in the metadata for any process on the machine and in the clear in the state and in the plan file. Pass the name of the secret and let the instance resolve it with its identity.

Changing an existing instance's user_data expecting it to be applied. cloud-init runs once. Use user_data_replace_on_change, or the scaling group's gradual renewal.

Exceeding AWS's 16 KB of user_data. The fix is not to compress: it is to have the script download what it needs from a bucket.

A grace period shorter than the boot time. The group kills instances that were still starting up, in a loop. Measure with cloud-init analyze blame and allow at least double.

Using remote-exec without realising what it implies. It requires opening SSH from wherever Terraform runs, or a bastion, forever, for a one-off operation.

Putting ansible-playbook in a local-exec with a sleep in front. A playbook failure taints the resource and destroys a healthy machine; instances created by auto scaling are never configured. Ansible afterwards, with a tag-based dynamic inventory.

Using timestamp() in triggers_replace. The resource is replaced on every plan and the plan is never empty, which makes real changes impossible to detect.

Referencing var. in a destroy provisioner. Only self, count.index and each.key are allowed. And if you delete the resource block, the provisioner goes with it: that is what removed is for.

Writing a local-exec that calls the cloud CLI. Check first whether a resource or provider does it declaratively. There almost always is one.

Tip: the medium-term goal is an image built with Packer. It cuts the boot from minutes to seconds, removes the dependence on external repositories at boot, lets you test the image before deploying it and makes the deployment reproducible. user_data is left for what genuinely varies between environments.

Tip: make the boot publish its log. Copying /var/log/cloud-init-output.log to the bucket with the instance's role is the only thing that lets you diagnose a machine auto scaling has already destroyed.

Tip: when you use a provisioner, write down why. A comment saying which alternative was ruled out and why. Without that note, the next person to read it will not know whether it can be replaced and will leave it there for years.

Tip: anything touching secrets, SSH keys or opening administration ports is reviewed with the security team. A remote-exec changes the platform's access topology, and that decision does not belong to whoever writes the resource.

Exercises

Exercise 1: portable cloud-init for the three clouds

Write a cloud-config.yaml.tftpl template that works unchanged on AWS, Azure and GCP, and that:

  1. Installs postgresql-client-16 and jq.
  2. Creates a service user ecomarket that cannot log in.
  3. Writes /etc/ecomarket/app.env with 0640 permissions, containing the environment, the database host, the bucket name and the name of the secret (never its value).
  4. Writes a script /usr/local/bin/start-ecomarket.sh that reads the password with the machine's identity and verifies the PostgreSQL connection.
  5. Installs a systemd unit and starts it.
  6. Publishes /var/log/cloud-init-output.log to the logs bucket when it finishes.

Also write the three HCL snippets that pass it to each cloud, and the command to validate the rendered YAML before applying.

Exercise 2: auditing three provisioners

These three blocks arrive in a code review. For each one: say whether you would approve it, identify all the problems and propose the correct alternative with code.

# A
resource "aws_instance" "web" {
  ami           = data.aws_ami.base.id
  instance_type = "t3.micro"

  provisioner "remote-exec" {
    inline = [
      "sudo apt-get update",
      "sudo apt-get install -y nginx",
      "echo 'DB_PASSWORD=${var.db_password}' | sudo tee /etc/app.env",
      "sudo systemctl start nginx",
    ]

    connection {
      type        = "ssh"
      host        = self.public_ip
      user        = "ubuntu"
      private_key = file("~/.ssh/id_rsa")
    }
  }
}

# B
resource "null_resource" "dns" {
  triggers = {
    always = timestamp()
  }

  provisioner "local-exec" {
    command = "aws route53 change-resource-record-sets --hosted-zone-id Z123 --change-batch file://change.json"
  }
}

# C
resource "aws_instance" "app" {
  # ...
  provisioner "local-exec" {
    when    = destroy
    command = "curl -X DELETE https://inventory.ecomarket.example.com/hosts/${var.host_name}"
  }
}

Exercise 3: designing EcoMarket's configuration strategy

On paper, write EcoMarket's complete strategy for getting the application onto the machines:

  1. A table assigning each of these tasks to one of the four strategies, with justification: installing the runtime; installing the monitoring agent; injecting the PostgreSQL endpoint; deploying a new version of the application; rotating an internal certificate on live machines; registering the instance in a legacy inventory with no API.
  2. The complete flow of deploying a new version to prod, step by step, stating which tool does what and what the end user sees.
  3. How you verify the deployment went well, without using a single sleep.
  4. Exactly what happens when auto scaling creates a new instance at three in the morning, and which component guarantees it ends up properly configured.
  5. The list of what will never go through user_data, with the reason for each item.

Solution 1

The template:

#cloud-config
package_update: true
package_upgrade: false

packages:
  - postgresql-client-16
  - jq

users:
  - name: ecomarket
    gecos: "EcoMarket service user"
    shell: /usr/sbin/nologin
    system: true
    lock_passwd: true

write_files:
  - path: /etc/ecomarket/app.env
    owner: root:ecomarket
    permissions: '0640'
    content: |
      ECOMARKET_ENVIRONMENT=${environment}
      ECOMARKET_CLOUD=${cloud}
      ECOMARKET_DB_HOST=${db_host}
      ECOMARKET_DB_PORT=5432
      ECOMARKET_DB_NAME=ecomarket
      ECOMARKET_BUCKET=${bucket}
      ECOMARKET_SECRET=${secret_name}
      ECOMARKET_LOGS_BUCKET=${logs_bucket}

  - path: /usr/local/bin/start-ecomarket.sh
    owner: root:root
    permissions: '0755'
    content: |
      #!/usr/bin/env bash
      set -euo pipefail
      source /etc/ecomarket/app.env

      # The password is resolved HERE, with the machine's identity.
      case "$${ECOMARKET_CLOUD}" in
        aws)
          PASSWORD=$(aws secretsmanager get-secret-value \
            --secret-id "$${ECOMARKET_SECRET}" \
            --query SecretString --output text | jq -r .password)
          ;;
        azure)
          TOKEN=$(curl -s -H "Metadata:true" \
            "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://vault.azure.net" \
            | jq -r .access_token)
          PASSWORD=$(curl -s -H "Authorization: Bearer $${TOKEN}" \
            "https://$${ECOMARKET_KEYVAULT}.vault.azure.net/secrets/$${ECOMARKET_SECRET}?api-version=7.4" \
            | jq -r .value)
          ;;
        gcp)
          PASSWORD=$(gcloud secrets versions access latest --secret="$${ECOMARKET_SECRET}")
          ;;
      esac

      export PGPASSWORD="$${PASSWORD}"
      psql -h "$${ECOMARKET_DB_HOST}" -U ecomarket -d ecomarket -c 'SELECT 1' >/dev/null
      echo "PostgreSQL connection verified"

  - path: /etc/systemd/system/ecomarket-web.service
    owner: root:root
    permissions: '0644'
    content: |
      [Unit]
      Description=EcoMarket Web
      After=network-online.target
      Wants=network-online.target

      [Service]
      Type=simple
      User=ecomarket
      EnvironmentFile=/etc/ecomarket/app.env
      ExecStart=/opt/ecomarket/bin/ecomarket-web
      Restart=always
      RestartSec=5

      [Install]
      WantedBy=multi-user.target

runcmd:
  - [ mkdir, -p, /opt/ecomarket, /etc/ecomarket ]
  - /usr/local/bin/start-ecomarket.sh
  - systemctl daemon-reload
  - systemctl enable --now ecomarket-web
  # Publish the boot log, so we can diagnose instances that auto scaling
  # destroys before we can connect to them.
  - /usr/local/bin/publish-log.sh

final_message: "EcoMarket ready after $UPTIME seconds"

Note the $${...}: inside the template, a literal $ for the shell is written doubled, because a plain ${} would be consumed by Terraform.

The three HCL snippets:

locals {
  cloud_config = templatefile("${path.module}/templates/cloud-config.yaml.tftpl", {
    environment = var.environment
    cloud       = var.cloud                # "aws" | "azure" | "gcp"
    db_host     = var.db_endpoint
    bucket      = var.bucket_id
    secret_name = var.secret_name
    logs_bucket = var.logs_bucket
  })
}

# AWS
resource "aws_launch_template" "web" {
  user_data = base64encode(local.cloud_config)
}

# Azure
resource "azurerm_linux_virtual_machine_scale_set" "web" {
  custom_data = base64encode(local.cloud_config)
}

# GCP
resource "google_compute_instance_template" "web" {
  metadata = {
    user-data = local.cloud_config
  }
}

Validation before applying:

# Render and save
terraform console <<'EOF' > /tmp/cc.yaml
templatefile("modules/app/templates/cloud-config.yaml.tftpl", {
  environment = "dev", cloud = "aws", db_host = "db.example.com",
  bucket = "ecomarket-dev-images", secret_name = "ecomarket-dev/db/master",
  logs_bucket = "ecomarket-dev-logs"
})
EOF

# Validate the YAML syntax and the cloud-init schema
python3 -c "import yaml; yaml.safe_load(open('/tmp/cc.yaml'))" && echo "YAML OK"
cloud-init schema --config-file /tmp/cc.yaml

That last part belongs in the pipeline: it validates the template without deploying a single machine.

Solution 2

Block A: REJECTED. Five problems, two of them serious:

  1. The secret in the provisioner's inline. ${var.db_password} is interpolated into a command that ends up in Terraform's state in the clear and, if there is an execution log, in the pipeline log. On top of that it reaches /etc/app.env with tee's default permissions, world-readable.
  2. host = self.public_ip implies the instance has a public IP and port 22 open, which contradicts the design in 05-02, where the web lives in a private subnet.
  3. private_key = file("~/.ssh/id_rsa") brings a personal private key into Terraform and potentially into the state, and ties the apply to whoever runs it having that key. In a pipeline it does not work.
  4. It is neither idempotent nor reflected in state. If somebody uninstalls nginx, no plan detects it.
  5. A transient network failure taints the instance and the next apply destroys and recreates it.

The correct alternative:

resource "aws_instance" "web" {
  ami                    = data.aws_ami.base.id
  instance_type          = "t3.micro"
  subnet_id              = var.private_subnet_id
  vpc_security_group_ids = [aws_security_group.web.id]
  iam_instance_profile   = aws_iam_instance_profile.web.name

  user_data                   = local.cloud_config   # with the NAME of the secret
  user_data_replace_on_change = true

  metadata_options {
    http_tokens = "required"
  }
}

And in the cloud-config, write_files with permissions: '0640', and the secret's value read with the instance role. No SSH, no private key, no provisioner.

Block B: REJECTED. Three problems:

  1. timestamp() in triggers makes the resource replace on every plan. The plan is never empty, which destroys the ability to detect real changes and makes any automatic destruction control useless.
  2. local-exec calling the AWS CLI for something that has a native resource. It does not appear in the plan, it is not in the state, it detects no drift and it depends on aws being installed and authenticated on the runner.
  3. file://change.json is a relative path with no working_dir: the command depends on the directory Terraform was invoked from.

The correct alternative, one hundred per cent declarative:

resource "aws_route53_record" "web" {
  zone_id = var.zone_id
  name    = "${var.environment}.ecomarket.example.com"
  type    = "A"

  alias {
    name                   = aws_lb.web.dns_name
    zone_id                = aws_lb.web.zone_id
    evaluate_target_health = true
  }
}

It appears in the plan, lives in the state, detects drift if somebody changes it in the console, and depends on no external tool. This is the most common case of an unnecessary provisioner: doing with a script what a resource already does.

Block C: APPROVED WITH CHANGES. The use case is legitimate — deregistering from a legacy inventory with no Terraform provider is exactly what destroy provisioners exist for — but it has two defects:

  1. ${var.host_name} is not allowed in a destroy provisioner. Only self, count.index and each.key. The apply fails with Invalid reference from destroy provisioner.
  2. Without on_failure, if the inventory is down, the destruction stops and you are left with a resource that cannot be destroyed.

The corrected version:

resource "aws_instance" "app" {
  # ...
  tags = merge(local.tags, { Name = "${var.base_name}-app" })

  provisioner "local-exec" {
    when = destroy

    # Only self: the name is taken from a tag on the resource itself.
    command = "curl -sf -X DELETE https://inventory.ecomarket.example.com/hosts/${self.tags["Name"]}"

    # If the inventory is down, we do not block the destruction.
    on_failure = continue
  }
}

And a note that must accompany the block:

# PROVISIONER JUSTIFICATION:
# The legacy inventory (inventory.ecomarket.example.com) has no Terraform
# provider and none is planned (decommissioning scheduled for 2027).
# Without this deregistration, records are orphaned and trigger false
# "host not responding" alerts. Reviewed with security on 2026-09.
# When the inventory is decommissioned, delete this block.

Moreover, if at some point the resource has to be removed from the code, its exit logic is preserved with a removed { lifecycle { destroy = true } } block that includes this same provisioner, as seen in section 10.

Solution 3

1. Assigning tasks to strategies:

Task Strategy Justification
Installing the runtime 1. Packer It is identical in every environment, heavy and slow to install. In the image it saves minutes on every boot
Installing the monitoring agent 1. Packer The same: common to everything, and it must be running from the first second, even before the application starts
Injecting the PostgreSQL endpoint 2. cloud-init It is the only thing that changes between environments; Terraform knows it and passes it in with templatefile()
Deploying a new version of the application 1 + group renewal A new image with the version → a new launch template → gradual renewal. Instance replacement, not in-place update
Rotating an internal certificate on live machines 3. Ansible Existing machines have to be touched without recreating them, it is idempotent and it is verified as it runs
Registering in the legacy inventory with no API 4. Provisioner The only task with no alternative: there is no provider, it cannot be done from the machine, and it has to be undone on destroy

2. The flow for deploying a new version to prod:

  1. The application pipeline builds the v2.5.0 artefact and publishes it to the artefacts bucket.
  2. Packer builds the image ecomarket-web-2.5.0 from the hardened base image, with the runtime, the agent and the artefact already inside. It tests it with goss or similar and publishes it.
  3. A pull request is opened on ecomarket-infra raising var.image_version to 2.5.0 in prod.tfvars.
  4. The pipeline runs terraform plan -out=plan.tfplan and the automatic control from 05-01 checks that there are no unapproved destructions. The plan shows a new version of the launch template.
  5. Human review of the plan by somebody other than whoever wrote it.
  6. terraform apply plan.tfplan. It creates the new template version and launches the group's gradual renewal: it replaces instances in batches, keeping 50 % healthy, waiting the warm-up period between batches.
  7. The load balancer only sends traffic to instances returning 200 on /health. Those that do not are removed and replaced.
  8. What the end user sees: nothing. There is no downtime because healthy capacity is never withdrawn.
  9. If something goes wrong, you roll back by lowering var.image_version to 2.4.1 and repeating the process: the previous image still exists.

3. Verification without sleep:

  • During the deployment, the gradual renewal mechanism is itself the verification: it does not move to the next batch if the previous one is not healthy according to the load balancer's check.
  • When the apply finishes, a data "http" with retry on /health inside a check block, as in section 14. It retries sensibly and warns if there is no response.
  • Afterwards, terraform plan -detailed-exitcode should return 0: if it returns 2, something did not converge.
  • Continuously, the group's health check and the observability platform's alerts. That is the verification that keeps working when nobody is looking.

4. The three-in-the-morning instance. Auto scaling detects a traffic peak and launches an instance from the current launch template. That instance:

  • Boots from the Packer image, which already carries the runtime, the agent and the application: it is ready in twenty seconds.
  • Runs the cloud-init user_data, which writes the environment file with the database endpoint and the secret's name.
  • Reads the password with the instance role, verifies the connection and starts the service.
  • Returns 200 on /health and the load balancer starts sending it traffic.

No Terraform provisioner is involved, because Terraform played no part in its creation. That is the decisive point: the configuration has to be in the image or in the user_data, which is what the instance carries with it. Any configuration that depends on somebody running Terraform or Ansible will never reach that machine. And for certificate rotation, Ansible with a dynamic inventory will find it on its next run, because it carries EcoMarket's tags.

5. What never goes through user_data:

Never Reason
The PostgreSQL password Readable in the metadata by any process on the machine, and in the clear in the state and in the plan file
SSH or TLS private keys The same, and they compromise more than a single database
Third-party API tokens The same, with the added problem that they usually have broad permissions
Complete connection strings They contain the password embedded
Anything over 16 KB AWS's hard limit; and a large user_data is a sign it should be an image
Complex configuration logic It cannot be tested, it is not reflected in state and it does not re-run. It belongs in Packer or Ansible

What does go through: the environment name, the region, the database endpoint, the bucket name, the name of the secret, the application version and public SSH keys. All of it is non-sensitive information whose exposure grants no access on its own.

Conclusion

This lesson closes module 5 and EcoMarket is complete: real infrastructure in three clouds, with the machines configuring themselves and the application serving requests.

  • Provisioning and configuring are different problems. Terraform creates resources and knows what exists thanks to its state; what happens inside a machine is not in that state, so Terraform cannot plan it, check it or detect its drift.
  • HashiCorp calls provisioners "a last resort" and it means it. Ahead of them come the prebuilt Packer image, cloud-init and configuration management tools, in that order of preference.
  • cloud-init is the same program in all three clouds; only the attribute changes: user_data in AWS (with a 16 KB limit), custom_data in Azure and metadata.user-data in GCP. One #cloud-config template serves all three.
  • The first #cloud-config line is mandatory, and write_files happens before runcmd, which lets you write a readable script and run it afterwards instead of piling up commands.
  • templatefile() injects what Terraform knows — the PostgreSQL endpoint, the bucket name — with two precautions: escaping $$ for the shell and validating the rendered YAML with cloud-init schema before applying.
  • A secret in user_data is exposed by two simultaneous routes: readable from the metadata by any process on the machine, and in the clear in the state and in the plan file. The correct pattern is to pass the secret's name and have the instance resolve the value with the identity you gave it in 05-02, 05-03 and 05-04.
  • Changing a live instance's user_data does nothing, because cloud-init runs once. user_data_replace_on_change makes the plan tell the truth, and with scaling groups the right mechanism is gradual renewal, not forced replacement.
  • Debugging cloud-init means reading /var/log/cloud-init-output.log, measuring with cloud-init analyze blame and waiting with cloud-init status --wait. And publishing that log to the bucket is the only thing that lets you diagnose an instance auto scaling has already destroyed.
  • The three provisioners — local-exec, remote-exec and file — have nine documented problems, and the two worst are that their effect does not live in the state (invisible drift) and that a failure taints the resource, so a transient error destroys a healthy machine.
  • remote-exec changes the platform's security topology forever for a one-off operation: it requires opening SSH or setting up a bastion.
  • The destroy provisioner is the most defensible use case, with its four rules: only self/count.index/each.key, the block must stay in the code, it runs before destroying, and without on_failure = continue it can block the destruction. And when the resource has to be removed from the code, the removed { destroy = true } block from 03-05 is what preserves that exit logic.
  • terraform_data replaces null_resource — no provider, triggers_replace of any type and input/output — and its best use is entirely declarative: replace_triggered_by, running nothing outside Terraform.
  • Ansible goes after Terraform, not inside it, and with a tag-based dynamic inventory rather than a generated one, because instances created by auto scaling never go through Terraform and a provisioner will never touch them.
  • Waiting is replaced by declarative health checks: the target group and auto-healing protect you at three in the morning, when a sleep in an apply is no longer there.

This module has been the leap to the real cloud, and it is worth looking back for a moment: you started with concepts common to the three clouds — credentials, the plan over real infrastructure, the symbols that announce a destruction, API errors, cost and the destroy discipline; you deployed EcoMarket on AWS reusing module 4's modules without changing their interface; you confirmed on Azure and GCP that what you had learned was infrastructure and not a provider; and you have closed by configuring the machines without writing a single secret into a file.

In module 6, Advanced Terraform Features, the language comes back into focus with everything the real cloud has made necessary. You will see workspaces and why EcoMarket chose separate .tfvars instead; Terraform's functions in depth, including the ones you have been using without picking apart (cidrsubnet, templatefile, merge, try); dynamic blocks, which already showed up in the auto scaling group's tags and in Azure's subnet delegations; importing resources, which is how you solve this module's most awkward case — a resource created in the cloud but absent from the state — and also how you adopt infrastructure that existed before your code; and preconditions, postconditions and check blocks, which turn the checks we have written by hand here — the correct account, the platform responding on /health — into guarantees Terraform itself verifies on every plan.

© Copyright 2026. All rights reserved