Skip to main content

📋 Infrastructure as Code

Building servers with recipes

The Blueprint Analogy

Building a house:

ApproachOutcome
Without blueprints"I think the kitchen was here?" Every house is different. Mistakes happen.
With blueprintsSame plans, same house every time. Change once, rebuild exactly.

Infrastructure as Code (IaC) treats server and cloud setup like blueprints - define everything in code, rebuild identically every time.


Why Infrastructure as Code?

The Manual Nightmare

Old way to set up a server:

  1. Click "Create Instance" in AWS console
  2. Click "Configure networking..."
  3. Click "Add security rules..."
  4. SSH in, run various commands...
ProblemImpact
"What were those settings?"Can't reproduce exactly
No version historyWho changed what, when?
"Click ops" doesn't scaleCreate 100 servers how?
Knowledge in someone's headThey leave, knowledge lost

The IaC Solution

Define in code, run command, infrastructure created.

BenefitHow
Identical every timeSame code = same result
Version controlledGit tracks every change
ReviewablePull requests for infra!
ScalableCreate 100 servers the same way
Self-documentingThe code IS documentation

Core Principles

1. Declarative vs Imperative

ApproachStyleExample
Imperative"Do these steps""Install Apache. Configure port 80. Copy files."
Declarative"Make it look like this""I need a web server on port 80 with these files"

Most IaC tools are declarative - you describe the end state, the tool figures out how to get there.

2. Idempotency

Running the same code multiple times produces the same result:

Run #StateAction
1stNothing existsCreates infrastructure
2ndAlready matchesNo changes
3rdSomeone made manual changeFixes drift back to desired state

Typically fine to run repeatedly.

3. Version Control

infra/
├── main.tf           ← Infrastructure definition
├── variables.tf      ← Configurable values
└── README.md

Git history:
  "Added Redis cache cluster"
  "Increased web servers to 5"
  "Rolled back database change"

Full history of every infrastructure change!


How IaC Works

The Workflow

1. WRITE     → Define desired infrastructure in code
      ↓
2. PLAN      → "What changes will this make?"
      ↓
3. REVIEW    → Team reviews the plan
      ↓
4. APPLY     → Tool makes reality match code
      ↓
5. STATE     → Tool tracks what exists

State Management

Without StateWith State
"Does this server exist already?""Yes, server X exists (tracked in state)"
Might create duplicates!Knows exactly what to add/change/remove
"What did we deploy?"Complete inventory tracked

State is the source of truth for what infrastructure actually exists.


ToolCreatorScopeNotable Feature
TerraformHashiCorpMulti-cloudWidely used, many providers
CloudFormationAWSAWS-focusedDeep AWS integration, included
PulumiPulumiMulti-cloudUse real programming languages
AnsibleRed HatConfigurationAgentless, uses SSH
CDKAWSAWS-focusedTypeScript/Python for AWS

Terraform Example

resource "aws_instance" "web" {
  ami           = "ami-12345"
  instance_type = "t3.micro"
}

Declare what you want → Terraform creates it.


IaC vs Configuration Management

AspectIaC (Terraform, CloudFormation)Config Mgmt (Ansible, Puppet)
PurposeCreate infrastructureConfigure software
Scope"Create 3 servers in us-east-1""Install nginx on existing servers"
WhenBefore servers existAfter servers exist

Often used together: Terraform creates servers, Ansible configures them.


Benefits of IaC

Reproducibility

EnvironmentCommandResult
Developmentterraform applyDev environment
Stagingterraform applyIdentical staging
Productionterraform applyIdentical production

Same code, same environment, anywhere.

Disaster Recovery

Data center burns down?

Old WayIaC Way
Panicterraform apply
Rebuild manuallyInfrastructure restored
Takes weeksTakes minutes

All you need is the code (in version control).

Documentation

QuestionAnswer
"What resources do we have?"Read the code
"When was this created?"Check git history
"Who changed this?"Check git blame

The code IS the documentation.

Review Process

  1. Open pull request with infra changes
  2. terraform plan shows exactly what will change
  3. Team reviews before applying
  4. Merge and apply

No more: "Someone changed production, what happened?"


Common Patterns

Modules: Reusable Components

Define complex infrastructure once, reuse everywhere:

module "web_app" {
  source = "./modules/web-app"
  name   = "my-app"
  size   = "large"
}

"Large web app with load balancer, autoscaling, and database" in one line.

Environments

environments/
├── dev/       ← Smaller instances, lower cost
├── staging/   ← Production-like for testing
└── prod/      ← Full production scale

Same modules, different configurations per environment.


Common Mistakes

1. Manual Changes After IaC

ActionResult
Apply Terraform, then fix something in consoleNext apply reverts your change!
RuleALL changes through code

2. Not Reviewing Plans

Typically review terraform plan before applying:

Scary Plan OutputWhat Happened
"Destroying 47 resources"Typo in resource name
"Replacing database"Changed config that requires recreation

Read the plan each time you apply changes.

3. Storing State Locally

Local StateRemote State
Lost if laptop diesStored in S3/GCS/Terraform Cloud
Hard to shareTeam collaboration

4. Hardcoding Secrets

Avoid committing passwords or API keys in IaC code. Use:

  • Secret managers (AWS Secrets Manager, Vault)
  • Environment variables
  • Encrypted data sources

FAQ

Q: IaC for small projects?

Yes! Even simple setups benefit from reproducibility and documentation.

Q: Terraform vs CloudFormation?

CloudFormation: AWS-focused, included with AWS (you pay for the resources), deep AWS integration Terraform: Multi-cloud, larger community, more flexibility

Q: What about existing infrastructure?

Most tools can import existing resources. Then manage them as code going forward.

Q: How do I start?

Terraform + AWS/GCP free tier. Deploy a simple web server. Iterate from there.


Summary

Infrastructure as Code manages cloud and server resources through version-controlled, repeatable code files.

Key Takeaways:

  • Define infrastructure in code, not clicks
  • Declarative: describe end state, tool handles the rest
  • Idempotent: designed to converge when applied repeatedly
  • Version controlled: full history, code review
  • Reproducible: same code = same infrastructure
  • Popular tools: Terraform, CloudFormation, Pulumi
  • Try to avoid manual changes after applying!

IaC brings software engineering discipline to infrastructure!

Leave a Comment

Comments (0)

Be the first to comment on this concept.

Comments are approved automatically.