Course contents · Lesson 15 of 19

Infrastructure as Code Explained for Beginners

Infrastructure as Code · Lesson 15 of 19 · 11 min Hands-on

A teammate built your test environment last spring by clicking through the cloud provider's website: a network, two servers, a storage bucket and dozens of settings. Now you need an identical copy, and that teammate has left. Nobody wrote the settings down or knows what has changed since. Infrastructure as code prevents exactly this. This lesson explains what it is, why declarative tools beat scripts, and which tools teams use.

The problem with clicking in a console

The console is the provider's website, where you create things by filling in forms. Each thing you create there, such as a virtual machine, a bucket or a network, is a resource. The console is good for exploring, but once a team depends on it, four problems appear.

It is slow: every new copy means filling in every form again. It is hard to review: nobody can check your clicks before you make them. It is impossible to repeat exactly: on a busy day, people skip a step or pick another option.

And nobody knows what changed. An audit log such as CloudTrail, from lesson 12, records which call changed a setting, but not why, and it is no plan you can rebuild from.

The diagram builds one bucket both ways. Notice step 8: skipped on Friday, so the two buckets differ, while the file gives the same bucket every run.

Side-by-side comparison. Left, clicking in a console: ten illustrative manual steps from sign in to confirm. On Monday all ten are done and the bucket is tagged team=shop; on Friday step 8, add tags, is skipped and the bucket has no tags, so two runs give two different buckets. Right, one file applied twice: bucket.tf declares an aws_s3_bucket called shop-site-example with the tag team = shop. Apply number 1 creates the bucket, apply number 2 finds nothing to change, so every run gives the same name and tags
By hand, every run can miss a step; a file gives the same bucket every time.

Infrastructure as code in one definition

Infrastructure as code (IaC) means describing servers, networks and storage in text files that a tool turns into real resources. You keep the files like any other code and run the tool whenever they change.

It works because every cloud action is a call to the provider's API, the interface other programs call, as you saw with S3 in lesson 6. The console makes those calls when you click; an IaC tool makes them from your file.

Here is one bucket in Terraform's language, which lesson 16 teaches line by line. A tag, the label from lesson 13, names the team that owns it:

resource "aws_s3_bucket" "site" {
  bucket = "shop-site-example"
  tags   = { team = "shop" }
}

There is no "click Create" and no list of steps. The file only says which bucket should exist and what it should look like.

Declarative vs imperative

An imperative approach lists the steps to run: "start two servers". A declarative approach describes the result, called the desired state: "make sure two servers exist". The bucket file is declarative. A shell script, a file of terminal commands run one after another, is usually imperative.

Run the imperative script twice and you have four servers. Apply the declarative file twice and the tool sees that two already exist, so it does nothing. Something you can repeat without changing the result is idempotent, which is why declarative IaC is safe to re-run.

The lab's script, trimmed, makes up a new bucket name on every run, then creates it with the AWS command-line tool, pointed at a local emulator:

bucket="iac-demo-$(date -u +%Y%m%d-%H%M%S)-$RANDOM"
aws --endpoint-url=http://localhost:4566 s3 mb "s3://$bucket"

It performs a step without asking what exists. A declarative tool works in a loop instead: it reads the desired state, reads the real world through the API, compares the two and applies only the difference. In the diagram, notice the arrow back from step 4: on the next run nothing is missing, so nothing changes.

Step-by-step loop with an illustrative example where the code asks for 2 servers. 1, desired state: read the code, 2 servers. 2, real world: ask the cloud API, 1 server exists. 3, compare: 1 server missing. 4, apply only the difference: create 1 server. An arrow from step 4 back to step 2 says next run: 2 servers exist, so no changes. Below, an imperative script that says start 2 servers leaves 2 servers after run 1 and 4 after run 2, while a declarative file that says 2 servers must exist leaves 2 after run 1 and still 2 after run 2
Only the difference is applied, so a second run with nothing missing does nothing.

Declarative is not harmless: delete a server from the file and the tool deletes the real one. That is why Terraform shows a plan before it acts (lesson 16).

What a team gains

Version control and review. The files live in Git, a version control system that records every change: who made it, when, and a message saying why. Teammates check each change in a pull request, a proposed change they read and approve before it is merged.

Repeatable environments. The same files build a test copy and a production copy, so you test on what customers use. Differences such as server size become settings in the files.

Drift detection. Drift is when real resources no longer match the code, usually after a change by hand. Terraform's plan reads the real resources first and proposes changes that make them match the code; AWS CloudFormation has a drift detection feature.

Recovery. If an environment is deleted, re-applying rebuilds what the files describe: the infrastructure, not the data inside it. A recreated database starts empty, so you still need the backups from lesson 8.

In the flowchart, a change passes review in Git, then a pipeline, an automated job that runs on every merge, hands it to the IaC tool. Notice the dashed arrows: a console click changes a resource behind the code's back, and the next comparison reports the drift.

Flowchart. 1, code in Git, every change recorded, leads to 2, pull request, a teammate reviews it, then 3, pipeline, runs on every merge, then 4, IaC tool, compares then applies, then 5, cloud resources such as a bucket, network and servers. A dashed amber arrow from a console click, a change by hand, also reaches the cloud resources, and a dashed amber arrow from the cloud resources back to the IaC tool is labelled drift: the next compare shows it. Notes: Git keeps who changed what, when and why; drift means real resources differ from the code, fixed by putting the change in code or re-applying
Changes flow through review; changes made by hand show up as drift.

The tool landscape

The tools differ in the language you write and the clouds they reach. Several use YAML, a plain-text format of indented names and values.

ToolYou writeWorks withGood to know
TerraformHCL, its own languageMany clouds, through plugins called providersHashiCorp, now IBM; Business Source License from version 1.6
OpenTofuHCLTerraform's providersOpen-source fork of Terraform, under the Linux Foundation
PulumiPython, TypeScript, Go, C#, Java and moreMany cloudsIts engine works out the changes your program asks for
AWS CloudFormationJSON or YAML templatesAWS onlyGroups resources into a stack; detects drift
AnsibleYAML playbooksServers, over SSHMainly configures what runs inside servers

A fork is a copy of a project's code that another group develops from then on. OpenTofu forked Terraform after the licence change, so what you learn here mostly carries over.

Ansible does configuration management: setting up packages, files and services inside a server. It logs in over SSH, the standard secure remote login, so there is no agent (helper program) to install. A YAML playbook lists tasks in order, but most modules first check whether the desired state already exists, so re-running is usually safe. A common split: Terraform creates the servers, Ansible sets them up.

Check yourself

A pipeline runs the lab's create-bucket.sh on every merge. After ten merges, how many buckets exist, and what would a declarative tool have done?

Ten, because the script acts on every run without looking at what exists. A declarative tool would create one bucket, then find nothing to change on the other nine runs.

During an outage, someone makes a server bigger in the console. What happens on the next IaC run, and what should the team do?

The tool sees drift, since the real size differs from the code, and plans to change the server back. The team should put the new size into the code through a pull request, so code and reality agree.

Your test environment, database included, is deleted by mistake, but you have its IaC files. What does re-applying bring back, and what not?

The network, the servers and an empty database. Not the data, because the files describe resources, not their contents; only backups restore that.