Learn Terraform Β· 7/11

Provisioners and Bootstrapping

7 min read

Course: Terraform

Topic: Provisioners and Bootstrapping πŸš€

Imagine you are opening a new pizza shop. Terraform is the general contractor: it builds the physical shop, wires the electricity, and installs the ovens. But when the contractor leaves, you just have an empty kitchen. You still need to stock ingredients, print menus, and prep the dough before you can serve your first customer.

In the world of infrastructure, Terraform provisions the Virtual Machine (the empty building), but the machine still needs software, configuration files, and running services (the ingredients and menus) to actually do its job. This process of preparing an empty server for service is called bootstrapping.

To handle bootstrapping, Terraform provides tools called Provisioners and integrates heavily with cloud-native solutions like cloud-init/user-data. Let us explore how to take our servers from "empty boxes" to "ready for production."


1. When (and When NOT) to Use Provisioners πŸ›‘

The Definition

A provisioner is a built-in Terraform feature that executes scripts or commands on a local or remote machine as part of resource creation or destruction.

The Problem

Terraform is entirely declarativeβ€”you tell it what you want (an AWS EC2 instance), and it figures out how to get it. However, installing specific software, running custom bash scripts, or triggering a third-party API often requires imperative steps (do step A, then step B). Terraform's declarative engine does not natively understand imperative shell scripts.

How Provisioners Solve It

Provisioners act as an escape hatch. They allow you to attach a script to a resource so that when the resource is created, Terraform runs the script to configure it.

⚠️ The Golden Rule: Provisioners are a Last Resort

If you read the official HashiCorp documentation, you will see a massive warning: Provisioners are a last resort. Why?

  1. They break idempotency: Terraform cannot track what a bash script did inside its state file. If a script fails halfway, Terraform doesn't know how to resume it.
  2. They are invisible to terraform plan: Terraform can tell you it will run a script, but it has no idea what the script will actually change inside the server.
  3. They require complex networking: To run a script on a remote server, Terraform needs SSH keys, open firewalls, and direct network access, which is a security headache.

When NOT to use them:

  • Installing heavy software stacks (use pre-built machine images with tools like Packer instead).
  • Ongoing configuration management (use Ansible, Chef, or Puppet).
  • Basic server setup (use user-data/cloud-init, which we will cover in section 4).

When TO use them:

  • Sending a Slack webhook notification when a deployment finishes.
  • Running a local script to clean up temporary files.
  • Interacting with a legacy system that doesn't have a Terraform Provider.

2. The local-exec Provisioner: Running Local Scripts πŸ’»

The Definition

The local-exec provisioner executes a command locally on the machine where you are running the terraform apply command (like your laptop or a CI/CD runner).

The Problem

Sometimes, creating infrastructure generates dynamic data (like a new public IP address) that you need to pass into a local script, save to a local text file, or send to an external API right away.

How it Solves It

local-exec simply uses your local machine's terminal to run a command, injecting Terraform variables into it.

Industry Example

A very common industry use case for local-exec is triggering an Ansible playbook right after Terraform finishes building the servers, or outputting the new server IPs into a file.

Instead of attaching provisioners to actual infrastructure resources (which can corrupt their state if the script fails), industry standard practice is to use the terraform_data resource. This is a special, empty resource purely used to trigger actions.

hcl
resource "aws_instance" "web_server" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

# Use terraform_data to run a local script after the server is built
resource "terraform_data" "notify_slack" {
  # The 'triggers_replace' argument ensures the provisioner runs 
  # only when the EC2 instance ID changes.
  triggers_replace = aws_instance.web_server.id

  provisioner "local-exec" {
    # We are running a local curl command from our laptop/runner
    command = "curl -X POST -H 'Content-type: application/json' --data '{\"text\":\"New server deployed with IP: ${aws_instance.web_server.public_ip}\"}' https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
  }
}

Under the hood: Terraform creates the EC2 instance, retrieves its public IP, resolves the variable in the command string, and then executes curl on your local operating system.


3. The remote-exec Provisioner: Running Commands on Instances 🌐

The Definition

The remote-exec provisioner invokes a script or a list of commands directly on a remote resource (like an AWS EC2 instance or an Azure VM) after it is created.

The Problem

You need to run a quick command inside the newly created server, such as restarting a service or changing a file permission, but you have no other automated configuration tools available.

How it Solves It

remote-exec opens an SSH (Linux) or WinRM (Windows) connection to the new server, logs in, executes the commands, and logs out.

Industry Example

You will rarely see this in modern, mature environments due to the "last resort" rule, but it is heavily used in quick proofs-of-concept.

To use remote-exec, you must provide a connection block so Terraform knows how to log into the server.

hcl
resource "aws_instance" "web_server" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
  key_name      = "my_ssh_key" # Required so we can SSH in

  # The connection block tells Terraform how to communicate with the server
  connection {
    type        = "ssh"
    user        = "ubuntu"
    private_key = file("~/.ssh/my_ssh_key.pem")
    host        = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo apt-get update",
      "sudo apt-get install -y nginx",
      "sudo systemctl start nginx"
    ]
  }
}

