Skip to content

Intermediate · Infrastructure as code with Terraform · topic 30 of 53 · 25 min

Why infrastructure as code

Explanation

Infrastructure as code (IaC) means you write your servers, networks and databases as text files instead of clicking in a web console. The files live in Git, so changes are reviewed, repeatable and easy to rebuild after a disaster. Most IaC tools are declarative: you describe the end result and the tool works out the steps. Running the same code twice should change nothing the second time (idempotency).

The problem with click-ops

Infrastructure is everything your application runs on: virtual machines, networks, firewalls, load balancers, databases, storage buckets and DNS records. In a small project, someone usually creates these by clicking in the cloud console (the website of AWS, Azure or Google Cloud). People call this "click-ops".

Click-ops works for one server on day one. It fails as the system grows. Nobody remembers which 40 settings were chosen. The staging server is slightly different from production, so a bug appears only in production. A new engineer cannot see why a firewall port is open. And if the region has an outage, nobody can rebuild the whole setup quickly, because the "documentation" is in one person's memory.

A server that was built and then changed by hand many times becomes a snowflake server: unique, fragile and impossible to copy exactly. Everyone is afraid to touch it.

Think of it like this: Click-ops is like cooking a family dish by feel every time: it tastes a little different each day, and when Grandma is away nobody can make it. Infrastructure as code is the written recipe with exact quantities. Anyone can follow it, you can improve it, and the dish comes out the same in any kitchen.

What infrastructure as code gives you

Infrastructure as code (IaC) means describing infrastructure in text files and letting a tool create it. Because the files are plain text in Git, you get all the habits you already use for application code.

  • Repeatability: the same files build dev, staging and production, so they really are the same.
  • Review: a change is a pull request. A teammate can see "this opens port 22 to the whole internet" before it happens.
  • History and audit: git log shows who changed what and why. Banks and hospitals need this for audits.
  • Disaster recovery: if a region or an account is lost, you run the code again in another place.
  • Speed: a new environment for a test or a new customer takes minutes, not days of tickets.

Declarative versus imperative

An imperative approach lists the steps: "create a VM, then attach a disk, then open port 443". A declarative approach describes the end result: "there should be one VM with this disk and port 443 open". The tool compares that wish with what exists and works out the steps itself.

Declarative code is easier to rerun. If the VM already exists, a declarative tool does nothing. An imperative script would try to create a second VM, or fail. Terraform, CloudFormation and Kubernetes manifests are declarative. A bash script that calls the cloud CLI is imperative.

Idempotency

An operation is idempotent when running it once or ten times gives the same result. "Make sure the bucket exists" is idempotent. "Create a bucket" is not. Good IaC is idempotent: the second run reports "no changes". That makes it safe to run often, for example on every merge.

output
desired (code):  web-vm, logs-bucket, db
actual (cloud):  web-vm, old-test-vm

plan:  create logs-bucket, create db, delete old-test-vm
       web-vm is unchanged, so nothing happens to it
A declarative tool diffs desired against actual and makes only the changes needed.

Three families of tools

FamilyJobExamples
ProvisioningCreate and delete cloud resources: networks, VMs, databases, DNSTerraform, OpenTofu, AWS CloudFormation, Azure Bicep, Pulumi
Configuration managementSet up the software inside servers: packages, files, users, servicesAnsible, Chef, Puppet, SaltStack
Image buildingBake a ready machine image (for example an AWS AMI) with software already installedPacker

Pulumi lets you write infrastructure in general programming languages such as Python or TypeScript. CloudFormation is AWS-only and uses YAML or JSON. Terraform works with hundreds of providers (AWS, Azure, Google Cloud, Cloudflare, GitHub and more) using one language, HCL. This module uses Terraform; the next module covers Ansible.

Immutable infrastructure

Mutable infrastructure means you log in and change running servers (patch them, edit files). Immutable infrastructure means you never change a running server: you build a new image with the change, start new servers from it and delete the old ones. Containers work this way too. Immutable servers cannot drift into snowflakes, and rollback is simply "start the old image again".

Common mistakes

Careful: Mixing IaC with manual changes. If someone "quickly fixes" a setting in the console, the code no longer matches reality, and the next apply may silently undo the fix. Make the change in code, or bring the manual change back into code at once.
Careful: Writing IaC as one giant imperative script. Prefer declarative tools so reruns are safe. Also keep secrets (passwords, keys) out of the files: use a secret manager or protected CI variables.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Why infrastructure as code · 1/8

