What is Terraform?
Terraform lets you define infrastructure in code (HCL — HashiCorp Configuration Language). Instead of clicking through cloud dashboards, you write declarative configs and terraform apply.
Installation
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp.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 -y terraform
Basic Structure
project/
├── main.tf # Primary resources
├── variables.tf # Input variables
├── outputs.tf # Output values
├── terraform.tfvars # Variable values (gitignored)
└── providers.tf # Provider configuration
Example: VPS with DNS
# providers.tf
terraform {
required_providers {
digitalocean = {
source = "digitalocean/digitalocean"
version = "~> 2.0"
}
cloudflare = {
source = "cloudflare/cloudflare"
version = "~> 4.0"
}
}
}
# variables.tf
variable "domain" {
type = string
default = "example.com"
}
variable "region" {
type = string
default = "nyc1"
}
# main.tf
resource "digitalocean_droplet" "web" {
name = "web-server"
region = var.region
size = "s-2vcpu-4gb"
image = "ubuntu-24-04-x64"
ssh_keys = [digitalocean_ssh_key.deploy.fingerprint]
}
resource "cloudflare_record" "web" {
zone_id = var.cloudflare_zone_id
name = var.domain
value = digitalocean_droplet.web.ipv4_address
type = "A"
proxied = true
}
# outputs.tf
output "server_ip" {
value = digitalocean_droplet.web.ipv4_address
}
Workflow
# Initialize (download providers)
terraform init
# Preview changes
terraform plan
# Apply changes
terraform apply
# Destroy everything
terraform destroy
State Management
Terraform tracks resources in a state file. For teams, store state remotely:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
}
}
Best Practices
| Practice | Why |
|---|---|
| Remote state with locking | Prevent concurrent modifications |
.tfvars in .gitignore |
Don't commit secrets |
terraform plan before apply |
Always review changes |
| Use modules for reusable infra | DRY principle |
| Pin provider versions | Prevent breaking updates |
| Tag all resources | Track costs and ownership |
Warning Never store
terraform.tfstatein git — it may contain secrets. Use remote backends (S3, Terraform Cloud, etc.) for team collaboration.