SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
  • Deployment Strategies Overview
  • CI/CD Pipelines
  • Rolling Deployments
  • Blue-Green Deployments
  • Canary Releases
  • Feature Flags
  • A/B Testing Infrastructure
  • Schema Migrations
  • Rollbacks and Immutable Infrastructure
  • Multi-Region and Active-Active
  • Infrastructure as Code (Terraform)
  • Auto-Scaling Policies
  • Zero-Downtime Deployment
  • Chaos Engineering
  • Shadow Traffic and Dark Launches
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Operations and Security/Deployment Patterns

Infrastructure as Code (Terraform)

Describe servers, networks and databases in files, and let a tool build and change them for you.

⏱ 13 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Infrastructure as Code (IaC) means you describe your servers, networks, databases and permissions in text files, keep them in Git, and let a tool create and change them. Terraform is the best-known tool for this.

  • Declarative: you write what you want ("3 servers, 1 database"), not the steps. The tool works out the steps.
  • Plan, then apply: terraform plan shows what would change. terraform apply does it.
  • State: Terraform remembers what it built in a state file, so it can compare the code with reality.

02Concept: What is it?

Before IaC, people built servers by clicking in a cloud console or running a pile of scripts. Nobody could say exactly what was running, two environments slowly became different, and rebuilding after a disaster meant remembering what had been clicked. With IaC, the files are the truth. A pull request is how infrastructure changes, so changes can be reviewed, tested, and rolled back like code.

Terraform reads your files, asks each provider (a plugin for AWS, Azure, Google Cloud, Kubernetes, and many others) what exists, compares that to what you wrote, and builds a plan: a list of things to create, change or destroy. It then calls the cloud APIs in the right order, using the dependencies it found between resources.

The Terraform loop
📝Config files.tf in Git
→↓read
🧮Planconfig vs state vs reality
→↓approve
☁️Applycalls cloud APIs
→↓record
🗂️Statewhat exists now
Config is the wish. State is the memory. Plan is the difference. Apply makes it true.
A tiny example
resource "aws_instance" "web" {
  count         = 3
  ami           = var.image_id
  instance_type = "t3.small"
}
🧠Declarative, not a script
You do not write "create 1 more server". You change count from 2 to 3. If the world already has 3, Terraform does nothing. Running it twice gives the same result.

03Real-Life Example

🍵A Recipe Card vs a Cooking Show
A cooking show says "chop this, then stir that". If you start halfway, you get a mess. A recipe card says what the finished dish is, and a good chef looks at your kitchen, sees you already chopped the onions, and only does what is missing. IaC is the recipe card. The plan is the chef saying "here is what I am going to do" before touching anything.
Kitchen
Terraform
The recipe card
The .tf configuration files
The finished dish
The desired infrastructure
The chef's notes on what is already cooked
The state file
Checking the kitchen against the notes
Refresh, then plan
Saying what you will do before doing it
terraform plan
Cooking
terraform apply
A cousin who adds salt behind your back
Drift (a manual change in the console)
A recipe for sauce reused in many dishes
A module

04Why Do We Need It?

🔁Repeatable
The same files build staging and production. No more “works in staging” surprises.
👀Reviewable
A plan on a pull request shows exactly what will change before anyone approves.
🕰️History
Git shows who changed what and when, and you can go back.
🚑Fast recovery
After a disaster, rebuild an environment from code instead of from memory.
🧯Fewer manual mistakes
Less clicking in a console, less “I forgot a setting”.
📏Consistent rules
Policies (such as “no public buckets”) can be checked automatically on every plan.
If you cannot rebuild your infrastructure from files, you do not really know what you are running.

05Where Do We Use It?

🌍Multi-region setups
Stamp out the same stack in each region from one module.
🧪Temporary environments
Create a full test environment for a pull request, then destroy it.
☸️Kubernetes clusters
Create the cluster, networks and node groups from code.
🔐Access and policies
Roles, permissions and network rules kept in version control.
🚑Disaster recovery
Rebuild a lost environment quickly in another region.
📦Platform teams
Offer approved modules so product teams get safe defaults.