Infrastructure as code

In this lesson you will learn why teams describe their infrastructure as code instead of clicking in a cloud console.

Prefer a video by a teacher? Find free videos on “infrastructure as code explained declarative vs imperative for beginners” on YouTube ↗

In real life: Rebuilding a college exam portal in another region

A university in Pune hosts its exam-results portal on AWS in the Mumbai region. On results day the traffic jumps tenfold. Because the whole setup (network, load balancer, autoscaling group, database, DNS) is in Terraform files in Git, the team creates an identical copy in the Hyderabad region for testing in 20 minutes, load-tests it, and deletes it the same evening. When an auditor asks who opened a database port last March, git log answers in seconds.

bash
git log --oneline -- network/
# a1b9f20 Allow DB port only from app subnet (reviewed by Ravi)
# 7c03e11 Add Hyderabad DR copy of the network
Every infrastructure change has an author, a reason and a reviewer.

Practice (0/3 done)

Task 1 · Question

Which statement is declarative?

Task 2 · Code · Python

Build a mini plan. desired and actual are dicts that map a resource name to a dict of its settings. Write plan_actions(desired, actual) that returns a dict with three sorted lists: "create" (in desired but not actual), "update" (in both, but settings differ) and "delete" (in actual but not desired). Resources that are the same appear in no list.

Task 3 · Practice

Your team runs a small online pharmacy. Everything was created by clicking in the AWS console. Write a short note (8 to 12 lines) to your manager explaining three risks of the current setup and how infrastructure as code reduces each one.

Quick quiz

Question 1

1.What is a snowflake server?

Question 2

2.You run the same correct IaC code a second time with no other changes. What should happen?

Question 3

3.Which tool is mainly for configuring software inside existing servers?

Question 4

4.In immutable infrastructure, how do you apply an OS patch?

Question 5

5.A teammate fixes a firewall rule in the console during an incident. What is the IaC risk?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is a snowflake server?

Answer: A server changed by hand so often that nobody can rebuild it exactly

Manual changes pile up until the server is unique and fragile, like a snowflake.

You run the same correct IaC code a second time with no other changes. What should happen?

Answer: Nothing: it reports no changes

Good IaC is idempotent: a rerun finds that reality already matches the code.

Which tool is mainly for configuring software inside existing servers?

Answer: Ansible

Ansible, Chef and Puppet are configuration management tools. Terraform and CloudFormation provision resources; Packer builds images.

In immutable infrastructure, how do you apply an OS patch?

Answer: Build a new image with the patch and replace the servers

Immutable servers are never changed in place; you replace them with servers from a new image.

A teammate fixes a firewall rule in the console during an incident. What is the IaC risk?

Answer: The code no longer matches reality, and the next apply may undo the fix

Manual changes cause drift. Put the fix into code too, or the next apply can revert it.

In an immutable infrastructure approach, how do you apply an OS security patch?Related

Answer: Build a new image with the patch, start new servers from it and remove the old ones

Immutable servers are never changed in place; you replace them with new ones built from an updated image.

From Why infrastructure as code

Why should terraform.tfstate not be committed to Git?Related

Answer: It can contain secrets in plain text and it must be shared with locking, which Git cannot do

State can hold passwords and keys, and it needs locking to stop two applies at once. Use an encrypted remote backend.

From Terraform for the cloud

In a good IaC workflow, when does the change get applied to production?Related

Answer: After the PR is reviewed and merged, by the pipeline, usually with an approval step

The pipeline applies reviewed, merged code, with a manual approval for production.

From IaC in a team: reviews, pipelines and policy

Which package gives you ansible-playbook on RHEL 9?Related

Answer: ansible-core

ansible-core.

From What Ansible is and how it works

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Infrastructure as code with Terraform” before its exam: Terraform basics: HCL, providers, resources and the workflow, Terraform state, backends and drift, Modules, environments and Terraform in CI.
  2. Module 7 exam: Infrastructure as code with Terraform · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Configuration management with Ansible, and YAML. 53 topics left in the course before the final exam.

← Previous: Deployment strategies, feature flags and GitOps