IntermediateLesson 9 of 128 min read

Infrastructure as Code: Templates, Dependency Order and the Plan

Describe cloud resources in a template instead of clicking in a console, then let a tool compare the template with reality and plan the changes. Build a dependency graph, order creation and deletion, detect cycles and unknown references, and check idempotence, with an independent verifier.

In this lesson you will

  • Explain declarative infrastructure
  • Order resources by dependencies
  • Detect cycles and missing references
  • Plan create, update and delete, and test idempotence

About 28 minutes

The console clicks nobody remembers

Wren’s first environment was built by clicking in the provider’s web console. Six months later nobody could say why one subnet had a different setting, and rebuilding it for a test copy took two days. Infrastructure as code, IaC, fixes that by describing the resources, networks, servers, databases and permissions, in text files that live in version control. The description is declarative: it says what should exist, not the steps to make it, and a tool compares it with what exists and works out the changes. The benefits are the same as for program code: review before a change, history of who changed what, the same environment created again in minutes, and tests. Popular tools exist for every provider, and each provider has its own template format too; the ideas of this lesson apply to all of them.

Two ideas make the tools work. The first is the dependency graph: a subnet cannot be created before its network, and a server needs the subnet and the security group, so the tool orders the work by the dependencies, creating in one direction and deleting in the opposite one. A template whose dependencies form a loop cannot be ordered, and a reference to a resource that does not exist is an error, and a good tool reports both before touching anything. The second is the plan: the tool reads the current state, compares each resource with the template, and lists what it would create, update or delete, so that a person can review the plan before it is applied. After applying, a second plan must show no changes, a property called idempotence, and a plan that always shows changes is a sign of a mistake.

Plan action When Order
Create In the template, not in the state Dependencies first
Update In both, but the properties differ Dependencies first
Delete In the state, not in the template Dependents first
No change Same in both Skipped
import json, sys
def check(tpl):
    errs = []
    for name, r in tpl.items():
        for d in r.get("deps", []):
            if d not in tpl: errs.append("%s refers to unknown %s" % (name, d))
    if errs: return None, errs
    indeg = {n: len(r.get("deps", [])) for n, r in tpl.items()}; users = collections.defaultdict(list)
    for n, r in tpl.items():
        for d in r.get("deps", []): users[d].append(n)
    ready = sorted(n for n, k in indeg.items() if k == 0); order = []
    while ready:
        n = ready.pop(0); order.append(n)
        for u in sorted(users[n]):
            indeg[u] -= 1
            if indeg[u] == 0: ready.append(u); ready.sort()
    if len(order) != len(tpl): return None, ["cycle among: " + ", ".join(sorted(set(tpl) - set(order)))]
    return order, []
import collections
def plan(tpl, state):
    order, errs = check(tpl)
    if errs: return None, errs
    steps = []
    for n in order:
        if n not in state: steps.append(("create", n))
        elif state[n]["props"] != tpl[n]["props"]: steps.append(("update", n))
    old = [n for n in state if n not in tpl]
    dep_of = {n: state[n].get("deps", []) for n in old}
    rem = list(old); dels = []
    while rem:                                         # delete a resource only when no other old resource still depends on it
        for n in sorted(rem):
            if not any(n in dep_of[m] for m in rem if m != n): dels.append(("delete", n)); rem.remove(n); break
    return steps + dels, []
def R(deps, **props): return {"deps": deps, "props": props}
tpl = {"net": R([], cidr="10.0.0.0/16"), "subnet_a": R(["net"], cidr="10.0.1.0/24"), "subnet_b": R(["net"], cidr="10.0.2.0/24"), "sg_web": R(["net"], ports=[80, 443]),
       "lb": R(["subnet_a", "subnet_b", "sg_web"], kind="app"), "vm1": R(["subnet_a", "sg_web"], size="small"), "vm2": R(["subnet_b", "sg_web"], size="small"),
       "bucket": R([], versioning=True), "db": R(["subnet_a", "subnet_b"], size="medium"), "dns": R(["lb"], name="shop.example")}
state = {"net": R([], cidr="10.0.0.0/16"), "subnet_a": R(["net"], cidr="10.0.1.0/24"), "bucket": R([], versioning=False), "old_vm": R(["subnet_a"], size="large"), "old_disk": R(["old_vm"], gb=100)}
steps, errs = plan(tpl, state)
for a, n in steps: print(a.ljust(7), n)
def apply(steps, state):
    new = {k: v for k, v in state.items()}
    for a, n in steps:
        if a == "delete": del new[n]
        else: new[n] = tpl[n]
    return new
after = apply(steps, state); again, _ = plan(tpl, after)
print("second plan after applying:", again if again else "no changes (idempotent)")
bad_cycle = {"a": R(["b"]), "b": R(["c"]), "c": R(["a"]), "d": R([])}
bad_ref = {"vm": R(["subnet_x"])}
print("cycle template:", check(bad_cycle)[1]); print("unknown reference template:", check(bad_ref)[1])
print("DATA " + json.dumps({"tpl": tpl, "state": state, "steps": steps, "again": again, "cycle": check(bad_cycle)[1], "ref": check(bad_ref)[1]}))
update  bucket
create  sg_web
create  subnet_b
create  db
create  lb
create  dns
create  vm1
create  vm2
delete  old_disk
delete  old_vm
second plan after applying: no changes (idempotent)
cycle template: ['cycle among: a, b, c']
unknown reference template: ['vm refers to unknown subnet_x']

