Terraform / Infrastructure as Code
Manage infrastructure with Terraform.
Core Concepts
State Management
- Store state remotely (S3, Terraform Cloud)
- Enable state locking (DynamoDB)
- Never edit state manually (use
terraform statecommands) - Isolate environments with workspaces or directories
Structure
terraform/ ├── modules/ │ ├── networking/ │ ├── compute/ │ └── database/ ├── environments/ │ ├── dev/ │ │ ├── main.tf │ │ ├── variables.tf │ │ └── terraform.tfvars │ ├── staging/ │ └── production/ └── backend.tf
Module Design
Module Interface
hcl# modules/compute/main.tf variable "instance_type" { type = string } variable "subnet_id" { type = string } output "instance_id" { value = aws_instance.app.id }
Module Best Practices
- Input validation (type constraints, validation blocks)
- Outputs for all useful values
- Versioned modules (Git tags, registry)
- Documentation (README per module)
- Test with Terratest
Remote Backend
hclterraform { backend "s3" { bucket = "my-terraform-state" key = "production/terraform.tfstate" region = "us-east-1" dynamodb_table = "terraform-locks" encrypt = true } }
Multi-Environment Strategy
- Workspaces: Simple, state separation only
- Directory structure: Full isolation, can diff configs
- Terragrunt: DRY config, repeatable structure
- Always: Plan in CI, approve, then apply
- No manual applies in production