06Types / Parts / How It Works

The main Terraform ideas

IdeaWhat it isWhy it matters
ProviderA plugin that talks to one platform (AWS, Azure, GCP, Kubernetes...)It is how Terraform reaches the real world
ResourceOne thing to create: a server, a bucket, a ruleThe unit of change in a plan
Variables and outputsInputs to a configuration, and values it exportsOne config, many environments
StateA record of what Terraform manages and its real IDsHow plan knows what to change
ModuleA reusable bundle of resourcesShared, tested building blocks
Workspace / environmentA separate state for the same code (dev, staging, prod)Keeps environments apart
Plan and applyPreview the change, then do itA safety step before anything breaks

Where the state lives

Keep state remote, locked and small
Risky
💻State on a laptoplost, stale, or edited by two people
Better
🗄️Remote backendversioned, encrypted storage
🔒State lockingone apply at a time
A state file on one laptop is a risk. A shared remote one with locking is the norm.

Declarative vs imperative, and other tools

StyleExamplesNotes
Declarative, provisioningTerraform, OpenTofu, CloudFormation, Pulumi (uses real programming languages)Describe the end result. Best for creating cloud resources
Imperative scriptsShell scripts, cloud CLI commandsSteps run in order. Easy to start, hard to repeat safely
Configuration managementAnsible, Chef, PuppetSet up software inside machines, often used after provisioning
Risky Recommended
VisualizerEdit the config and read the planChange the server count, size or database engine and watch the plan show + (create), ~ (update), - (destroy) or -/+ (replace). Then switch on a manual change in the console (drift) without touching the config, and see Terraform propose to undo it.
Server size
Database
Database engine
Assets bucket
Someone changed things by hand in the console (drift)
What is really running
  • server.web[1] size=small
  • server.web[2] size=small
  • database.main engine=postgres 15
  • bucket.assets versioning=on
terraform plan
No changes. Your infrastructure matches the configuration.
To create
0
To update
0
To destroy
0
To replace
0
No changes. The real world already matches the config, so apply would do nothing. This is the goal: running plan on a healthy system shows an empty plan.

A simplified model. Real plans depend on the provider and on which settings can change in place. Here, changing the database engine is shown as a replacement. A hand-made resource that was never in the state is left alone by Terraform.

07How to Use It / Steps / Implementation

A safe workflow

  1. 1
    Put the code in Git
    Infrastructure changes go through pull requests, like application code.
  2. 2
    Use a remote state with locking
    Store state in versioned, encrypted storage so two applies cannot collide.
  3. 3
    Run plan on every pull request
    Post the plan as a comment so reviewers read exactly what will change.
  4. 4
    Apply on merge, from CI
    A pipeline with limited permissions does the apply. People do not apply from laptops.
  5. 5
    Split big stacks into small states
    One state per area (network, data, app) keeps plans fast and limits the blast radius.
  6. 6
    Use modules for repeated patterns
    Version them, so a change to a module is a deliberate upgrade.
  7. 7
    Detect drift on a schedule
    Run plan nightly. Anything it wants to change was changed by hand.
  8. 8
    Guard the dangerous parts
    Use prevent_destroy on key databases, and policy checks for risky changes.
⚠️Secrets in state
The state file can contain passwords and keys in plain text. Encrypt it, restrict who can read it, and pull secrets from a secrets manager instead of writing them in the code.
💡Read the plan like a reviewer
Look first for destroy and -/+ lines. A replaced database or load balancer is the kind of change that causes an outage.

08Key Terms to Know

TermMeaning in easy words
Infrastructure as CodeDescribing infrastructure in files that a tool applies
DeclarativeYou state the goal, and the tool works out the steps
ProviderA plugin that lets Terraform manage one platform
ResourceOne managed object, such as a server or a bucket
StateTerraform's record of what it created and the real IDs
PlanA preview of the changes Terraform will make
ApplyCarrying out the plan
DriftReal infrastructure that no longer matches the code
ModuleA reusable group of resources
WorkspaceA separate state for the same configuration
Blast radiusHow much can be harmed by one bad change
IdempotentRunning it again changes nothing if nothing is different

