Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 4 · Operations and troubleshooting · Lesson 05 · 60 minutes

Describe a system as code

After this lesson you can
  • Read and write YAML and JSON and validate a file before you use it
  • Run a script that makes a folder match a description, twice, with the same result
  • Stop a bad change with a Git hook and say what continuous integration and delivery do
Lab files of this lesson (14)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Three servers were set up by hand, and no two are the same. Nobody can say which settings are right, and a rebuilt server loses changes that only existed in someone's memory. Your lead asks for the wanted state in a file in Git, and a program that makes a server match the file. You build a small one: Ansible, Terraform and cloud-init work on the same idea.

Recall

What does git diff --staged show?

The changes that are in the staging area and go into the next commit (lesson 4). Plain git diff shows the changes that are not staged.

How does a shell script say that it failed, and how do you read that in the shell?

By its exit code. 0 means success and any other number means failure (lesson 11 of Part 2). echo $? prints the code of the last command.

The idea

Infrastructure as code means that you describe servers, settings and services in text files, keep the files in version control and let a program apply them. A declarative description says what the end state must be ("this folder exists with mode 0750"), not the steps. The program compares the wanted state with the real state, and changes only the difference. Drift is the gap that grows when somebody changes a server by hand.

A program like that must be idempotent: running it twice gives the same result as running it once. The second run finds nothing to change and says so. That makes it safe to run on a timer, after a failure, or by two people.

Two text formats carry the descriptions. YAML uses indentation, a dash for a list item and key: value. JSON uses braces, brackets and double quotes, and it does not allow comments or a comma after the last item. A program that reads a description must refuse a file that it does not understand, before it changes anything.

From a change to a running system
EditPre-commit hookPushCI checksDeploygit commit starts itthe checks passthe server tests every pushall checks passEditPre-commit hookPushCI checksDeploy1234
  1. Edit → Pre-commit hook: git commit starts it
  2. Pre-commit hook → Push: the checks pass
  3. Push → CI checks: the server tests every push
  4. CI checks → Deploy: all checks pass

Continuous integration (CI) means that a server builds and tests every push at once, so a broken change is found in minutes. Continuous delivery means that every change that passes is ready to release at any moment. Continuous deployment releases it with no human step. All three are a pipeline: ordered stages that stop at the first failure. The hook of this lesson is the smallest pipeline: one stage, on your own machine. A real CI server is a separate machine, and it is not tested here.

Worked example

Work in a new folder. The program reads YAML with the Python module yaml. Install it if it is missing: sudo apt install -y python3-yaml.

1. Read YAML and JSON, and meet their traps

python3 -c 'CODE' runs one line of Python. yaml.safe_load turns YAML text into Python data. python3 -m json.tool FILE reads a JSON file and prints it again, or names the first error.

mkdir -p ~/krlab/linux-operations/infra && cd ~/krlab/linux-operations/infra
python3 -c 'import yaml; print(yaml.safe_load("mode: 0750"), yaml.safe_load("country: no"))'
printf '{"port": 8080,}\n' > broken.json
python3 -m json.tool broken.json
{'mode': 488} {'country': False}
Expecting property name enclosed in double quotes: line 1 column 15 (char 14)

Two traps in YAML. 0750 is read as an octal number (488), and no is read as False. Quote the value when it is text: "0750". This is the rule of YAML 1.1, which PyYAML follows. Other tools can read the same file differently (Ansible and Kubernetes files have their own surprises), so validate with the tool that really reads the file. The JSON file has a comma after the last item, which JSON forbids, and the message names the place. A newer Python words it differently ("Illegal trailing comma"), and it points at the comma.

2. Describe the wanted state

Save this as desired.yaml. It describes a folder target that stands for a server: two directories with modes, two files with content and a file that must not exist. A real tool would use /; this lab never leaves its own folder.

desired.yaml

# desired.yaml - the wanted state of the lab server, under the folder "target"
base: target
directories:
  - path: etc/krapp
    mode: "0750"
  - path: var/log/krapp
    mode: "0755"
files:
  - path: etc/krapp/app.conf
    mode: "0640"
    content: |
      listen = 127.0.0.1
      port = 8080
  - path: etc/motd
    mode: "0644"
    content: |
      Managed by converge.py. Do not edit by hand.
absent:
  - etc/krapp/old.conf

3. Validate the description

