Skip to the levels
ROOTSPIRE
DiscsFor teachers
▶ Play freeLibrary 16 discsDiscsFor teachersLog in

Every level, in the open

Python for Ops

5 worlds · 52 levels · 6 bosses

SOLUTION HIDDENTeachers see answer keys in the classroom.

▶ Play this discAll discs
All discsLinux: Zero to RootBash ScriptingGitDatabasesPython for OpsLinux Sysadmin ProNetworkingObservabilityCloud & IaCDocker & ContainersCTF ArenaSOC FieldWindows for Linux peopleKubernetesAnsibleThe Guildhall: First Week

Real python3 on a real Linux box: the scripts an on-call engineer actually writes. Parse logs, CSV and JSON, replace fragile bash with subprocess, build argparse CLIs, talk to HTTP APIs, make idempotent changes and test your tools. Hidden tests run your scripts on inputs you never saw.

Guided levels show the command first. Alone levels give the goal only. Bosses and exams are timed.

Jump to a world

World 1 The Snake PitWorld 2 The LedgerWorld 3 The Engine RoomWorld 4 The RelayWorld 5 The Workshop

World 1The Snake Pit

13 levels

Kern found a snake in the server room that counts instead of biting: your first python3 scripts: REPL, heredoc, types, lists, dicts, argv, files.

  1. 1

    Level 1: First hiss

    GuidedEasy

    Objective: Open the python3 REPL, compute something, exit cleanly; then write ~/pit/hello.py that prints 'Snake Pit online' and run it.

    python3 alone opens the REPL, where Python answers each expression and exit() or Ctrl-D brings you back to bash. To keep code, write hello.py with a quoted heredoc (cat > hello.py <<'EOF', the lines, then EOF) and run hidden.

    Commands taughtpy-replpy-heredoc-scriptpy-why-python

    ▶ Play: First hissSOLUTION HIDDEN15 XP
  2. 2

    Level 2: Disk math

    GuidedEasy

    Objective: Write ~/pit/disk.py: read used GB, then total GB (one per line on stdin) and print 'Disk: <used*100//total>% used' and 'Free: <total-used> GB'.

    input() reads one line of stdin, always as text (str), so '40' + '2' is '402'. int() turns text into a number so math works; // divides without the fraction. An f-string, f'Disk: {pct}% used', drops values straight into text.

    Commands taughtpy-int-strpy-fstrings

    ▶ Play: Disk mathSOLUTION HIDDEN20 XP
  3. 3

    Level 3: Port sieve

    GuidedEasy

    Objective: Write ~/pit/ports.py: read one line of ports from stdin; print 'privileged: <port>' for each port below 1024 (in order), then 'count: <how many>'.

    line.split() cuts text on spaces into a list: '22 80 8080'.split() is ['22', '80', '8080']. for p in ports: runs the indented block once per item; if int(p) < 1024: only for privileged ports. Python's blocks are its indentation (4 spaces), not do/done.

    Commands taughtpy-listspy-for-if

    ▶ Play: Port sieveSOLUTION HIDDEN20 XP
  4. 4

    Level 4: Status tally

    GuidedEasy

    Objective: Write ~/pit/tally.py: read one line of HTTP status codes from stdin and print '<code>: <count>' for each code, sorted by code.

    A dict maps keys to values: counts = {}; counts['404'] = 1. counts.get(code, 0) gives the value or 0 if the key is new, so counts[code] = counts.get(code, 0) + 1 counts anything. sorted(counts) gives the keys in order. It is bash's declare -A, without the pain.

    Commands taughtpy-dicts

    ▶ Play: Status tallySOLUTION HIDDEN20 XP
  5. 5

    Level 5: First arguments

    GuidedEasy

    Objective: Make ~/pit/check.py executable: ./check.py svc1 svc2 … prints 'checking <svc>' for each argument.

    Arguments land in sys.argv (import sys): [0] is the script, [1:] is everything typed after it. for svc in sys.argv[1:]: runs once per argument; print(f'checking {svc}') fills the value in. Line 1 #!/usr/bin/env python3 + chmod +x lets you run ./check.py.

    Commands taughtpy-argvpy-fstringspy-shebang

    ▶ Play: First argumentsSOLUTION HIDDEN20 XP
  6. 6

    Level 6: Uptime tag

    AloneMedium

    Objective: Write ~/pit/uptime.py: python3 uptime.py MINUTES prints 'up <h>h <m>m' (135 → 'up 2h 15m').

    import sys gives you sys.argv, the command line as a list: sys.argv[0] is the script, sys.argv[1] the first argument, like $1 in bash. It is text, so int() it. m // 60 is whole hours, m % 60 the minutes left over.

    Commands taughtpy-argv

    ▶ Play: Uptime tagSOLUTION HIDDEN25 XP
  7. 7

    Level 7: Quota calc

    AloneMedium

    Objective: Write ~/pit/quota.py with a function that returns the usage percent: python3 quota.py USED TOTAL LIMIT prints 'usage: <pct>%' then ALERT (pct >= LIMIT) or OK.

    def pct(used, total): starts a function; its indented body ends with return, which hands a value back to the caller (bash functions can only return an exit code). Name a calculation once, reuse it everywhere.

    Commands taughtpy-functions

    ▶ Play: Quota calcSOLUTION HIDDEN25 XP
  8. 8

    Level 8: Read the lines

    GuidedEasy

    Objective: Write ~/pit/show.py: python3 show.py FILE prints every line of FILE stripped, skipping blank lines and lines that start with # (sample: ~/pit/hosts.txt).

    with open(path) as f: opens a file and closes it for you. for line in f: gives one line at a time; line = line.strip() removes the newline and stray spaces. if not line catches a blank, line.startswith('#') a comment; continue skips it.

    Commands taughtpy-open-lines

    ▶ Play: Read the linesSOLUTION HIDDEN20 XP
  9. 9

    Level 9: Host list

    AloneMedium

    Objective: Write ~/pit/hosts.py: python3 hosts.py FILE prints every host in FILE (stripped, no blank or # lines), then 'total: <count>' (sample: ~/pit/hosts.txt).

    with open(path) as f: opens a file and closes it for you when the block ends. for line in f: gives one line at a time, newline included; line.strip() removes it and stray spaces. Skip blanks with if not line and comments with line.startswith('#').

    Commands taughtpy-open-lines

    ▶ Play: Host listSOLUTION HIDDEN25 XP
  10. 10

    Level 10: Own command

    AloneMedium

    Objective: Make ~/pit/tool.py an executable python script: ./tool.py svc1 svc2 … prints 'checking <svc>' for each argument, then 'done: <count>'.

    Same trick as bash: line 1 #!/usr/bin/env python3 tells the kernel which program runs the file (env finds python3 on PATH), chmod +x makes it runnable, and ./tool.py starts it with no python3 in front. sys.argv[1:] is every argument (bash's "$@").

    Commands taughtpy-shebang

    ▶ Play: Own commandSOLUTION HIDDEN25 XP
  11. 11

    Level 11: Slow pings

    GuidedEasy

    Objective: Make ~/pit/ping.py executable: ./ping.py FILE MAX prints 'SLOW <host> <ms>ms' for each host slower than MAX ms, then 'slow: <count>' (sample: ~/pit/probe.txt).

    The second argument is sys.argv[2], but it is text: limit = int(sys.argv[2]). host, ms = line.split() unpacks 'web1 120' into two names. Compare numbers, not text: int(ms) > limit. A counter (slow = 0, slow += 1) keeps score.

    Commands taughtpy-open-linespy-fstrings

    ▶ Play: Slow pingsSOLUTION HIDDEN20 XP
  12. 12

    Level 12: PAGER: slow hosts

    Alone⏱ TimedHard

    Objective: Make ~/pit/slow.py executable: ./slow.py FILE MAX prints 'SLOW <host> <ms>ms' per host above MAX ms, then 'slow: <n> of <hosts>'.

    Pager at 03:12: the probe wrote one 'host latency_ms' line per machine, with blanks and # notes. On-call wants a real command: shebang, chmod +x, argv, open + strip, split, int() before you compare.

    ▶ Play: PAGER: slow hostsSOLUTION HIDDEN40 XP
  13. 13

    Level 13: BOSS: Fleet report

    Boss⏱ TimedHard

    Objective: Write ~/pit/report.py: python3 report.py INVENTORY prints '<role>: <count>' per role sorted by role, then 'total: <hosts>'. ~/pit/inventory.txt is a sample.

    The Pit's keeper wants a fleet report before the deploy: the inventory has one 'host role' line per machine, with blanks and # comments. Everything from this world in one script: argv, open + strip, split, a dict of counts, sorted, f-strings.

    ▶ Play: BOSS: Fleet reportSOLUTION HIDDEN70 XP

World 2The Ledger

10 levels

The archive under the server room, where Kern swears every outage leaves a confession you can read with pathlib, CSV, JSON and regex.

  1. 14

    Level 14: Shelf count

    GuidedEasy

    Objective: Write ~/ledger/shelf.py: for python3 shelf.py DIR print '<name> <bytes>' per *.log file in DIR (sorted), then 'total <bytes>'; no DIR: 'no such folder: DIR'.

    pathlib turns paths into objects: Path('logs').glob('*.log') finds the logs, .is_file() skips folders, .stat().st_size is the size in bytes and .exists() asks before you touch. Before cleaning a disk, you measure it.

    Commands taughtpy-pathlib

    ▶ Play: Shelf countSOLUTION HIDDEN20 XP
  2. 15

    Level 15: Error tally

    GuidedEasy

    Objective: Write ~/ledger/tally.py: python3 tally.py LOG prints '<service> <count>' for every service with ERROR lines, alphabetical.

    line.split() cuts a log line on runs of spaces (a blank line gives []), so parts[1] is the level and parts[2] the service. Matching the word ERROR anywhere in the line counts the wrong lines.

    Commands taughtpy-split

    ▶ Play: Error tallySOLUTION HIDDEN20 XP
  3. 16

    Level 16: Quoted commas

    GuidedEasy

    Objective: Write ~/ledger/bill.py: python3 bill.py CSV prints '<team> <total cost, 2 decimals>' per team, alphabetical; rows with an empty cost are skipped.

    The billing export has a note column, and notes contain commas inside quotes: "VM, 2 vCPU". line.split(',') cuts them in pieces and the cost lands in the wrong column. csv.DictReader knows the CSV rules and hands you each row as a dict keyed by the header.

    Commands taughtpy-csv

    ▶ Play: Quoted commasSOLUTION HIDDEN25 XP
  4. 17

    Level 17: Config flip

    GuidedEasy

    Objective: Write ~/ledger/flip.py: python3 flip.py IN OUT sets log_level 'warn', version +1, writes OUT (indent 2, folders created), other keys kept.

    Config files are JSON: json.load(f) gives you a dict, you change it like any dict, json.dump(obj, f, indent=2) writes it back readable. Deploy folders may not exist yet: Path(out).parent.mkdir(parents=True, exist_ok=True) makes them, and does nothing if they are there.

    Commands taughtpy-json

    ▶ Play: Config flipSOLUTION HIDDEN25 XP
  5. 18

    Level 18: Slow calls

    AloneMedium

    Objective: Write ~/ledger/slow.py: python3 slow.py FILE MS prints '<path> <ms>' for each request slower than MS (in file order), then 'slow <count>'.

    Many services log JSON lines: one complete JSON object per line, so the file is never loaded whole. json.loads(line) parses one line; event.get('ms') returns None when the key is missing instead of crashing.

    Commands taughtpy-jsonl

    ▶ Play: Slow callsSOLUTION HIDDEN30 XP
  6. 19

    Level 19: Who knocked?

    AloneMedium

    Objective: Write ~/ledger/users.py: python3 users.py AUTHLOG prints '<user> <failed logins>' for every user with failed password attempts, alphabetical.

    auth.log lines differ: 'Failed password for root from …' and 'Failed password for invalid user admin from …'. One regular expression fits both: r'Failed password for (invalid user )?(\S+) from'. re.search finds it anywhere; group(2) is the user. r'' keeps backslashes.

    Commands taughtpy-re

    ▶ Play: Who knocked?SOLUTION HIDDEN30 XP
  7. 20

    Level 20: Top knockers

    AloneMedium

    Objective: Write ~/ledger/top.py: python3 top.py AUTHLOG N prints the N IPs with the most failed passwords as '<ip> <count>', most first, ties in IP text order.

    re.findall returns every captured IP, collections.Counter counts them. sorted(counts.items(), key=lambda item: (-item[1], item[0])) ranks by count, then IP text. most_common() breaks ties by first seen.

    Commands taughtpy-counter

    ▶ Play: Top knockersSOLUTION HIDDEN35 XP
  8. 21

    Level 21: PAGER: Over budget

    Alone⏱ TimedHard

    Objective: PAGER: write ~/ledger/over.py: python3 over.py CSV BUDGET OUT writes OUT as CSV team,item,note,cost : rows costing more than BUDGET, priciest first.

    PAGER from finance: the cloud bill jumped and they want every line over budget in a spreadsheet before 9. csv.writer(f).writerow([...]) quotes fields with commas so notes stay in one cell; open the file with newline=''.

    Commands taughtpy-csv-writer

    ▶ Play: PAGER: Over budgetSOLUTION HIDDEN45 XP
  9. 22

    Level 22: PAGER: 5xx spike

    Alone⏱ TimedHard

    Objective: PAGER: write ~/ledger/spike.py: python3 spike.py LOG prints '<HH:MM> <count>' for the minute with the most 5xx responses (tie: earliest), or 'no 5xx'.

    PAGER 03:21: checkout is throwing 5xx and the incident channel needs to know which minute it started burning. The gateway's JSON-lines log is all you have.

    ▶ Play: PAGER: 5xx spikeSOLUTION HIDDEN50 XP
  10. 23

    Level 23: BOSS: The night digest

    Boss⏱ TimedHard

    Objective: Build ~/ledger/digest.py step by step: python3 digest.py DIR OUT summarizes every app.log* file (incl. .gz) in DIR as JSON, prints it and saves it to OUT.

    Logrotate keeps app.log, app.log.1, and older nights as app.log.2.gz, app.log.3.gz. The morning stand-up wants one JSON digest of the whole week: files, lines, and errors per service.

    Commands taughtpy-gzip

    ▶ Play: BOSS: The night digestSOLUTION HIDDEN120 XP

World 3The Engine Room

10 levels

Old bash scripts hiss and leak behind the boiler doors, so Kern hands you a Python wrench (subprocess, exit codes, argparse, logging) to fix the pipes.

  1. 24

    Level 24: First call

    GuidedEasy

    Objective: Write ~/engine/count.py PATH: run wc -l on PATH and print only the number, or 'cannot count PATH' when wc's returncode is not 0.

    subprocess.run(["wc", "-l", path], capture_output=True, text=True) starts a program straight away, no shell in between: every list item is one argument, so spaces and ; in a name stay part of the name. The result keeps .stdout (text) and .returncode (0 = it worked).

    Commands taughtpy-subprocess

    ▶ Play: First callSOLUTION HIDDEN20 XP
  2. 25

    Level 25: Fail loud

    GuidedEasy

    Objective: Write ~/engine/backup.py SRC DEST: copy with cp (check=True, timeout=5) and print 'backup ok', 'backup failed (exit N)' or 'backup timed out'.

    check=True turns a failed command into an exception, subprocess.CalledProcessError (e.returncode says which exit). timeout=5 stops a command that hangs and raises subprocess.TimeoutExpired. Catch each one with try/except and say what happened.

    Commands taughtpy-check-timeout

    ▶ Play: Fail loudSOLUTION HIDDEN20 XP
  3. 26

    Level 26: Exit contract

    GuidedEasy

    Objective: ~/engine/logcheck.py FILE (grep -c ERROR): 'clean' exit 0 · 'N errors' exit 1 · unreadable: stderr, exit 1 · not 1 argument: usage on stderr, exit 2.

    cron, CI and systemd never read your text: they read the exit code. sys.exit(0) = all good, sys.exit(1) = found a problem, sys.exit(2) = called wrong (usage). Messages for humans go to stderr with print(..., file=sys.stderr), so stdout stays clean data.

    Commands taughtpy-sys-exit

    ▶ Play: Exit contractSOLUTION HIDDEN25 XP
  4. 27

    Level 27: Proper flags

    GuidedEasy

    Objective: ~/engine/rotate.py LOGDIR [--keep N=5] [--mode gzip|delete, default gzip] [--dry-run]: print dir=LOGDIR keep=N mode=MODE dry_run=True/False.

    argparse turns sys.argv into a command line: add_argument("logdir") is a required positional, "--keep" with type=int converts and checks numbers, choices= limits values, action="store_true" makes an on/off flag. Bad input → usage on stderr + exit 2, and --help is written for you.

    Commands taughtpy-argparse

    ▶ Play: Proper flagsSOLUTION HIDDEN25 XP
  5. 28

    Level 28: Missing pieces

    AloneMedium

    Objective: ~/engine/readcfg.py FILE: print port= as a number; on errors one stderr line with 'not found', 'permission' or 'not a number', exit 1, no traceback.

    A traceback is a crash, not a message: catch the exception you expect, FileNotFoundError, PermissionError or ValueError (int("80a")), say it in one stderr line and exit 1. Never a bare except: it hides real bugs too.

    Commands taughtpy-try-except

    ▶ Play: Missing piecesSOLUTION HIDDEN30 XP
  6. 29

    Level 29: Quiet logs

    AloneMedium

    Objective: ~/engine/sweep.py DIR [--verbose]: print only the count of *.tmp files, log INFO (level name shown) on stderr, and with --verbose a DEBUG line per .tmp file.

    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") sets up logs once; logging.info / .debug / .warning / .error write them to stderr. Only messages at the level or above show, so --verbose switching to logging.DEBUG adds detail without touching stdout.

    Commands taughtpy-logging

    ▶ Play: Quiet logsSOLUTION HIDDEN30 XP
  7. 30

    Level 30: Tool check

    AloneMedium

    Objective: ~/engine/preflight.py TOOL…: print 'TOOL: PATH' for each found, name every missing one on stderr then exit 1 (else 0), and never run them.

    shutil.which("tar") searches PATH like the shell does and returns the full path, or None if the tool is missing. Check every tool a script needs before doing any work: fail fast with a clear list, instead of dying halfway through.

    Commands taughtpy-shutil-which

    ▶ Play: Tool checkSOLUTION HIDDEN30 XP
  8. 31

    Level 31: Disk alarm

    Alone⏱ TimedHard

    Objective: ~/engine/diskcheck.py [--threshold N=90]: df -P, print 'MOUNT USE%' per mount at/over N, exit 1; else 'disk ok', exit 0. df fails/hangs: stderr, exit 1.

    Wrapping a tool means reading its output: df -P gives one line per filesystem, columns split by spaces, Capacity in column 5 ("87%") and the mount in column 6. Skip the header, split each line, strip the %, compare as int.

    Commands taughtpy-tool-output

    ▶ Play: Disk alarmSOLUTION HIDDEN40 XP
  9. 32

    Level 32: Port watch

    Alone⏱ TimedHard

    Objective: ~/engine/portcheck.py PORT...: ss -ltn, print 'PORT open'/'PORT closed' each; exit 0 if all open, else 1. ss missing/failing/hanging: stderr, exit 1.

    ss -ltn lists listening TCP sockets; column 4 is Local Address:Port (0.0.0.0:22, [::]:22, *:8080), and the port is after the LAST colon: rsplit(":", 1)[1]. Compare whole numbers, never 'in' the line: 80 is in 8080.

    ▶ Play: Port watchSOLUTION HIDDEN40 XP
  10. 33

    Level 33: BOSS: The night shift

    Boss⏱ TimedHard

    Objective: Port ~/engine/nightly.sh to ~/engine/nightly.py SRC DEST [--dry-run] [--verbose]: argparse, tar as a list, timeout, exit codes, stderr messages and logging.

    nightly.sh archives a folder every night, but it never quotes its variables and ignores failures: a strange folder name runs commands, a failed tar still says 'archived' and exits 0. Port it to a Python CLI that cron can trust.

    Commands taughtpy-bash-to-python

    ▶ Play: BOSS: The night shiftSOLUTION HIDDEN120 XP

World 4The Relay

8 levels

Static on the radio tower that relays every service call. Kern climbs up with you to speak HTTP from Python and build a deploy gate that says no.

  1. 34

    Level 34: First contact

    GuidedEasy

    Objective: Write ~/relay/services.py: GET http://api.relay/services (a JSON list) and print 'NAME VERSION' for each service, one per line.

    urllib.request.urlopen(url, timeout=5) sends a GET and gives back a response. resp.read() is the body as bytes; json.loads() turns that JSON into Python lists and dicts. Use it in a with-block so the connection is closed.

    Commands taughtpy-urllib-getpy-relay-api

    ▶ Play: First contactSOLUTION HIDDEN20 XP
  2. 35

    Level 35: Dead air

    GuidedEasy

    Objective: ~/relay/svc.py NAME: GET /services/NAME (timeout=3). 200: 'NAME VERSION', exit 0. HTTP error: 'NAME: HTTP CODE', exit 1. No answer: 'NAME: unreachable', exit 2.

    Two failures: the server ANSWERED with an error status (404, 500: urllib.error.HTTPError, e.code), or no answer came (no server: URLError; too slow: TimeoutError). HTTPError is a kind of URLError: catch it FIRST. timeout= caps the wait.

    Commands taughtpy-urllib-errors

    ▶ Play: Dead airSOLUTION HIDDEN20 XP
  3. 36

    Level 36: Signed orders

    GuidedEasy

    Objective: ~/relay/deploy.py SERVICE VERSION: POST that JSON to http://api.relay/deploys, print 'deploy ID queued'. HTTP error: 'deploy rejected: HTTP CODE', exit 1.

    To send data, build a urllib.request.Request: data= is the body as bytes (json.dumps(...).encode()), headers= says what it is (Content-Type: application/json), method="POST". The API answers 201 Created with JSON of its own.

    Commands taughtpy-urllib-post

    ▶ Play: Signed ordersSOLUTION HIDDEN20 XP
  4. 37

    Level 37: The long list

    AloneMedium

    Objective: Write ~/relay/all.py: print every service name from every page of http://api.relay/services?page=N, one per line, and stop when next is null.

    Big lists come in pages: /services?page=1 answers {"page": 1, "next": 2, "services": [...]}, the last page has "next": null (None in Python). Loop: fetch, print, follow next until it is None. A while loop runs as long as its condition is true.

    Commands taughtpy-http-pages

    ▶ Play: The long listSOLUTION HIDDEN30 XP
  5. 38

    Level 38: Try again

    AloneMedium

    Objective: ~/relay/retry.py PATH: GET http://api.relay/PATH and print the body. 5xx: retry, 4 tries max, wait 0.3 s then double. 4xx: no retry. Failure: exit 1.

    A 5xx means the server is struggling: wait and try again, a bit longer each time (backoff: 0.3 s, 0.6 s, 1.2 s, time.sleep). A 4xx means YOUR request is wrong: retrying sends the same wrong request, so stop at once. Always cap the tries.

    Commands taughtpy-http-retry

    ▶ Play: Try againSOLUTION HIDDEN30 XP
  6. 39

    Level 39: The badge

    AloneMedium

    Objective: ~/relay/rotations.py: GET /admin/rotations with Bearer $RELAY_TOKEN, print 'SERVICE KEY DUE' lines. No token: exit 2, no call. 401: exit 1.

    Admin endpoints want a token: the header Authorization: Bearer TOKEN. The token is a secret, so it never goes in the code (code gets copied, committed, pasted): read it from the environment with os.environ.get("RELAY_TOKEN"). A wrong token gets 401.

    Commands taughtpy-http-auth

    ▶ Play: The badgeSOLUTION HIDDEN30 XP
  7. 40

    Level 40: PAGER: Night watch

    Alone⏱ TimedHard

    Objective: Pager: ~/relay/check.py NAME...: print 'NAME ok', 'NAME down (HTTP CODE)' or 'NAME unreachable' (timeout=2). Exit with the worst: 0 ok, 1 down, 2 unreachable.

    Monitoring tools (Nagios, cron alerts, CI) read ONE thing: the exit code. 0 = all fine, 1 = something is down, 2 = we could not even ask. Check every service, never stop at the first problem, and let the worst status win.

    Commands taughtpy-health-exit

    ▶ Play: PAGER: Night watchSOLUTION HIDDEN40 XP
  8. 41

    Level 41: BOSS: The deploy gate

    Boss⏱ TimedHard

    Objective: ~/relay/gate.py SERVICE VERSION: deploy only when every service in /services is healthy. Retry blips, time out hangs, exit 0 / 1 closed / 2 API unreachable.

    Friday, 17:55. Someone wants to ship. The gate is the script that says no: it asks the API for every service, checks each one's health, and POSTs the deploy only if all of them are healthy. It must not lie, not hang, and not panic at one blip.

    Commands taughtpy-deploy-gate

    ▶ Play: BOSS: The deploy gateSOLUTION HIDDEN120 XP

World 5The Workshop

11 levels

Templates, test benches and a ticket printer that never sleeps. Kern's rule over the door: run it twice; if run two changes anything, it isn't done.

  1. 42

    Level 42: Blank forms

    GuidedEasy

    Objective: Write ~/workshop/render.py TEMPLATE KEY=VALUE...: print the filled template; a missing key → 'missing key: NAME' on stderr, exit 1.

    string.Template fills $name and ${name} holes in a text from a dict; $$ is a literal $. substitute() raises KeyError when a key is missing, safe_substitute() quietly leaves the hole: for configs you want the loud one.

    Commands taughtpy-template

    ▶ Play: Blank formsSOLUTION HIDDEN20 XP
  2. 43

    Level 43: Exactly once

    GuidedEasy

    Objective: Write ~/workshop/ensure_line.py FILE LINE: make LINE a line of FILE exactly once; print 'changed' if you wrote, 'ok' if it was already there.

    Idempotent means: run it twice, the second run changes nothing. Look before you write: if the line is already there, say 'ok' and touch nothing; otherwise add it and say 'changed'. That is how Ansible reports every task.

    Commands taughtpy-idempotent

    ▶ Play: Exactly onceSOLUTION HIDDEN20 XP
  3. 44

    Level 44: Swap in place

    GuidedEasy

    Objective: Write ~/workshop/set_key.py FILE KEY VALUE: set KEY=VALUE, keep FILE.bak, swap in via temp file + os.replace, print changed; same value → 'ok', nothing touched.

    Writing over a live config is a gamble: crash halfway and the service reads half a file. Write the new text to a temp file in the same folder, then os.replace(tmp, path): the swap is all or nothing. Keep the old one as .bak first.

    Commands taughtpy-atomic-write

    ▶ Play: Swap in placeSOLUTION HIDDEN25 XP
  4. 45

    Level 45: Probes

    GuidedEasy

    Objective: Write ~/workshop/probe.py PORT MIN_FREE_MB: print 'port 7070 open' (or closed), then 'disk ok' (or low: MB free on /); exit 0 only if both are fine.

    socket.create_connection((host, port), timeout=2) is the Python 'is anything listening?': it connects or raises OSError (refused, timed out). shutil.disk_usage(path).free is the free space in bytes, like df.

    Commands taughtpy-socket-probe

    ▶ Play: ProbesSOLUTION HIDDEN25 XP
  5. 46

    Level 46: Guard tests

    GuidedEasy

    Objective: Write ~/workshop/test_hostnames.py with unittest tests for every rule of normalize_host (hostnames.py), strong enough to catch each planted bug.

    A test pins down what code must do. unittest is in every python3: a class extending unittest.TestCase, methods named test_…, self.assertEqual / assertTrue / assertRaises. Run them with python3 -m unittest. A good test fails when someone breaks the code.

    Commands taughtpy-unittest

    ▶ Play: Guard testsSOLUTION HIDDEN30 XP
  6. 47

    Level 47: Report and dry run

    GuidedEasy

    Objective: report.py FILE [--report OUT] [--dry-run]: print 'lines: N' (non-blank); --report writes {"lines": N} to OUT, --dry-run: 'would write OUT' instead.

    add_argument('--report') gives args.report (None when absent); add_argument('--dry-run', action='store_true') gives args.dry_run (dash becomes underscore), True only when typed. --report PATH saves a result; --dry-run touches nothing.

    Commands taughtpy-argparse

    ▶ Play: Report and dry runSOLUTION HIDDEN25 XP
  7. 48

    Level 48: One per host

    AloneMedium

    Objective: Write ~/workshop/render_all.py INVENTORY TEMPLATE OUTDIR: OUTDIR/<name>.conf per host, print 'rendered N configs'; missing key → stderr, exit 1, no files.

    One template, many hosts: the inventory (JSON) holds each host's values, the template the shape. Render every host first; write only when all of them worked, so a typo in host 40 never leaves you with 39 new configs and one old one.

    Commands taughtpy-inventory-render

    ▶ Play: One per hostSOLUTION HIDDEN35 XP
  8. 49

    Level 49: Health board

    Alone⏱ TimedHard

    Objective: Write ~/workshop/health.py CHECKS.json: for each check (type file/port/disk, unknown = FAIL) print 'OK name' or 'FAIL name' in order; exit 1 if any failed.

    A health check tool reads its checks from a file, runs every one (a failure never stops the others), prints one line each and sums it up in the exit code. Monitors and cron read the exit code; humans read the lines.

    Commands taughtpy-health-checks

    ▶ Play: Health boardSOLUTION HIDDEN40 XP
  9. 50

    Level 50: PAGER: size limits

    Alone⏱ TimedHard

    Objective: Write ~/workshop/test_sizes.py with unittest tests for every rule of parse_size (sizes.py), strong enough to catch five planted bugs.

    Pager: a refactor of parse_size() shipped a bug and logs filled a disk, because nothing tested it. Mutation testing grades tests by breaking the code on purpose: a test suite that still passes against broken code is not guarding anything.

    Commands taughtpy-mutation-testing

    ▶ Play: PAGER: size limitsSOLUTION HIDDEN45 XP
  10. 51

    Level 51: BOSS: TICKET OPS-311

    Boss⏱ TimedHard

    Objective: Build ~/workshop/rotate.py LOGDIR [--days N] [--report FILE] (gzip old *.log into LOGDIR/archive, JSON report, idempotent, clean errors) and test_rotate.py.

    TICKET OPS-311: /var/log on the build box filled up again. Wanted: a tool cron can run every night that archives old logs, writes a report the dashboard reads, changes nothing on a second run, and comes with tests.

    Commands taughtpy-rotate

    ▶ Play: BOSS: TICKET OPS-311SOLUTION HIDDEN120 XP
  11. 52

    Level 52: BOSS: TICKET OPS-412

    Boss⏱ TimedHard

    Objective: Build ~/workshop/rollout.py INVENTORY TEMPLATE DEST [--dry-run]: render per host, write only changes, atomic + .bak, a diff on --dry-run, exit codes.

    TICKET OPS-412: roll the new app.conf out to every host in the inventory. Change only what differs, never leave a half-written file, and give the reviewer a --dry-run diff before anything is touched.

    Commands taughtpy-difflib

    ▶ Play: BOSS: TICKET OPS-412SOLUTION HIDDEN140 XP

For teachers

Use these levels with a class

SOLUTION HIDDEN Teachers see answer keys in the classroom.

For teachers
ROOTSPIRE
DiscsFor teachers
▶ Play freeLibrary 16 discsDiscsFor teachersLog in