Introduction
After years of managing infrastructure with Terraform across dozens of projects, these are the patterns that have consistently proven their value.
Project Structure
A well-organized Terraform project scales much better:
infrastructure/
โโโ modules/
โ โโโ networking/
โ โ โโโ main.tf
โ โ โโโ variables.tf
โ โ โโโ outputs.tf
โ โโโ compute/
โ โโโ database/
โโโ environments/
โ โโโ dev/
โ โ โโโ main.tf
โ โ โโโ terraform.tfvars
โ โ โโโ backend.tf
โ โโโ staging/
โ โโโ production/
โโโ shared/
โโโ state-backend/
Remote State Management
Always use remote state with locking:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "production/terraform.tfstate"
region = "ap-southeast-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
}State Locking
State locking prevents concurrent modifications:
# If you need to force-unlock (use with caution)
terraform force-unlock LOCK_IDModule Design
Keep Modules Focused
Each module should manage a single concern:
module "vpc" {
source = "./modules/networking"
cidr_block = "10.0.0.0/16"
availability_zones = ["ap-southeast-1a", "ap-southeast-1b"]
environment = var.environment
}
module "eks" {
source = "./modules/compute"
vpc_id = module.vpc.vpc_id
subnet_ids = module.vpc.private_subnet_ids
cluster_version = "1.28"
}Validation and Testing
Variable Validation
variable "environment" {
type = string
validation {
condition = contains(["dev", "staging", "production"], var.environment)
error_message = "Environment must be dev, staging, or production."
}
}Plan Before Apply
# Always review the plan
terraform plan -out=tfplan
# Apply only the reviewed plan
terraform apply tfplanConclusion
Good Terraform practices compound over time. Invest in module design, state management, and validation early โ your future self will thank you.
powered by Gemini 2.5 Flash