Terraform
Infrastructure as Code for Any Cloud
What is TF?
Terraform is a declarative Infrastructure as Code (IaC) tool that lets you define desired infrastructure state in configuration files. It compares desired state to current state, creates an execution plan, then applies changes across 3,000+ providers (AWS, Azure, GCP, Kubernetes, etc.). State is tracked, enabling incremental changes and drift detection.
Think of Terraform like a universal blueprint language
Imagine designing buildings across multiple cities with different building codes. Terraform is like having a universal blueprint language that works with any city's construction department. You write plans once, and Terraform translates them into the specific permits each city needs. If modifications are needed, you update the blueprint, and Terraform figures out what to change.
Key Features
Multi-Cloud Support
Single workflow for AWS, Azure, GCP, and 3000+ providers. No vendor lock-in.
Declarative Configuration
Define what you want, not how to get there. Terraform handles orchestration.
State Management
Tracks real infrastructure in state files. Enables incremental changes and drift detection.
Execution Plans
Preview changes before applying. Know exactly what will be created, modified, or destroyed.
When to Use
- Provisioning cloud infrastructure (VMs, networks, databases)
- Multi-cloud or hybrid cloud environments
- Reproducible environments (dev, staging, prod)
- Infrastructure needing version control and code review
- Complex dependencies between resources
- Team collaboration on infrastructure changes
When Not to Use
- Simple single-server deployments (overkill)
- Application configuration management (use Ansible/Chef)
- Kubernetes resource management (use Helm/kubectl)
- Real-time configuration changes
- One-off manual tasks in cloud console
Prerequisites
- Cloud provider account (AWS, Azure, GCP, etc.)
- Basic understanding of cloud concepts
- Command-line familiarity
- Text editor with HCL support (VS Code recommended)
Installation
brew tap hashicorp/tap && brew install hashicorp/tap/terraformwget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg && sudo apt update && sudo apt install terraformUbuntu/Debian
choco install terraformgit clone https://github.com/tfutils/tfenv.git ~/.tfenv && tfenv install latestVersion manager
Verify installation: terraform version
Quick Start Steps
Create directory
Create project directory
mkdir my-terraform && cd my-terraform
Create main.tf
Write configuration
touch main.tf
Initialize
Download providers
terraform init
Plan
Preview changes
terraform plan
Apply
Create infrastructure
terraform apply
terraform initInitialize directory, download providers
terraform planPreview changes before applying
terraform applyApply changes to infrastructure
terraform destroyDestroy all managed infrastructure
terraform validateValidate configuration syntax
terraform fmtFormat configuration files
terraform state listList resources in state
terraform outputRead output values
Commands by Category
Pro Tips8
Always use remote state with locking
best-practiceS3 + DynamoDB for AWS. Prevents concurrent modifications and enables team collaboration.
Configure S3 backend with DynamoDB lockingUsing local state files for team projectsRun terraform fmt before commits
workflowConsistent formatting makes code reviews easier. Add pre-commit hook.
terraform fmt -check -recursiveUse -target sparingly
gotchaTargeting specific resources can lead to state drift. Use for debugging, not regular workflow.
Pin provider versions explicitly
best-practiceUse version = "~> 5.0" not ">= 5.0". Prevents unexpected breaking changes.
version = "~> 5.0"version = ">= 5.0" or no version constraintPrefer for_each over count
best-practicefor_each uses keys (stable), count uses indices (fragile). Adding/removing items with count causes unwanted changes.
Use plan -out and apply the plan file
best-practiceEnsures what you reviewed is exactly what gets applied. Critical for production.
terraform plan -out=tfplan && terraform apply tfplanStructure code with modules early
best-practiceStart with modules/ directory. Reusable, testable, maintainable. Don't wait until it's too late.
Use moved blocks for refactoring
best-practiceWhen renaming resources or moving to modules, use moved {} to preserve state without destroy/create.
Key Facts8
State is the source of truth, not your config
Terraform compares desired state (config) to current state (state file) to determine changes.
terraform apply without a plan file re-runs plan
For production, always use: terraform plan -out=tfplan && terraform apply tfplan
Providers are plugins downloaded during init
Each provider (AWS, Azure) is a separate binary. terraform init downloads required providers.
Dependencies are automatic when using references
Referencing another resource (aws_vpc.main.id) creates implicit dependency. No need for depends_on.
Data sources read; resources create/modify
data {} queries existing infrastructure. resource {} manages infrastructure lifecycle.
Count creates a list, for_each creates a map
count: resource.name[0]. for_each: resource.name["key"]. Keys are stable; indices are not.
Terraform state can contain sensitive data
Passwords and secrets are stored in plain text in state. Always encrypt remote state.
Workspaces share code but have separate state
terraform.workspace returns current workspace name. Each workspace has isolated state.
Interview & Exam Practice2
State drift handling
Someone deleted a resource in AWS console that Terraform manages. What happens on next apply?
Environment management