09Pros, Cons and Trade-offs

✅ Pros
  • Repeatable and reviewable
  • History and rollback through Git
  • Fast to rebuild an environment
  • Plan shows impact before it happens
  • Works across many clouds and services
⚠️ Cons
  • State must be protected and managed
  • Learning curve and its own language
  • A wrong apply can destroy real things
  • Drift needs active detection
  • Some changes force replacement, which can cause downtime

Trade-offs

ChoiceWe gainWe lose
One big stateSimple to startSlow plans, large blast radius
Many small statesSafer and fasterCross-state wiring to manage
Apply from CI onlyAudited and consistentSlower emergency fixes
Terraform (declarative)Clear end stateHard for complex logic
Pulumi (real code)Loops, functions, testsMore power to write confusing code

10Common Problems and Mistakes

Common mistakes

  1. Editing things by hand in the console. This creates drift, and the next apply may undo your fix.
  2. State on a laptop. It gets lost or overwritten. Use a remote backend with locking.
  3. Secrets in code or state. They end up in Git history or readable state files.
  4. Applying without reading the plan. A -/+ on a database can wipe data.
  5. One giant state. A small change plans for ages, and one mistake touches everything.
  6. No version pins. A provider or module update changes behaviour without a pull request.
  7. Importing without care. Existing resources must be brought into state before Terraform manages them, or it will try to create duplicates.

Things to watch

🔒Lock stuck
A crashed run can leave the state locked. Know how to release it safely.
🧩Implicit dependencies
Resources with no reference between them may be built in the wrong order.
🪪CI permissions
The pipeline can change everything, so give it the least access it needs.
🔄Provider upgrades
Major upgrades can change plans. Test them in a lower environment first.

11Real-World Examples

🧱Terraform and OpenTofu
Widely used declarative tools with providers for most clouds and SaaS products.
☁️AWS CloudFormation
AWS's own template-based IaC service, used inside AWS.
🧑‍💻Pulumi
Uses general-purpose languages (TypeScript, Python, Go) to describe infrastructure.
🔧Ansible
Often used to configure software on machines after they are created.
🚀GitOps
Tools such as Argo CD and Flux apply the desired state stored in Git to Kubernetes.
🏛️Platform teams
Offer shared modules so each product team starts from safe, approved building blocks.
Mini case: plan in a pull request
🔀Pull requestcount 2 to 3
→↓CI runs plan
📋Plan comment+1 server, 0 destroy
→↓review + merge
✅CI appliesstate updated
The plan is posted as a comment, a human checks it, then CI applies on merge.

12Related Topics to Read Next

CI/CD Pipelines→

Where plan and apply run, with checks and approvals.

Rollbacks and Immutable Infrastructure→

Replace servers instead of changing them by hand.

Secrets Management→

Keep passwords out of code and state.

Containers and Docker→

What often runs on the infrastructure you create.

Kubernetes Basics→

Clusters are commonly created with IaC.

Multi-Region and Active-Active→

Stamp out the same stack in many regions.

Auto-Scaling Policies→

Scaling rules are themselves defined as code.

Deployment Strategies Overview→

How new application versions reach the infrastructure.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔IaC: infrastructure described in files, kept in Git.
  • ✔Declarative: say the end result, the tool finds the steps.
  • ✔Loop: config → plan → apply → state.
  • ✔State: remote, locked, encrypted, and small.
  • ✔Plan: read the destroy and replace lines first.
  • ✔Drift: manual changes. Detect with scheduled plans.
  • ✔CI: plan on PR, apply on merge, least privilege.
  • ✔One line: “If you cannot rebuild it from files, you do not own it.”
← Previous
Multi-Region and Active-Active
Next →
Auto-Scaling Policies