Getting Started with Terraform
Discover Terraform on Debian or Ubuntu: providers, plan, apply, state management and secret protection, with a generic example.
On this page
Your values
Enter them once and the commands in this guide update.
Terraform describes infrastructure in text files, compares that description with what already exists, then applies only the necessary changes. It relies on providers, which know how to talk to a given service.
This guide presents the basics with an example that works without any external account: Terraform generates a random password, an Ansible inventory and a local configuration file.
| Term | Meaning |
|---|---|
| Provider | Plugin that gives access to a service or resource |
| Resource | Object managed by Terraform |
| Variable | Input value for the configuration |
| Output | Value exposed after applying |
| Plan | List of changes that Terraform proposes |
| State | File that links the configuration to real objects |
Prerequisites
- A machine running Debian 12/13 or Ubuntu 22.04/24.04: your computer or an administration server
- A user with
sudo - Outbound HTTPS access to
apt.releases.hashicorp.comandregistry.terraform.io
Terraform does not listen on any port and this example does not require opening any inbound port.
Install Terraform
Add the official HashiCorp repository, then install the package:
sudo apt update
sudo apt install -y wget gpg lsb-release
wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update
sudo apt install -y terraform
terraform versionCreate the project
mkdir -p ~/terraform-demo
cd ~/terraform-demoDeclare Terraform and the providers
Create versions.tf:
terraform {
required_version = ">= 1.11"
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.9"
}
random = {
source = "hashicorp/random"
version = "~> 3.9"
}
}
}Declare the variables
Create variables.tf:
variable "ssh_user" {
description = "SSH user for the servers"
type = string
}
variable "servers" {
description = "Servers to add to the inventory (name => IP address)"
type = map(string)
validation {
condition = length(var.servers) > 0
error_message = "Declare at least one server."
}
}Give them a value in terraform.tfvars, which is loaded automatically:
ssh_user = "YOUR_USER"
servers = {
web1 = "YOUR_SERVER_IP"
}Describe the resources
Create an inventory template inventory.tftpl:
[web]
%{ for name, ip in servers ~}
${name} ansible_host=${ip} ansible_user=${ssh_user}
%{ endfor ~}Then create main.tf:
resource "random_password" "app_token" {
length = 32
special = false
}
resource "local_file" "inventory" {
filename = "${path.module}/generated/inventory.ini"
file_permission = "0644"
content = templatefile("${path.module}/inventory.tftpl", {
servers = var.servers
ssh_user = var.ssh_user
})
}
resource "local_sensitive_file" "app_env" {
filename = "${path.module}/generated/app.env"
file_permission = "0600"
content = "APP_TOKEN=${random_password.app_token.result}\n"
}And outputs.tf:
output "inventory_path" {
description = "Path of the generated inventory"
value = local_file.inventory.filename
}
output "app_token" {
description = "Token generated for the application"
value = random_password.app_token.result
sensitive = true
}Exclude local files from Git
Create .gitignore before your first commit:
.terraform/
*.tfstate
*.tfstate.*
*.tfvars
*.tfplan
generated/Do, however, commit .terraform.lock.hcl, which pins the exact provider versions.
Initialize and validate
terraform init
terraform fmt
terraform validate| Command | Effect |
|---|---|
terraform init |
Downloads the providers and prepares the folder |
terraform fmt |
Normalizes the formatting |
terraform validate |
Checks the consistency of the configuration |
Plan and apply
Save the plan so you apply exactly what you reviewed:
terraform plan -out=demo.tfplan
terraform apply demo.tfplanIn a plan, + marks a creation, ~ a change, - a deletion and -/+ a replacement. Always read these lines before applying, especially deletions and replacements.
Check the result:
terraform output
terraform output -raw inventory_path; echo
cat generated/inventory.ini
ls -l generated/
terraform planThe app.env file must have the permissions -rw-------, the app_token output must appear as <sensitive>, and the last plan must report No changes.
Change the infrastructure
Add a server in terraform.tfvars:
servers = {
web1 = "YOUR_SERVER_IP"
web2 = "SECOND_SERVER_IP"
}terraform plan -out=demo.tfplan
terraform apply demo.tfplanThe plan reports the replacement of the inventory file only (1 to add, 1 to destroy): the token stays the same. The generated file can then be used by a playbook, as in the Automate Your Servers with Ansible guide.
Understand the state
After apply, Terraform records what it manages in terraform.tfstate. Inspect it with the provided commands, without editing it by hand:
terraform state list
terraform state show local_file.inventory| Command | Usage |
|---|---|
terraform state list |
List the tracked resources |
terraform state show ADDRESS |
Display a resource |
terraform state mv SOURCE DESTINATION |
Rename a resource without recreating it |
terraform state rm ADDRESS |
Stop tracking a resource, without deleting it |
terraform import ADDRESS ID |
Attach an existing object, if the provider allows it |
Restrict the permissions of local files to the minimum:
chmod 600 terraform.tfstate terraform.tfstate.backup demo.tfplan 2>/dev/null || trueManage secrets
Do not put secrets in .tf files. Pass them through a TF_VAR_ environment variable instead:
variable "api_token" {
description = "API token used by the provider"
type = string
sensitive = true
}read -rs TF_VAR_api_token
export TF_VAR_api_token
terraform plan -out=demo.tfplan
unset TF_VAR_api_tokenIf the value is only used to configure a provider or to feed a write-only argument, declare it as ephemeral: Terraform then stores it neither in the state nor in the plan.
variable "api_token" {
description = "API token used by the provider"
type = string
sensitive = true
ephemeral = true
}An ephemeral variable must be provided again during terraform apply, and it cannot be used in just any argument. For a secrets vault, see the Install HashiCorp Vault guide.
Store the state remotely
As soon as several people or machines use the project, put the state in remote storage that is encrypted, private and locked. Here is a generic example with the s3 backend, to add inside the terraform block:
terraform {
backend "s3" {
bucket = "mon-etat-terraform"
key = "demo/terraform.tfstate"
region = "eu-west-1"
encrypt = true
use_lockfile = true
}
}Provide the credentials through the environment, never in this block, then migrate the existing state:
terraform init -migrate-stateUse another provider
The logic stays the same for any service that has a provider. Look it up in the Terraform registry, read its documentation and check who maintains it. The general form is as follows. editeur/service and the arguments are fictional:
terraform {
required_providers {
service = {
source = "editeur/service"
version = "~> 1.0"
}
}
}
provider "service" {
api_token = var.api_token
}Give the API token only the permissions it strictly needs, and start on a test project: an apply really acts on the account's resources.
Update
Terraform is updated with APT. Providers are updated within the limits of version:
sudo apt update
sudo apt install --only-upgrade terraform
terraform init -upgrade
terraform planReview the plan, then commit the .terraform.lock.hcl file if it has changed.
Back up
Keep the configuration and .terraform.lock.hcl in a private Git repository. For the state, enable versioning on the remote storage. With a local state, create a protected copy:
install -m 600 /dev/null "$HOME/terraform-demo-$(date +%F).tfstate"
terraform state pull > "$HOME/terraform-demo-$(date +%F).tfstate"This copy contains secrets: store it encrypted and off the server. If the state is lost, Terraform no longer knows which objects it manages.
Destroy the resources
Preview the deletion, then apply it:
terraform plan -destroy -out=destroy.tfplan
terraform apply destroy.tfplanIn this example, only the local files and the token are deleted. With a real provider, this operation can erase services and their data.
Troubleshooting
Inconsistent dependency lock file
The requested providers do not match the lock file. After checking the change:
terraform init -upgradeBackend initialization required
The backend configuration has changed. Run terraform init again, or terraform init -migrate-state to move the state.
Error acquiring the state lock
Another run holds the lock, or a run was interrupted. First check that no command is in progress. Only then, use the displayed ID:
terraform force-unlock LOCK_IDSaved plan is stale
The state has changed since the plan was created. Generate a new plan, review it, then apply it.
Failed to query available provider packages
Check the provider name, the version constraint and access to registry.terraform.io:
curl -I https://registry.terraform.io/.well-known/terraform.jsonNo value for required variable
Set the variable in terraform.tfvars, with -var, or with TF_VAR_name.
The plan wants to replace a resource
Look for the forces replacement mention in the plan. If you only renamed a resource, use terraform state mv or a moved block rather than accepting its recreation.