Terraform

Terraform

Infrastructure as Code for Any Cloud

devopsintermediate
43K+
GitHub Stars
active community
3,000+
Providers
cloud & services
20M+
Downloads/week
most popular IaC
2014
Released
by HashiCorp

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

macos(brew)
brew tap hashicorp/tap && brew install hashicorp/tap/terraform
linux(apt)
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg && sudo apt update && sudo apt install terraform

Ubuntu/Debian

windows(choco)
choco install terraform
linux(tfenv)
git clone https://github.com/tfutils/tfenv.git ~/.tfenv && tfenv install latest

Version manager

Verify installation: terraform version

Quick Start Steps

1

Create directory

Create project directory

mkdir my-terraform && cd my-terraform
2

Create main.tf

Write configuration

touch main.tf
3

Initialize

Download providers

terraform init
4

Plan

Preview changes

terraform plan
5

Apply

Create infrastructure

terraform apply
terraform init

Initialize directory, download providers

terraform plan

Preview changes before applying

terraform apply

Apply changes to infrastructure

terraform destroy

Destroy all managed infrastructure

terraform validate

Validate configuration syntax

terraform fmt

Format configuration files

terraform state list

List resources in state

terraform output

Read output values

Commands by Category

Pro Tips8

Always use remote state with locking

best-practice

S3 + DynamoDB for AWS. Prevents concurrent modifications and enables team collaboration.

Configure S3 backend with DynamoDB locking
Using local state files for team projects

Run terraform fmt before commits

workflow

Consistent formatting makes code reviews easier. Add pre-commit hook.

terraform fmt -check -recursive

Use -target sparingly

gotcha

Targeting specific resources can lead to state drift. Use for debugging, not regular workflow.

Pin provider versions explicitly

best-practice

Use version = "~> 5.0" not ">= 5.0". Prevents unexpected breaking changes.

version = "~> 5.0"
version = ">= 5.0" or no version constraint

Prefer for_each over count

best-practice

for_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-practice

Ensures what you reviewed is exactly what gets applied. Critical for production.

terraform plan -out=tfplan && terraform apply tfplan

Structure code with modules early

best-practice

Start with modules/ directory. Reusable, testable, maintainable. Don't wait until it's too late.

Use moved blocks for refactoring

best-practice

When 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

How do you manage different environments (dev, staging, prod) in Terraform?

Related Tools

ansiblekubernetesdocker