Why infrastructure belongs in code: provisioning, configuration and images
Why infrastructure belongs in code: compare declarative provisioning, configuration management and machine images, and see how plan, apply, destroy and state work together.
Contentsand lesson path
On this page
- From ClickOps to Declarative Infrastructure
- Which tool does which job
- Plan, apply and the state file
- Check your understanding
- Apply it
- Review prompt
Lessons of IaC Fundamentals
- Why infrastructure belongs in code: provisioning, configuration and images Concept · 20 min
- Lab: plan, apply and destroy, then extract a reusable module Lab · 40 min
- Remote state, environments and the checks every plan should pass Concept · 25 min
- Reading a plan like a reviewer: drift, import and state refactoring Worked example · 25 min
- Lab: configure a small fleet idempotently with an Ansible playbook Lab · 30 min
- Check: plan review, drift and configuration scenarios Knowledge check · 10 questions
What you will learn
- Explain declarative provisioning, the plan and apply cycle and the role of state, and contrast it with configuration management tools such as Ansible.
- Configure servers idempotently with an Ansible playbook (inventory, modules, handlers and templates), preview it with check and diff mode, and decide when to bake an image instead.
01. From ClickOps to Declarative Infrastructure
Before infrastructure as code, people built servers and networks by hand. They clicked through a cloud console (AWS Console, Google Cloud Console, Azure Portal) to create virtual machines, security groups and disks, or ran one-off shell scripts such as setup-server.sh over SSH. The console habit is often called "ClickOps". It is quick for the first server, but it causes four problems as a system grows:
- Drift and snowflake servers. Manual fixes, emergency changes and untracked package updates make servers differ from each other over time. Nobody knows exactly what is on each one, so people are afraid to rebuild them. A server that cannot be rebuilt from a written description is called a snowflake.
- Slow, uncertain recovery. If an account or a region is lost, someone has to recreate hundreds of network rules, route tables and databases from memory or screenshots. That can take days, far longer than most recovery time objectives (RTO: the longest outage the business accepts).
- No review or audit trail. A console click leaves no commit, no pull request and no record of who approved it, so mistakes are found only after they cause trouble.
- Knowledge in people's heads. The setup lives in the memory of a few engineers. When they leave, the team loses the ability to change the system safely.
Infrastructure as code (IaC) answers these problems by describing networks, servers and their configuration in text files kept in version control. The same files can be reviewed in a pull request, checked by automated tests, and applied again to rebuild the same result.
02. Which tool does which job
Each kind of tool works at a different point in a machine's life:
- Provisioning (OpenTofu, Terraform). You declare what should exist: VPCs, subnets, route tables, managed databases, Kubernetes clusters. The files use HCL, a declarative configuration language. The tool compares your declaration with what it recorded earlier and with the real resources, then proposes a plan to create, change or delete resources until they match.
- Configuration management (Ansible, Puppet). You describe how an existing operating system should be set up: packages, files such as
nginx.conf, users and services. Ansible connects over SSH and needs no agent on the host. Its modules are written to be idempotent: a module first checks the host and changes something only if it differs, so a second run on a host that is already correct reports no changes. Rawcommandandshelltasks are the exception, as lab 7 shows. - Machine images (Packer, image pipelines). Configuring every new VM at boot is slow exactly when speed matters. If an autoscaling group adds ten VMs during a traffic spike and each must first run a 15-minute playbook, the extra capacity arrives a quarter of an hour late. Instead, teams run the playbook once in an image build (for example with HashiCorp Packer) and save the result as a machine image, such as an AMI. New VMs boot from that image and only need their per-host settings.
Teams often describe the work in three phases. Day 0 creates the topology (provisioning), Day 1 sets up the operating system or bakes the image, and Day 2 covers ongoing work such as drift detection and patching. Keeping each phase in the tool built for it avoids, for example, a provisioning tool that runs long shell scripts on every host.
The difference between how and what shows even in a small task: write a settings file for a service. An imperative script lists every step, and it must check for itself what already exists, or each run repeats the work:
#!/usr/bin/env bash
set -euo pipefail
mkdir -p out
# Without this check, every run would rewrite the file
if [ ! -f out/service.json ]; then
echo '{"environment":"staging","port":8080,"workers":4}' > out/service.json
chmod 0644 out/service.json
fiThe script checks only that the file exists. If someone later changes workers by hand, the next run sees a file and does nothing, so the change stays. The declarative version below states only the result. OpenTofu works out the steps, and when the file on disk no longer matches, its next plan proposes to write it again.
terraform {
required_version = ">= 1.6.0"
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.9"
}
}
}
# Declarative resource declaration: specifies the desired outcome
resource "local_file" "service_config" {
# A path inside the working directory: no root rights needed
filename = "${path.module}/out/service.json"
file_permission = "0644"
content = jsonencode({
environment = "staging"
port = 8080
workers = 4
})
}03. Plan, apply and the state file
What a shell script lacks, and a declarative tool has, is state. OpenTofu keeps a state file (by default terraform.tfstate) that maps each resource block in your code, such as resource "aws_instance" "web", to the ID of the real object it created, such as i-0a8b9c1d2e3f. Cloud APIs do not record which code created an object, so state is how the tool knows that a block and an object belong together.
A run uses three commands:
planreads the real objects (a refresh), compares them and the state with your code, and prints what it would do:+create,~update in place,-destroy,-/+replace. Nothing changes yet, so a reviewer can stop an accidental deletion here.applymakes the API calls in dependency order after you confirm, and records each result in state as it goes. Apply is not a transaction: if it fails halfway, the resources already created or changed remain, in the cloud and in state, and nothing is rolled back. Fix the cause and run plan again; it shows only what is still missing.destroydeletes every object in state, in reverse dependency order. It is how temporary environments, such as a preview environment for one pull request, are removed.
To find the order, the tool builds a dependency graph from the references between blocks. If a subnet uses aws_vpc.main.id, the subnet depends on the VPC. The graph is a directed acyclic graph (DAG): each resource is a node, each reference is an edge, and cycles are not allowed. The tool starts a resource only after everything it references exists, and works on independent resources in parallel (OpenTofu runs up to 10 operations at a time by default; -parallelism changes that). A dependency that the code does not express, such as an application that needs a database it never references, is invisible to the graph; declare it with depends_on.
State is also how the tool tells removed from the code apart from not created yet. If a block disappears from the code but its address is still in state, the next plan proposes destroying that object. Without state, the tool could not tell the two cases apart.
04. Check your understanding
05. Apply it
Try these ideas on a system you work on:
- Pick one piece of infrastructure that was built by hand, such as a security group or a DNS zone, and write it as OpenTofu code. Use
tofu planto compare your code with the real object; lesson 5 shows how to import it without recreating it. - List the setup steps for one server and decide which belong in provisioning, which in configuration management and which in an image build.
- Pin each provider with a version constraint and commit
.terraform.lock.hcl, so a new provider release cannot change your plans without review (lab 2). - Keep state out of Git, because it can hold secrets in clear text; lesson 4 shows a locked remote backend.
- Rebuild a test environment from code on a schedule and time it, so you know your recovery time instead of guessing it.
06. Review prompt
Without looking back, explain what a declarative tool does on a second apply of unchanged code, and what a shell script does. Say whether you would use provisioning, configuration management or an image build for a VPC, for nginx settings and for VMs that must start fast under autoscaling, and why. Then describe what state records, what plan, apply and destroy do with it, and what is left after an apply fails halfway.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.