Intermediate · Infrastructure as code with Terraform · topic 30 of 53 · 25 min
Why infrastructure as code
Explanation
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.
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.
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 itThree families of tools
| Family | Job | Examples |
|---|---|---|
| Provisioning | Create and delete cloud resources: networks, VMs, databases, DNS | Terraform, OpenTofu, AWS CloudFormation, Azure Bicep, Pulumi |
| Configuration management | Set up the software inside servers: packages, files, users, services | Ansible, Chef, Puppet, SaltStack |
| Image building | Bake a ready machine image (for example an AWS AMI) with software already installed | Packer |
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
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
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.
git log --oneline -- network/
# a1b9f20 Allow DB port only from app subnet (reviewed by Ravi)
# 7c03e11 Add Hyderabad DR copy of the networkPractice (0/3 done)
Which statement is declarative?
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.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Terraform basics: HCL, providers, resources and the workflowInfrastructure as code with Terraform · same module
- Terraform state, backends and driftInfrastructure as code with Terraform · same module
- Modules, environments and Terraform in CIInfrastructure as code with Terraform · same module
- Why infrastructure as codeCloud Computing (AWS, Azure, Google Cloud) · Infrastructure as code
- Terraform for the cloudCloud Computing (AWS, Azure, Google Cloud) · Infrastructure as code
- IaC in a team: reviews, pipelines and policyCloud Computing (AWS, Azure, Google Cloud) · Infrastructure as code
Questions people ask about this
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.
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.
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.
Which package gives you ansible-playbook on RHEL 9?Related
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
- 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.
- Module 7 exam: Infrastructure as code with Terraform · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Configuration management with Ansible, and YAML. 53 topics left in the course before the final exam.