Exercises — Module 11: Python for DevOps
Rules for every script: venv per project,
requirements.txtcommitted,ruff checkclean, type hints on functions,loggingnot
Part A — Warm-Up Drills (REPL + tiny scripts)
Drill 1 — Collections reps. In the REPL: build a list of 5 fake hostnames; slice first 2, last 1; build a dict service→port for 4 services; add one, safely get a missing one with a default; loop printing name:port; one-line a list of only services with port > 1000 (comprehension); dedupe ["a","b","a","c","b"] preserving nothing (set) then preserving order (dict.fromkeys trick).
✓ Each under 30 seconds, no syntax stumbles.
Drill 2 — String surgery. Given the line 10.0.1.5 - - [07/Jul/2026:14:03:22] "GET /api/users HTTP/1.1" 200 512: extract IP, path, and status using only .split() and indexing. Then f-string them into ip=10.0.1.5 path=/api/users status=200.
✓ You can dissect a log line without regex.
Drill 3 — Exceptions ladder. Write read_config(path) that returns parsed JSON; handle FileNotFoundError (return {}, log warning), json.JSONDecodeError (log error, re-raise), and prove a bare except: would have hidden a KeyboardInterrupt (try it, feel it, delete it).
✓ You can say why each handler exists.
Drill 4 — JSON↔dict fluency. Take kubectl get pods -o json output (or any saved sample). Load it; print each pod's name and phase; count pods per phase into a dict; dump that summary back as pretty JSON.
✓ Nested-dict navigation (d["items"][0]["metadata"]["name"]) feels natural.
Drill 5 — pathlib + os. Script that walks a directory tree, sums total size, prints the 5 biggest files, and reads HOME and a custom env var with a default. No os.system, no shelling out.
Part B — Guided Labs
Lab 1 — logtop.py: Log Analyzer as a Real CLI (90 min)
- Core: parse an nginx access log;
Counters for IPs, paths, status codes. - argparse: positional file,
--top N(default 5),--status-class 4xx|5xxfilter,--jsonoutput mode. - Handle the ugly real world: blank lines, malformed lines (count them, don't crash), gzipped input (
gzip.openif suffix.gz). loggingfor diagnostics on stderr, results on stdout (so it pipes cleanly).- Tests (pytest): feed 5 crafted lines via
tmp_path, assert counts; a malformed-line test; a gz test. ✓ruffclean, 4+ tests green, and./logtop.py access.log --top 3 --json | jqworks.
Lab 2 — healthcheck.py: HTTP with Retries (60 min)
- Read a list of URLs from a YAML file (
safe_load): name, url, expected_status, timeout. - Check all; print a ✓/✗ table with latency; exit non-zero if any fail (CI-usable).
- Add retry with exponential backoff (write it yourself first; THEN compare with
tenacityif curious). - Add
--parallelusingconcurrent.futures.ThreadPoolExecutor; time 10 slow URLs sequential vs parallel (use httpbin.org/delay/2 endpoints). ✓ You wrote the retry/backoff pattern from memory AND made I/O concurrent — two interview staples in one tool.
Lab 3 — k8s_bump.py: YAML Manifest Editor (60 min)
- Load a Deployment YAML (
safe_load); walk tospec.template.spec.containers[0].image; replace the tag with--tagargument;safe_dumpback preserving key order. - Guardrails: refuse if the file has no containers;
--dry-runprinting a unified diff (difflib.unified_diff) instead of writing; back up the original to.bak. - Multi-doc support: handle a file with
----separated Deployment+Service (safe_load_all), touching only the Deployment. - Close the loop: run it against your Module 7 chart's rendered output,
kubectl apply, watch the rollout. ✓ This is literally the CI step that GitOps automates — you've now built it by hand.
Lab 4 — subprocess Bridge: Wrap the CLIs You Know (60 min)
dockerps.py: rundocker ps --format '{{json .}}', parse line-JSON, print a clean table of name/image/status;--filter-image substringoption.gitreport.py: rungit log --pretty=format:%anin a repo path argument, Counter authors, top 5 committers.- Both: list-form subprocess,
check=True,capture_output=True, and a proper error message when the underlying tool is missing (FileNotFoundError). ✓ The run→parse→act pattern is now reflex; you'll never awkwardly parse CLI text in bash again when Python's nearer.
Lab 5 — aws_audit.py: boto3 for Real (2 h)
Against your (cheap!) AWS account:
- List running EC2 instances; flag any missing required tags (
Owner,Env) — the tags-list→dict comprehension from the module. - Find unattached EBS volumes and unassociated Elastic IPs (both bill!). Use paginators even if you have 3 resources — build the habit.
--stop-devaction stoppingEnv=devinstances — dry-run by default,--applyto execute, logging every decision.- Output modes: human table and
--json. - Moto-based test (
pip install moto): mock EC2, create a fake untagged instance, assert your finder flags it — testing cloud code without a cloud. ✓ You have the exact script pattern behind most real AWS automation, tested offline.
Lab 6 — Ship It: Lambda + CI (60 min)
- Convert Lab 5's dev-stopper into a Lambda handler; deploy (console or your Terraform!); EventBridge cron for 20:00 weekdays; confirm via CloudWatch logs after a scheduled run (or a manual test invoke).
- Add Python CI to the repo: GitHub Actions job running
ruff check+pyteston every PR (you know exactly how from Module 6). ✓ Your Python is now deployed, scheduled, and gated — the full lifecycle.
Part C — Timed Interview Katas (20 min each, then compare with your untimed solution)
K1. Given an access log path, print the top 3 IPs with counts. (Target: 10 lines.)
K2. Given two JSON config files, print keys present in one but not the other, and keys whose values differ.
K3. Poll a URL until it returns 200 or 10 attempts pass, 3s apart; exit code reflects outcome.
K4. Given a list of dicts (instances with id, state, tags), return ids of running instances missing an Owner tag — one function, with a test.
K5. Parse df -h output (run it via subprocess) and print any filesystem over N% used.
K6. Read a .env-style file into a dict, ignoring comments/blank lines, erroring on lines without =.
K7. Given nested JSON of arbitrary depth, write a recursive function that finds every key named "password" and prints its path (e.g., db.credentials.password). (The one genuinely algorithmic kata that appears in DevOps screens.)
✓ Done when each kata passes your own test cases within the timer, twice, a week apart.
Part D — Break & Fix Scenarios
D1 — The mutable default. Run this, observe the bug, explain, fix:
def add_server(name, servers=[]):
servers.append(name); return servers
print(add_server("a")); print(add_server("b")) # why ['a','b']?!D2 — Swallowed failure. Take Lab 2 and wrap the whole loop in try: ... except: pass. One URL has a typo'd scheme — the tool reports all-green. Feel the horror; restore specific exceptions; add a test that would have caught it.
D3 — Injection via shell=True. Write a "ping host" function using subprocess.run(f"ping -c1 {host}", shell=True); call it with host="8.8.8.8; touch /tmp/pwned". Check /tmp. Fix with list-form; write the rule on a sticky note.
D4 — The pagination lie. Against moto (or reasoning on paper): a bucket with 1500 objects, code using bare list_objects_v2 — how many does it see? Fix with the paginator and prove the count.
D5 — Timezone/format drift. Your Lab 1 counts "requests per hour" but the log rotates across midnight UTC while you're at UTC+6. Make the bug happen with crafted lines; fix by parsing timestamps with datetime.strptime + explicit timezone rather than string slicing.
Part E — Interview Rehearsal (out loud + whiteboard)
- When do you reach for Python over bash? Three concrete triggers from your own labs.
- Whiteboard K1 and K3 cold.
- How do you run and parse an external command safely in Python? Why never
shell=Truewith user input? - How does your code authenticate to AWS in: a laptop, EC2, Lambda, GitHub Actions? (No keys anywhere — narrate each.)
- How do you test code that calls AWS without calling AWS?
- Show me a script you're proud of — walk through
aws_audit.py: its safety rails, tests, and one bug you hit building it.
Done when
all labs are ruff-clean with tests, all katas pass timed twice, D1–D3's morals are memorized one-liners, and E6's walkthrough of your own repo flows like a story.
