Module 11 (Supplement): Python for DevOps — The Complete Guide
Goal
Bash is glue; Python is the power tool. When a script needs real logic, API calls, JSON handling, or error recovery, DevOps engineers reach for Python. This module teaches exactly the Python a DevOps job requires — no web frameworks, no data science — just automation, cloud APIs, and tooling. It also prepares you for the scripting round in DevOps interviews.
Where it fits
best read after Module 3 (Bash), but works anytime. Rule of thumb from Module 3: bash for < 200 lines of command-gluing; Python for anything with logic, data structures, APIs, or error handling.
1. Setup & Running Python
python3 --version # 3.10+ is fine; installed on nearly every Linux
python3 script.py # run a script
python3 # interactive REPL — your experiment labAnalogy
Python is the Swiss Army knife you reach for when the bash butter-knife stops being enough. Bash is brilliant for gluing commands together, but once you're slicing JSON, calling APIs, and handling errors, you want the multi-tool with the right blade for each job. This module is you graduating from one knife to the whole kit.
Virtual environments — the Python equivalent of "don't install globally." Every project gets its own isolated package set (this prevents the "works on my machine" dependency mess Docker also solves):
Analogy
A virtual environment is giving each project its own toolbox instead of tossing every tool into one shared drawer. Project A can keep its old wrench and Project B a newer one, and neither reaches into the other's box. requirements.txt is the packing list taped inside the lid, so anyone can rebuild the exact same toolbox somewhere else.
python3 -m venv .venv # create
source .venv/bin/activate # enter (prompt changes)
pip install requests boto3 # installs land INSIDE .venv
pip freeze > requirements.txt # lock what you installed
pip install -r requirements.txt # reproduce elsewhere (this line is in every Dockerfile you wrote!)
deactivateThis is exactly the COPY requirements.txt + RUN pip install -r requirements.txt pattern you'll meet in Module 5's Dockerfiles — same lockfile, same reason.
Script skeleton — the Python version of your bash header:
#!/usr/bin/env python3
"""Cleanup old log files. Usage: cleanup.py /var/log 14"""
import sys
def main() -> int:
...
return 0 # exit code, same meaning as bash
if __name__ == "__main__": # runs only when executed, not when imported
sys.exit(main())2. Core Language — Fast, Through a DevOps Lens
Variables & types
name = "web-01" # str
port = 8080 # int
cpu = 72.5 # float
healthy = True # bool (capital T/F!)
nothing = None # like null
f"Server {name} on port {port}" # f-strings — use these for all formattingUnlike bash: no $, real data types, spaces around = are fine, and indentation is syntax — blocks are defined by consistent 4-space indents, not braces.
Analogy
A dict is a labelled set of drawers, and it's the single most important tool in the kit because JSON — the language every cloud API speaks — is basically a stack of these drawers. Learn to open and refill drawers by their labels and you can handle almost any API response you'll ever meet on the job.
Collections (the big upgrade over bash)
# list — ordered, like bash arrays but sane
servers = ["web-01", "web-02", "db-01"]
servers.append("cache-01")
servers[0] # "web-01"
servers[-1] # last item
len(servers) # 4
"db-01" in servers # True
# dict — key/value, THE data structure of DevOps (JSON is basically dicts)
instance = {
"id": "i-0abc123",
"type": "t3.micro",
"tags": {"Env": "prod", "Team": "platform"},
"private_ips": ["10.0.11.5"],
}
instance["type"] # "t3.micro"
instance.get("public_ip", "none") # safe access with default — no KeyError
instance["state"] = "running" # add/update
# tuple — immutable list; set — unique items (dedupe: set(mylist))Conditionals & loops
if cpu > 90:
print("critical")
elif cpu > 75:
print("warning")
else:
print("ok")
for s in servers: # for-each, like bash but over real objects
print(f"checking {s}")
for i, s in enumerate(servers): # need the index too
print(i, s)
for key, value in instance["tags"].items(): # loop a dict
print(f"{key}={value}")
while not is_healthy() and attempts < 10: # retry loops
time.sleep(3)
attempts += 1List/dict comprehensions — one-line transforms you'll see everywhere in real code:
prod = [s for s in servers if s.startswith("web")] # filter
ips = [i["PrivateIpAddress"] for i in instances] # extract a field
by_id = {i["InstanceId"]: i["State"] for i in instances} # build a lookup dictFunctions
def check_disk(path: str, threshold: int = 85) -> bool:
"""Return True if usage of `path` is below threshold %."""
usage = shutil.disk_usage(path)
percent = usage.used / usage.total * 100
return percent < threshold
# type hints (str, int, -> bool) are optional but professional: editors and
# reviewers catch bugs early. Use them.Error handling — where Python beats bash decisively
try:
resp = requests.get(url, timeout=5)
resp.raise_for_status() # raise on 4xx/5xx
data = resp.json()
except requests.Timeout:
log.warning("timed out, retrying...")
except requests.HTTPError as e:
log.error(f"HTTP {e.response.status_code} from {url}")
raise # re-raise: don't swallow unknown errors
finally:
cleanup() # always runs (like bash trap EXIT)Rules that mark professional code: catch specific exceptions (bare except: hides bugs), let unexpected errors crash loudly (a silent broken automation is worse than a dead one), use finally/context managers for cleanup.
3. Files, JSON & YAML — The Data Formats of Your Job
# Files — the with-block closes automatically even on errors
with open("/var/log/app.log") as f:
for line in f: # memory-safe even for huge files
if "ERROR" in line:
print(line.strip())
with open("report.txt", "w") as f:
f.write("all good\n")JSON — every API, every cloud CLI, every K8s object speaks it:
import json
data = json.loads(text) # string → dict
text = json.dumps(data, indent=2) # dict → string
data = json.load(open("cfg.json")) # file → dictYAML — every K8s manifest, Compose file, CI workflow, Ansible playbook:
import yaml # pip install pyyaml
with open("deployment.yaml") as f:
doc = yaml.safe_load(f) # ALWAYS safe_load (plain load can execute code)
doc["spec"]["replicas"] = 5
doc["spec"]["template"]["spec"]["containers"][0]["image"] = "myapp:v2.4.0"
with open("deployment.yaml", "w") as f:
yaml.safe_dump(doc, f, sort_keys=False)That snippet — programmatically editing a K8s manifest — is a real interview task and a real job task. Notice how a YAML file is just nested dicts/lists once loaded; navigate it exactly like the kubectl get -o yaml structure you'll work with in Module 7 (Kubernetes).
Also know: csv module (reports), configparser (.ini), and pathlib:
from pathlib import Path
for f in Path("/var/log").glob("*.log"):
if f.stat().st_size > 100_000_000:
print(f, "is huge")4. Talking to the OS — Replacing Bash Gradually
Analogy
subprocess is the blade on the multi-tool that still lets you use your old butter-knife when it's genuinely the best fit. You don't have to reimplement docker or kubectl in Python — you hand the shell the raw task and catch its result cleanly. It's the bridge between the two worlds, so you can migrate off bash one command at a time instead of all at once.
import os, shutil, subprocess
os.environ.get("APP_ENV", "dev") # read env vars (config, secrets in CI)
shutil.disk_usage("/") # df in Python
shutil.copy2(src, dst); shutil.rmtree(d) # cp/rm -rf with error handling
# Running commands — the bridge between worlds
result = subprocess.run(
["kubectl", "get", "pods", "-o", "json"], # list form: no shell-injection risk
capture_output=True, text=True, check=True, # check=True → raises on non-zero exit
)
pods = json.loads(result.stdout)
for p in pods["items"]:
print(p["metadata"]["name"], p["status"]["phase"])That pattern — run a CLI, parse its JSON, act on it — is 50% of all DevOps Python. subprocess.run + json.loads will serve you for years.
Arguments & logging — turn scripts into tools:
import argparse, logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description="Prune old backups")
parser.add_argument("path")
parser.add_argument("--days", type=int, default=14)
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()
if args.dry_run:
log.info("DRY RUN — nothing will be deleted")--dry-run flags and real logging (instead of prints) are what separate a script from a tool teammates trust. (For structured JSON logs feeding Loki — Module 10 — use python-json-logger.)
5. HTTP APIs with requests — Automating Everything With an API
Analogy
requests is the phone in the toolkit for calling any service that has a reception desk (an API). You dial the number (the URL), state who you are (the auth header), ask your question, and write down the answer. Once you can make that call cleanly, almost every SaaS, monitoring tool, and chat system becomes something you can automate instead of click through.
import requests
# GET with query params and auth header
resp = requests.get(
"https://api.github.com/repos/myorg/myapp/actions/runs",
headers={"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}"},
params={"status": "failure", "per_page": 5},
timeout=10, # ALWAYS set a timeout
)
resp.raise_for_status()
for run in resp.json()["workflow_runs"]:
print(run["name"], run["conclusion"], run["html_url"])
# POST — e.g., the Slack alert from Module 3 (and the CI pipelines in Module 6), now with error handling
requests.post(SLACK_WEBHOOK, json={"text": f" Disk at {pct}% on {host}"}, timeout=5)Real uses: health-check probes, calling the GitHub/GitLab API from pipelines, querying the Prometheus API (/api/v1/query?query=up==0), Slack/PagerDuty notifications, webhooks between systems. A resilient-call helper worth memorizing:
def get_with_retry(url, attempts=3, backoff=2):
for i in range(attempts):
try:
r = requests.get(url, timeout=5)
r.raise_for_status()
return r
except requests.RequestException as e:
if i == attempts - 1:
raise
wait = backoff ** i
log.warning(f"{e} — retry {i+1}/{attempts} in {wait}s")
time.sleep(wait)Exponential backoff with retries: an interview classic and a daily-life pattern.
6. boto3 — Python for AWS (The Job-Description Line Item)
boto3 is AWS's official Python SDK. Credentials come from the environment/instance role automatically (the IAM discipline you'll formalize in Module 8 — never hardcode keys).
Analogy
boto3 is a direct phone line to AWS wired straight into your toolkit — no dialling, no reading your credentials aloud each call. Because it picks up your instance's IAM badge automatically, it's like a phone that already knows who's calling and only offers the buttons that badge is allowed to press. That's why hardcoding keys is such a smell: you'd be taping a master key to a phone that never needed one.
import boto3
ec2 = boto3.client("ec2")
# The classic: audit instances — list all running, flag untagged
resp = ec2.describe_instances(
Filters=[{"Name": "instance-state-name", "Values": ["running"]}]
)
for reservation in resp["Reservations"]:
for inst in reservation["Instances"]:
tags = {t["Key"]: t["Value"] for t in inst.get("Tags", [])}
if "Owner" not in tags:
print(f"UNTAGGED: {inst['InstanceId']} ({inst['InstanceType']})")
# S3: upload a backup, list old ones
s3 = boto3.client("s3")
s3.upload_file("db_backup.sql.gz", "myco-backups", "db/2026-07-07.sql.gz")
# Stop dev instances at night (a real cost-saving Lambda!)
ids = [i["InstanceId"] for r in resp["Reservations"] for i in r["Instances"]
if {t["Key"]: t["Value"] for t in i.get("Tags", [])}.get("Env") == "dev"]
if ids:
ec2.stop_instances(InstanceIds=ids)Pagination gotcha (interviewers probe this): list calls return max ~1000 items — use paginators for truth:
paginator = s3.get_paginator("list_objects_v2")
for page in paginator.paginate(Bucket="myco-backups", Prefix="db/"):
for obj in page.get("Contents", []):
print(obj["Key"], obj["Size"])Lambda + boto3 (a preview of Module 8's serverless piece) — the nightly dev-shutdown as a real serverless job:
# handler.py — deploy as Lambda, trigger by EventBridge cron(0 20 ? * MON-FRI *)
import boto3
def handler(event, context):
ec2 = boto3.client("ec2")
resp = ec2.describe_instances(Filters=[
{"Name": "tag:Env", "Values": ["dev"]},
{"Name": "instance-state-name", "Values": ["running"]},
])
ids = [i["InstanceId"] for r in resp["Reservations"] for i in r["Instances"]]
if ids:
ec2.stop_instances(InstanceIds=ids)
return {"stopped": ids}This single script pattern — tag-filter → act → report — covers snapshot cleanup, AMI pruning, unattached-EBS hunts, security-group audits… a huge share of real AWS automation.
7. Interview-Style Scripting Problems (Practice These Patterns)
DevOps interviews rarely ask LeetCode algorithms; they ask practical parsing and automation. The recurring shapes:
Log parsing — "top 5 IPs by request count from an nginx log":
from collections import Counter
counts = Counter()
with open("access.log") as f:
for line in f:
counts[line.split()[0]] += 1
for ip, n in counts.most_common(5):
print(ip, n)Threshold report — "print any service whose error rate exceeds 2% from this JSON": load → loop → compute ratio → filter → print.
Config diff — "compare two YAML/JSON configs, print keys that differ": load both into dicts, compare set(a) ^ set(b) and values on the intersection.
Retry/health poller — "wait until this URL returns 200, max 10 tries" (you wrote it in §5).
De-dup / cross-reference — "these instances exist in AWS; these are in the CMDB list; print orphans": two sets, aws_ids - cmdb_ids.
Master Counter, set operations, sorted(items, key=lambda x: x[1], reverse=True), string .split()/.strip()/.startswith(), and dict comprehensions — that toolkit solves ~90% of these live-coding rounds.
8. Quality Habits (Small Effort, Big Professional Signal)
pip install ruff pytest
ruff check . # linter (the shellcheck of Python) — wire into CI
pytest # run testsA taste of testing your automation:
# test_cleanup.py
from cleanup import is_older_than_days
def test_old_file_detected(tmp_path):
f = tmp_path / "old.log"
f.write_text("x")
os.utime(f, (0, 0)) # epoch-old timestamps
assert is_older_than_days(f, 14) is TrueEven two or three tests on a destructive script (the thing that deletes backups) is the difference between "script" and "tool we trust." Wire ruff + pytest into CI (Module 6) for any repo containing Python — the same quality gate you'll build there for everything else.
9. Hands-On Project (Do This)
Build a small ops toolkit repo, devops-pytools, applying every section:
diskreport.py— argparse path + threshold, walks with pathlib, prints biggest dirs,--jsonoutput flag, proper logging.logtop.py— top-N IPs/paths/status codes from an nginx log (Counter), with--nflag.healthwait.py— poll a URL with retry/backoff until healthy or timeout; exit code reflects result (usable in CI!).k8s_image_bump.py— safe_load a deployment YAML, change the image tag from an argument, safe_dump it back (thenkubectl applyit yourself).aws_audit.py(boto3) — list running instances with missing required tags + unattached EBS volumes;--stop-devflag that stops Env=dev instances (with--dry-rundefault!).- Ship it like a pro: venv + requirements.txt, ruff clean, 3+ pytest tests, GitHub Actions CI running both, README. This repo itself becomes a portfolio item.
- Deploy
aws_audit's dev-stopper as a Lambda on an EventBridge schedule (come back to this once you reach Module 8).
10. Self-Check Questions
- When bash vs when Python? Give two concrete triggers to switch.
- Why virtual environments — what problem do they share with Docker?
- Why
subprocess.run([...])list-form instead of a shell string? - Why must you paginate boto3 list calls? Why
yaml.safe_loadnotload? - Write from memory: top-5 counter from a log; a GET with timeout, raise_for_status, and 3-retry backoff.
- Why is a bare
except:dangerous in automation? - What do type hints, logging,
--dry-run, and tests each signal to a hiring team?
Next → Module 4: Networking (with the foundations — Git, Linux, Bash, Python — behind you, the rest of the path builds on them).
