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?
- 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.
- 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. - 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.
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.
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.
# 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 β
- Need to configure a server on boot? Use
user-data. - Need to trigger a local script, API call, or Ansible? Use
local-execwithterraform_data. - 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:
- AWS Provider: Configure the AWS provider for the
us-east-1region. - AMI Data Source: Use a
datasource to find the most recent Ubuntu 22.04 LTS AMI. The owner is Canonical, identified by the ID099720109477. Use a filter to select the AMI nameubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*. - EC2 Instance: Define an
aws_instanceresource namedweb_serverusing at2.microinstance type and the AMI ID from your data source. - Bootstrapping (Preferred Method): Within the
aws_instanceresource, use theuser-dataargument to provide a bash script. This script must perform the following actions on the instance's first boot: update package lists, installnginx, and enable thenginxservice to start on boot. - Local Post-Provisioning Action (Best Practice): Define a
terraform_dataresource namedip_recorder. This resource must explicitly depend on theaws_instance.web_server. Attach alocal-execprovisioner to this resource that executes a command to write the public IP of theweb_serverinto a local file namedserver_ip.txt. - Remote Execution (Last Resort): To demonstrate its complexity, also add a
remote-execprovisioner directly to theaws_instance.web_serverresource. It should include aconnectionblock configured for SSH with the userubuntuand 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.logcontaining the textConfigured 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_serverresource must correctly reference the AMI ID from the data source usingdata.aws_ami.ubuntu.id. - It must contain a
user-dataargument with a multi-line bash script, typically defined using a heredoc (<<-EOF ... EOF). The script should contain the necessaryapt-get update,apt-get install -y nginx, andsystemctl enable --now nginxcommands. - It must also contain a
remote-execprovisioner block with aninlinecommand array. A nestedconnectionblock is required, specifyingtype = "ssh",user = "ubuntu",private_key, and thehostdynamically set to the instance's public IP (self.public_ip). - The
terraform_data.ip_recorderresource must use thedepends_onmeta-argument to reference the EC2 instance ([aws_instance.web_server]). - The
local-execprovisioner withinterraform_datashould have acommandattribute that executes the shell commandecho ${aws_instance.web_server.public_ip} > server_ip.txt, correctly interpolating the public IP attribute from theaws_instanceresource.