π§ Terraform Complete Reference Guide
Authorβs Note:
This guide is based on a real-world setup used for automating Proxmox, Ansible, and other infrastructure tasks.
All commands are tested on Ubuntu 22.04 with Terraform v1.9+.
βοΈ Introduction: Why Terraform?
Terraform is an open-source Infrastructure as Code (IaC) tool by HashiCorp that allows you to define, provision, and manage infrastructure consistently across cloud and on-prem environments.
It works by describing what your infrastructure should look like, not how to build it. Terraform then interacts with APIs to make that configuration a reality.
Common use cases:
- Provisioning VMs and containers (e.g., Proxmox, VMware, AWS, Azure)
- Managing networks, firewalls, and DNS records
- Automating hybrid setups with repeatable templates
π‘ Tip: Terraform is declarative. You describe the desired state, and Terraform ensures it matches reality.
π§° Installing Terraform
On Ubuntu / Debian
sudo apt update && sudo apt install -y wget unzip gnupg software-properties-common
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install terraform -y
Verify installation:
terraform -version
terraform -help
terraform providers
π‘ Tip: Always install Terraform from HashiCorpβs repo for the latest stable version.
π§± Terraform Directory Structure
Organize your Terraform projects like this:
/home/automation/terraform/project/
βββ main.tf
βββ variables.tf
βββ terraform.tfvars
βββ outputs.tf
βββ .terraform/
To view your structure:
tree -a /home/automation/terraform/project/
βοΈ Terraform Core Commands
| Command | Description | Example |
|---|---|---|
terraform init |
Initializes Terraform working directory | terraform init |
terraform validate |
Checks syntax validity | terraform validate |
terraform plan |
Shows proposed changes | terraform plan -var-file=prod.tfvars |
terraform apply |
Provisions infrastructure | terraform apply -auto-approve |
terraform destroy |
Removes all managed resources | terraform destroy |
terraform refresh |
Syncs state file with live infra | terraform refresh |
terraform output |
Displays declared outputs | terraform output container_ip |
π‘ Tip: Always run
terraform planbefore applying to verify intended changes.
π§© Terraform Building Blocks
Providers
Connect Terraform to external systems.
provider "proxmox" {
pm_api_url = "https://10.0.0.3:8006/api2/json"
pm_api_token_id = "terraform@pve!tf-token"
pm_api_token_secret = "<SECRET>"
}
Resources
Define what Terraform will create or manage.
resource "proxmox_lxc" "web" {
hostname = "web01"
cores = 2
memory = 1024
ostemplate = "local:vztmpl/ubuntu-22.04-standard_22.04-2_amd64.tar.zst"
}
Variables
Define flexible configuration options.
variable "vm_memory" {
description = "Memory for the VM"
type = number
default = 2048
}
Outputs
Display values after apply.
output "container_ip" {
value = proxmox_lxc.web.network[0].ip
}
πΎ Terraform State Management
Terraform maintains a state file (terraform.tfstate) that records resource metadata.
State Commands
terraform state list
terraform state show proxmox_lxc.web
terraform state rm proxmox_lxc.db
terraform state mv proxmox_lxc.app proxmox_lxc.application
terraform refresh
| Command | Purpose |
|---|---|
state list |
Lists all tracked resources |
state show |
Displays resource details |
state rm |
Removes orphaned entries |
state mv |
Moves or renames resources in state |
refresh |
Updates state to reflect live infra |
β οΈ Caution: Never manually edit
terraform.tfstate. Back it up regularly.
π§ Variables and Workspaces
Passing Variables
terraform apply -var "vm_name=webserver"
terraform apply -var-file=prod.tfvars
Environment Variable Override
export TF_VAR_vm_name=appserver
terraform plan
Workspaces for Multiple Environments
terraform workspace list
terraform workspace new staging
terraform workspace select staging
terraform workspace delete staging
π‘ Each workspace maintains its own state file β ideal for separating dev/prod environments.
π§ Importing Existing Resources
To import existing infrastructure under Terraform control:
terraform import proxmox_lxc.web proxmox/lxc/101
terraform import proxmox_vm_qemu.vm1 pve/qemu/100
terraform state list
π§ Pro Note: Always review and align imported resources with your configuration files to avoid drift.
π§° Debugging and Logging
Enable verbose output:
TF_LOG=TRACE terraform apply
TF_LOG=DEBUG terraform plan
TF_LOG_PATH=/tmp/terraform.log terraform apply
| Log Level | Description |
|---|---|
| TRACE | Full execution details |
| DEBUG | Provider interactions |
| INFO | Normal runtime logs |
| WARN | Warnings |
| ERROR | Critical failures |
π‘ Tip: Use logging when diagnosing provider authentication or network issues.
π§© Providers and Modules
Providers
terraform providers
terraform init -upgrade
Modules
Reusable blocks for organization.
Example structure:
/modules/lxc/
βββ main.tf
βββ variables.tf
βββ outputs.tf
Usage in root configuration:
module "containers" {
source = "./modules/lxc"
name = "web01"
vlan = 10
ip = "10.0.10.50"
}
π Terraform File Commands
| Command | Description |
|---|---|
terraform fmt |
Auto-format .tf files |
terraform validate |
Syntax validation |
terraform graph |
Visualize dependencies |
terraform show |
Show current configuration |
terraform console |
Interactive mode for evaluating expressions |
Example:
terraform console
> var.memory_size * 2
π§Ύ Real-World Example: Proxmox Container
provider "proxmox" {
pm_api_url = "https://10.0.0.3:8006/api2/json"
pm_api_token_id = "terraform@pve!tf-token"
pm_api_token_secret = "<SECRET>"
}
resource "proxmox_lxc" "containers" {
hostname = "demo-lxc"
target_node = "pve-node"
ostemplate = "local:vztmpl/ubuntu-22.04-standard_22.04-2_amd64.tar.zst"
cores = 2
memory = 1024
unprivileged = true
start = true
network {
name = "eth0"
bridge = "vmbr0"
ip = "10.0.10.25/24"
gw = "10.0.10.1"
}
ssh_public_keys = file("/home/automation/.ssh/id_rsa.pub")
}
Run the full workflow:
terraform init
terraform validate
terraform plan
terraform apply -auto-approve
terraform output
π Destroying and Cleanup
terraform destroy
terraform destroy -target=proxmox_lxc.containers["demo-lxc"]
rm -rf .terraform terraform.tfstate*
terraform state rm proxmox_lxc.containers["demo-lxc"]
π‘ Tip: Use
terraform state rmto untrack resources without deleting them.
π§© Advanced Commands
| Command | Description |
|---|---|
terraform plan -out=plan.tfplan |
Save a plan for later apply |
terraform apply plan.tfplan |
Apply from saved plan |
terraform workspace show |
Display current workspace |
terraform providers lock |
Lock provider versions |
terraform version |
Check Terraform binary version |
terraform fmt -recursive |
Format multiple directories |
π§ Best Practices
- Use version control (Git) for
.tffiles. - Backup
terraform.tfstateor use remote state (Terraform Cloud, S3). - Use environment-specific
tfvarsfiles (dev, prod). - Store sensitive variables in environment variables or Vault.
- Always tag resources for traceability.
π§© Example:
tags = { environment = "prod", managed_by = "terraform" }
βοΈ Troubleshooting
| Problem | Cause | Solution |
|---|---|---|
| Provider authentication failed | Wrong token/permissions | Recheck API credentials |
| State drift | Manual changes in environment | Run terraform refresh |
| Resource already exists | Conflict with unmanaged infra | Use terraform import |
| Plan shows no changes | Cached state | Run terraform plan -refresh-only |
π§Ύ Terraform Command Cheat Sheet
| Category | Command | Purpose |
|---|---|---|
| Init & Setup | terraform init -upgrade |
Initialize or update providers |
| Planning | terraform plan -out=plan.tfplan |
Generate plan file |
| Apply | terraform apply plan.tfplan |
Execute plan |
| Destroy | terraform destroy |
Remove infrastructure |
| Validate | terraform validate |
Check syntax |
| Format | terraform fmt -recursive |
Format code |
| State | terraform state list |
List tracked resources |
| Workspace | terraform workspace list |
Manage environments |
| Debug | TF_LOG=DEBUG terraform apply |
Debug mode |
| Output | terraform output |
Display output variables |
β Conclusion
Terraform acts as the foundation of infrastructure automation β defining, provisioning, and maintaining systems in a repeatable, declarative way.
When combined with Proxmox and Ansible, it forms a complete, hands-free automation pipeline:
Terraform defines β Proxmox provisions β Ansible configures.
π‘ Use this guide as both a command reference and a foundation for scaling automation across environments.
End of Guide β Terraform Complete Reference