Under the hood: Terraform provisions the VM. Once the VM reports as "running", Terraform attempts to SSH into it using the provided connection block. It then executes the inline commands one by one. If any command fails, Terraform marks the entire aws_instance as "tainted" (meaning it is considered broken and will be destroyed and recreated on the next terraform apply).


4. Using cloud-init/user-data (The Preferred Way) πŸ†

The Definition

user-data (often powered by a tool called cloud-init) is a cloud-native feature that allows you to pass a script to a cloud provider (like AWS, Azure, or GCP). The cloud provider injects this script into the virtual machine, and the VM executes it automatically on its very first boot.

The Problem

Using remote-exec forces Terraform to handle SSH keys, manage network timeouts, and wait for the server to be completely online before configuring it. If a firewall blocks SSH, Terraform gets stuck. We need a way to pass instructions to the server without needing to establish a network connection to it.

How it Solves It

By using user-data, Terraform hands the script to the cloud provider's API at the exact same time it requests the server.

Imagine handing the chef the pizza recipe before they walk into the kitchen, rather than trying to shout the recipe through a tiny window from the outside (which is what SSH via remote-exec feels like). The chef (the server) reads the recipe locally as soon as they start working.

Industry Example

This is the industry standard for bootstrapping servers. It is entirely declarative, requires zero SSH keys in your Terraform code, and doesn't break Terraform's state.

hcl
# 1. We write our bash script
locals {
  setup_script = <<-EOF
    #!/bin/bash
    sudo apt-get update
    sudo apt-get install -y apache2
    echo "<h1>Welcome to the Preferred Way!</h1>" > /var/www/html/index.html
    sudo systemctl enable apache2
    sudo systemctl start apache2
  EOF
}

# 2. We pass the script to the user_data argument
resource "aws_instance" "web_server" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
  
  # The cloud provider takes this string and runs it on boot!
  user_data = local.setup_script

  # user_data_replace_on_change forces Terraform to recreate the VM 
  # if you change the setup script later.
  user_data_replace_on_change = true 
}

Under the hood: Terraform sends a single API payload to AWS containing both the instance configuration and the user-data script. Terraform's job is now done. AWS spins up the server, and the Linux operating system inside the server looks for the user-data payload and executes it as the root user during the boot sequence.


Summary Checklist βœ…

  1. Need to configure a server on boot? Use user-data.
  2. Need to trigger a local script, API call, or Ansible? Use local-exec with terraform_data.
  3. Have absolutely no other choice and need to SSH into a box to run a command? Use remote-exec (but expect occasional headaches).

References & Extra Reading πŸ“š

Challenge

Your task is to write a complete Terraform configuration to automate a two-stage deployment process. First, you will provision an AWS EC2 instance and bootstrap it with a web server using the cloud-native user-data method. Second, after the instance is successfully created, you will trigger a local script to record the new server's IP. You will also demonstrate the configuration necessary for a remote-exec provisioner as a comparison.

Requirements:

  1. AWS Provider: Configure the AWS provider for the us-east-1 region.
  2. AMI Data Source: Use a data source to find the most recent Ubuntu 22.04 LTS AMI. The owner is Canonical, identified by the ID 099720109477. Use a filter to select the AMI name ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*.
  3. EC2 Instance: Define an aws_instance resource named web_server using a t2.micro instance type and the AMI ID from your data source.
  4. Bootstrapping (Preferred Method): Within the aws_instance resource, use the user-data argument to provide a bash script. This script must perform the following actions on the instance's first boot: update package lists, install nginx, and enable the nginx service to start on boot.
  5. Local Post-Provisioning Action (Best Practice): Define a terraform_data resource named ip_recorder. This resource must explicitly depend on the aws_instance.web_server. Attach a local-exec provisioner to this resource that executes a command to write the public IP of the web_server into a local file named server_ip.txt.
  6. Remote Execution (Last Resort): To demonstrate its complexity, also add a remote-exec provisioner directly to the aws_instance.web_server resource. It should include a connection block configured for SSH with the user ubuntu and a placeholder for a private key path (file("~/.ssh/tf-key.pem")). The provisioner itself should execute a single inline command to create a file at /tmp/provisioned.log containing the text Configured via remote-exec.

Expected result

Your final configuration should consist of four complete blocks: provider, data, aws_instance, and terraform_data.

  • The aws_instance.web_server resource must correctly reference the AMI ID from the data source using data.aws_ami.ubuntu.id.
  • It must contain a user-data argument with a multi-line bash script, typically defined using a heredoc (<<-EOF ... EOF). The script should contain the necessary apt-get update, apt-get install -y nginx, and systemctl enable --now nginx commands.
  • It must also contain a remote-exec provisioner block with an inline command array. A nested connection block is required, specifying type = "ssh", user = "ubuntu", private_key, and the host dynamically set to the instance's public IP (self.public_ip).
  • The terraform_data.ip_recorder resource must use the depends_on meta-argument to reference the EC2 instance ([aws_instance.web_server]).
  • The local-exec provisioner within terraform_data should have a command attribute that executes the shell command echo ${aws_instance.web_server.public_ip} > server_ip.txt, correctly interpolating the public IP attribute from the aws_instance resource.
hcl

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.