The planner has two parts. The function check takes a template, a map from the names of resources to their dependencies and properties, and first looks for references to resources that do not exist. Then it orders the resources with Kahn’s algorithm: it repeatedly takes a resource whose dependencies are all done. If some resources are left over when nothing is ready, they form a cycle. The two failing templates at the end of the output show both errors: a loop among a, b and c is reported by name, and a server that refers to a subnet that is not defined is reported before anything is created. The function plan then compares the ordered template with the current state. Seven resources are missing and are created, in an order that always puts a network before its subnets and the subnets and security group before the load balancer and servers; one, the bucket, exists with the versioning property off and is updated; and two old resources that are not in the template are deleted.

The order of the deletions matters too. The old disk depends on the old server, so the disk must be deleted first, and the plan lists old_disk before old_vm, the reverse of the order of creation. Deleting the server first would fail, or leave a disk attached to nothing. After the plan was applied to the state, the program planned again, and the second plan is empty: nothing is left to create, update or delete. This idempotence is how you know that the template describes the state completely, and it is why a plan is safe to run again after a partial failure: only what is still missing is done. In real tools the state records the identifiers that the provider assigned, and a plan is saved and then applied unchanged, so that what was reviewed is what runs.

Independent check: a separate JavaScript verifier received the template, the state and the plan, and rechecked three things without using the Python code. Every create or update step comes after the steps for its dependencies, every delete comes before the deletion of what it depends on, and the sets of resources to create, update and delete are exactly those given by comparing names and properties directly. All checks pass, with ten steps in total, which equals the 7 creations, 1 update and 2 deletions counted by hand from the two dictionaries. A cycle and a missing reference were tested as failures, and both were reported correctly.

Check by hand: the template has 10 resources and the state has 5. Three names appear in both, net, subnet_a and bucket, so 10 – 3 = 7 resources are new, and 5 – 3 = 2 are old and must go. Of the three shared ones only the bucket has a different property, versioning false against true, so there is 1 update. The plan therefore has 7 + 1 + 2 = 10 steps, and the independent verifier counted ten.

Never edit by hand what the code owns

If someone changes a resource in the console, the next plan will show a difference, and applying it will undo their change. Decide that the code is the source of truth, and change it there.

Review the plan, not only the code

The plan is the list of what will really change. Read the deletions with special care, since a renamed resource appears as a delete and a create.

About this course

No cloud account is needed for this course. The cloud services in these lessons are small simulations that run on your own computer, in Python 3.13 or Node.js 22, because the ideas, such as access policies, queues, autoscaling and templates, are the same at every provider. Prices and names are invented or generic, and each provider’s services and prices change often, so check the current documentation of the provider you use. Every result was checked a second way. Real IaC tools keep a state file, support modules and variables, and each has its own syntax. The graph ordering and the plan comparison are common to all.

Practice

Add a resource that depends on the database and see where it falls in the order. Make the plan detect a renamed resource as one delete and one create. Write a check that rejects security groups open to the whole internet on port 22.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does declarative mean in infrastructure as code?

  1. You list every command to run
  2. You describe what should exist and the tool works out the steps
  3. You click in a console
  4. You write only comments

The tool plans the changes.

Why order resources by dependencies?

  1. A subnet cannot exist before its network
  2. To make files shorter
  3. To rename them
  4. Because the console requires it

And delete in reverse order.

What does a cycle in the dependencies mean?

  1. The template cannot be ordered and is invalid
  2. It runs twice
  3. It is faster
  4. It is a backup

Report it before changing anything.

What is idempotence of a plan?

  1. The plan always has changes
  2. It deletes everything
  3. It runs offline
  4. Applying it and planning again shows no changes

Safe to repeat.

Why verify the plan with a second implementation?

  1. It is required by law
  2. To add resources
  3. To hide errors
  4. Independent confirmation of order and sets

The verifier recomputes from the data.

Summary

  • Infrastructure as code describes resources in reviewed text files.
  • Dependencies set the order: create forward, delete backward.
  • A plan lists create, update and delete; a second plan should be empty.
  • Verify plans with an independent checker.

Next lesson

Lesson 10 covers networks, subnets and security groups.

Questions

What is drift?

A difference between the real infrastructure and the template, usually caused by manual changes. A plan shows drift, and the team decides whether to adopt the change or undo it.

Where do I keep secrets in templates?

Not in the template. Use the provider's secret store and refer to it, so that the file in version control holds no passwords or keys.

Can I test infrastructure code?

Yes: validate and plan in a test account, write checks like the ones in this lesson, and create a short-lived copy of the environment from the same template.

Progress is saved in this browser.