The program converge.py has two parts. The first part is the function validate. It refuses a description that the program does not understand, before anything changes. Each rule is one test:

  • The top level is a map with only the keys base, directories, files and absent.
  • Each item has exactly the keys that its kind needs (path and mode, and content for a file), and every value is text. A mode that is a number is refused here: this is the trap of step 1.
  • A mode is written with three or four octal digits (0 to 7). re.fullmatch tests the whole text against a pattern.
  • Each of directories, files and absent is a list, not one value.
  • base and every path are not empty, not absolute, have no .. part and are already in plain form (docs/ and a//b are refused), so that nothing can leave the base folder. The function check_path tests this, and validate calls it for the base and for every path.
def validate(want):
    if not isinstance(want, dict) or set(want) - TOP:
        raise ValueError("the top level must be a map with the keys " + ", ".join(sorted(TOP)))
    for kind, keys in KEYS.items():
        for item in want.get(kind) or []:
            if not isinstance(item, dict) or set(item) != keys:
                raise ValueError("each item of %s needs the keys %s: %s" % (kind, ", ".join(sorted(keys)), item))
            if not all(isinstance(v, str) for v in item.values()):
                raise ValueError("every value must be text (quote a mode like \"0640\"): %s" % item["path"])
            if not re.fullmatch(r"[0-7]{3,4}", item["mode"]):
                raise ValueError("mode is not an octal number: " + item["path"])
    # ... then the list check, and check_path for the base and for every path

4. Apply it, and keep the result the same

The second part reads the real state first and changes only what differs. set_mode returns True when it changed a mode. In apply, each item has two named results: made or written (did it create or write?) and moded (did the mode change?). The item counts as a change when either is true. apply returns the number of changes, and main prints it.

def apply(want):
    base = want.get("base", "target")
    changed = 0
    for d in want.get("directories") or []:
        path = os.path.join(base, d["path"])
        made = not os.path.isdir(path)
        os.makedirs(path, exist_ok=True)
        moded = set_mode(path, d["mode"])
        changed += show(made or moded, "directory " + d["path"])
    # ... the same for the files (written or moded) and for the absent paths
    return changed

The constants TOP and KEYS, and the helpers set_mode and show, are in the finished file. Save it as converge.py.

The finished file: converge.py

converge.py

#!/usr/bin/env python3
"""converge.py - makes a folder match a description in YAML.
Usage: python3 converge.py desired.yaml [--check]
--check only validates the file. Exit codes: 0 done, 2 the description is not valid."""
import os
import re
import sys

import yaml

TOP = {"base", "directories", "files", "absent"}
KEYS = {"directories": {"path", "mode"}, "files": {"path", "mode", "content"}}


def check_path(path):
    """Refuse a path that is not text, is empty, is absolute, has a .. part, means the folder itself or is not plain."""
    if not isinstance(path, str) or not path or os.path.isabs(path) or ".." in path.split("/") or os.path.normpath(path) == "." or os.path.normpath(path) != path or "\n" in path:
        raise ValueError("unsafe path: %r" % (path,))


def validate(want):
    """Refuse everything that the program does not understand, before it changes anything."""
    if not isinstance(want, dict) or set(want) - TOP:
        raise ValueError("the top level must be a map with the keys " + ", ".join(sorted(TOP)))
    for kind in list(KEYS) + ["absent"]:
        if not isinstance(want.get(kind) or [], list):
            raise ValueError(kind + " must be a list")
    check_path(want.get("base", "target"))
    for kind, keys in KEYS.items():
        for item in want.get(kind) or []:
            if not isinstance(item, dict) or set(item) != keys:
                raise ValueError("each item of %s needs the keys %s: %s" % (kind, ", ".join(sorted(keys)), item))
            if not all(isinstance(v, str) for v in item.values()):
                raise ValueError("every value must be text (quote a mode like \"0640\"): %s" % item["path"])
            if not re.fullmatch(r"[0-7]{3,4}", item["mode"]):
                raise ValueError("mode is not an octal number: " + item["path"])
            check_path(item["path"])
    for name in want.get("absent") or []:
        check_path(name)


def set_mode(path, mode):
    """Set the mode when it differs. Return True when it changed the mode."""
    if os.stat(path).st_mode & 0o7777 == int(mode, 8):
        return False
    os.chmod(path, int(mode, 8))
    return True


def show(did, what):
    print(("changed  " if did else "ok       ") + what)
    return did


def apply(want):
    """Make the folder match the description. Return the number of changes."""
    base = want.get("base", "target")
    changed = 0
    for d in want.get("directories") or []:
        path = os.path.join(base, d["path"])
        made = not os.path.isdir(path)
        os.makedirs(path, exist_ok=True)
        moded = set_mode(path, d["mode"])
        changed += show(made or moded, "directory " + d["path"])
    for f in want.get("files") or []:
        path = os.path.join(base, f["path"])
        os.makedirs(os.path.dirname(path), exist_ok=True)
        old = open(path).read() if os.path.isfile(path) else None
        written = old != f["content"]
        if written:
            with open(path, "w") as out:
                out.write(f["content"])
        moded = set_mode(path, f["mode"])
        changed += show(written or moded, "file      " + f["path"])
    for name in want.get("absent") or []:
        path = os.path.join(base, name)
        here = os.path.exists(path)
        if here:
            os.remove(path)
        changed += show(here, "absent    " + name)
    return changed


def main():
    args = [a for a in sys.argv[1:] if not a.startswith("--")]
    if len(args) != 1:
        print("usage: converge.py desired.yaml [--check]")
        return 2
    try:
        with open(args[0]) as f:
            want = yaml.safe_load(f)
        validate(want)
    except (OSError, yaml.YAMLError, ValueError) as e:
        print("invalid:", e)
        return 2
    if "--check" in sys.argv:
        print("valid")
        return 0
    print("changed:", apply(want))
    return 0


sys.exit(main())

Check the file, with --check, which validates and changes nothing.

python3 converge.py desired.yaml --check
valid

5. Run it twice

Plant the file that must go, then run the program two times. echo "text" > FILE writes a file (lesson 1 of Part 1).

mkdir -p target/etc/krapp
echo "port = 80" > target/etc/krapp/old.conf
python3 converge.py desired.yaml
python3 converge.py desired.yaml
changed  directory etc/krapp
changed  directory var/log/krapp
changed  file      etc/krapp/app.conf
changed  file      etc/motd
changed  absent    etc/krapp/old.conf
changed: 5
ok       directory etc/krapp
ok       directory var/log/krapp
ok       file      etc/krapp/app.conf
ok       file      etc/motd
ok       absent    etc/krapp/old.conf
changed: 0

Each line has three parts:

One line of converge.py
changedwhat it did (ok: nothing)filethe kind of itemetc/krapp/app.confits path under the base folderchangedwhat it did (ok: nothing)filethe kind of itemetc/krapp/app.confits path under the base folder

The first run made five changes. The second run made none: that is idempotence. The directory etc/krapp counted as changed in the first run because it was made with the default mode and the description asks for 0750.

6. Repair drift

Play the person who changes a server by hand: delete one file and open a directory to everyone. Run the program again.

rm target/etc/motd
chmod 777 target/etc/krapp
python3 converge.py desired.yaml | grep -E "^changed"
changed  directory etc/krapp
changed  file      etc/motd
changed: 2

The program found the two differences, and only those, and put them right. Run from a timer, it removes drift by itself.

7. Refuse a bad description

A path with .. could write outside the base folder, a file with no content is incomplete, and an empty path would name the folder itself. Each of them must stop the program before it does anything.

printf 'files:\n  - path: ../../etc/passwd\n    mode: "0644"\n    content: x\n' > bad.yaml
python3 converge.py bad.yaml; echo "exit=$?"
printf 'files:\n  - path: etc/a.conf\n    mode: "0644"\n' > bad2.yaml
python3 converge.py bad2.yaml; echo "exit=$?"
printf 'directories:\n  - path: etc/ok\n    mode: "0755"\nfiles:\n  - path: ""\n    mode: "0644"\n    content: x\n' > bad3.yaml
python3 converge.py bad3.yaml; echo "exit=$?"
ls target/etc
invalid: unsafe path: '../../etc/passwd'
exit=2
invalid: each item of files needs the keys content, mode, path: {'path': 'etc/a.conf', 'mode': '0644'}
exit=2
invalid: unsafe path: ''
exit=2
krapp
motd

Nothing was changed: target/etc holds only krapp and motd. There is no a.conf and no ok, although the first item of bad3.yaml was fine. The program checks every item first and acts after.

8. Run the checks before every commit

A hook is a script that Git runs at a fixed moment. A pre-commit hook runs before a commit and stops it when it exits with a number other than 0. Save this as pre-commit.sh.

How a hook stops a commit
YouGitHookgit commitrun .git/hooks/pre-commitvalidate desired.yaml, look for secretsexit 1: a check failedcommit refused, nothing is savedYouGitHook12345
  1. You → Git: git commit
  2. Git → Hook: run .git/hooks/pre-commit
  3. Hook: validate desired.yaml, look for secrets
  4. Hook → Git: exit 1: a check failed
  5. Git → You: commit refused, nothing is saved

pre-commit.sh

#!/bin/sh
# pre-commit.sh - a Git hook: it runs before each commit and stops the commit when a check fails.
python3 converge.py desired.yaml --check || { echo "pre-commit: desired.yaml is not valid"; exit 1; }
if git diff --cached | grep -qiE '^\+.*(password|api_key|secret)[[:space:]]*[=:]'; then
    echo "pre-commit: this commit looks like it holds a secret"
    exit 1
fi

grep -q prints nothing and only sets the exit code, and -i ignores the case. git diff --cached shows the staged change. Install the hook by copying it to .git/hooks/pre-commit in a new repository, and make it executable. .gitignore keeps the generated folder and the test files out.

git init -q -b main .
git config user.name "You"
git config user.email "you@example.invalid"
cp pre-commit.sh .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
printf 'target/\nbad*.yaml\nbroken.json\n' > .gitignore
git add .gitignore desired.yaml converge.py pre-commit.sh
git commit -qm "First version"
printf 'directories: [\n' >> desired.yaml
git commit -qam "Break the file"
git checkout -q desired.yaml
echo "api_key = abc123" > notes.txt
git add notes.txt
git commit -qm "Add notes"
valid
invalid: while parsing a flow node
expected the node content, but found '<stream end>'
  in "desired.yaml", line 21, column 1
pre-commit: desired.yaml is not valid
valid
pre-commit: this commit looks like it holds a secret

The first commit passed, and the two bad ones were refused: the file that is not valid YAML, and the staged text that looks like a key. git checkout -q desired.yaml threw the broken edit away. A hook lives in .git and is not copied by git clone, so a team also runs the same checks on the CI server, where nobody can skip them.

Your turn

Write your own description, site.yaml, with base: site. It must hold: a directory srv/www with mode 0755; a file srv/www/index.html with mode 0644 and the content <h1>ready</h1>; and the absent file tmp/leftover.txt. Plant site/tmp/leftover.txt first (any text). Then:

  1. Run converge.py site.yaml and note the number of the last line.
  2. Run it again.
  3. Delete site/srv/www/index.html and run it a third time.
  4. Make a copy of the file in which the mode of the directory is written without quotes (mode: 0755), and run the program on the copy.

Check yourself

What makes a script idempotent, and why does it matter on a server?

It looks at the state first and acts only on the difference, so a second run changes nothing. It matters because runs are repeated: after a failure, on a timer, or by a second person. A script that appends a line every time breaks the file on the second run.

Why does converge.py refuse a path with ".." before it changes anything?

A description is input, and input can be wrong or hostile. A path such as ../../etc/passwd would write outside the base folder. Validate first, then act, so that a bad file does nothing at all.

A colleague skips the pre-commit hook with git commit --no-verify. What protects the repository?

The same checks on a server that every push must pass. A local hook is a help for the author. A CI check is a rule for the team.

What is the difference between continuous delivery and continuous deployment?

In delivery, every change that passes the pipeline is ready to release, and a person decides when. In deployment, a change that passes is released with no person in the loop. Choose by the risk of the system.

Field notes

  • Real tools do what converge.py does, with more kinds of item: Ansible applies a description to machines over SSH, Terraform to cloud services, cloud-init at the first boot.
  • Run a tool in check mode first (a "dry run") and read what it would change, as with --check here, before you apply it to production.
  • Never put a secret in a description. Keep it in a secret store, and let the file name where to find it. A hook that looks for secrets is a net, not a guarantee (lesson 4).
  • Keep the description and the tool in one repository, and tag each release. Then a rollback is a checkout.
  • YAML can be wrong and still load without an error. Validate against a schema when a file matters, and keep indentation to spaces.