with contextlib.suppress(FileNotFoundError): p.unlink() (or p.unlink(missing_ok=True))
Custom exception hierarchy
class OpsError(Exception): ..., class ConfigError(OpsError): ...
Group of errors (3.11+)
except* TimeoutError as eg: for ExceptionGroup from TaskGroup
Never
bare except: (catches KeyboardInterrupt, SystemExit) or except Exception: pass
python
from contextlib import contextmanager, ExitStackimport os@contextmanagerdef temporary_env(**changes): old = {k: os.environ.get(k) for k in changes} os.environ.update(changes) try: yield finally: # runs on success, exception, or Ctrl+C for k, v in old.items(): if v is None: os.environ.pop(k, None) else: os.environ[k] = vwith ExitStack() as stack: # variable number of resources files = [stack.enter_context(open(p, encoding="utf-8")) for p in paths]
# Stream output live (e.g. terraform apply) and still get the exit codewith subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) as p: for line in p.stdout: log.info(line.rstrip())if p.returncode != 0: raise subprocess.CalledProcessError(p.returncode, cmd)# Equivalent of: journalctl -u nginx | grep error (no shell=True)j = subprocess.Popen(["journalctl", "-u", "nginx", "--no-pager"], stdout=subprocess.PIPE)g = subprocess.run(["grep", "-i", "error"], stdin=j.stdout, capture_output=True, text=True)j.stdout.close(); j.wait()
Never: subprocess.run(f"rm -rf {user_input}", shell=True). A list of arguments is never parsed by a shell, so ; rm -rf / stays a literal filename. os.system and os.popen are the legacy versions of the same mistake.
# Edit a Kubernetes manifest: bump the image in every Deployment of a multi-doc filedocs = list(yaml.safe_load_all(Path("app.yaml").read_text(encoding="utf-8")))for d in docs: if d and d.get("kind") == "Deployment": for c in d["spec"]["template"]["spec"]["containers"]: c["image"] = c["image"].rsplit(":", 1)[0] + ":v1.4.2"Path("app.yaml").write_text(yaml.safe_dump_all(docs, sort_keys=False), encoding="utf-8")
YAML gotchas: yaml.load without SafeLoader can construct arbitrary Python objects (code execution). PyYAML follows YAML 1.1, so unquoted no, off, yes, on become booleans and 0755 becomes an octal int. Quote values when in doubt. Use ruamel.yaml when you must preserve comments.
c = sts.assume_role(RoleArn=arn, RoleSessionName="audit")["Credentials"] then boto3.session.Session(aws_access_key_id=c["AccessKeyId"], aws_secret_access_key=c["SecretAccessKey"], aws_session_token=c["SessionToken"])
Local endpoint (moto server, LocalStack)
AWS_ENDPOINT_URL=http://localhost:5000 (boto3 1.28+) or endpoint_url=
Debug the wire
boto3.set_stream_logger("botocore", logging.DEBUG) (logs signed requests, keep out of CI logs)
from concurrent.futures import ThreadPoolExecutor, as_completedwith ThreadPoolExecutor(max_workers=16) as pool: futures = {pool.submit(check_region, r): r for r in regions} for fut in as_completed(futures): region = futures[fut] try: results[region] = fut.result() except Exception as exc: # one failure must not lose the others errors[region] = str(exc)
python
import asyncio, httpxasync def fetch_all(urls: list[str], limit: int = 100) -> list[int | str]: sem = asyncio.Semaphore(limit) async with httpx.AsyncClient(timeout=10) as client: async def one(url: str) -> int | str: async with sem: try: return (await client.get(url)).status_code except httpx.HTTPError as exc: return type(exc).__name__ async with asyncio.timeout(120): # 3.11+ return await asyncio.gather(*(one(u) for u in urls))results = asyncio.run(fetch_all(urls))
The GIL allows one thread to run Python bytecode at a time but is released during I/O, so threads speed up API fan-out and do nothing for pure CPU work. Free-threaded CPython (3.13t+) is optional and still not what production images use.
from kubernetes import client, config, watchtry: config.load_incluster_config() # inside a pod (ServiceAccount token)except config.ConfigException: config.load_kube_config() # ~/.kube/config, honours KUBECONFIG and current contextv1, apps = client.CoreV1Api(), client.AppsV1Api()for pod in v1.list_namespaced_pod("prod", label_selector="app=web").items: restarts = sum(cs.restart_count for cs in pod.status.container_statuses or []) print(pod.metadata.name, pod.status.phase, restarts)apps.patch_namespaced_deployment_scale("web", "prod", {"spec": {"replicas": 5}})w = watch.Watch()for ev in w.stream(v1.list_namespaced_event, "prod", timeout_seconds=300): print(ev["type"], ev["object"].reason, ev["object"].message)
Task
Code
Paginate
limit=200, _continue=resp.metadata._continue
Handle API errors
except client.exceptions.ApiException as e: if e.status == 404: ...
Watch restart rule
track resourceVersion; on 410 Gone, re-list and watch again
Rollout restart
patch spec.template.metadata.annotations["kubectl.kubernetes.io/restartedAt"] with a timestamp
python
import dockerd = docker.from_env() # honours DOCKER_HOST, e.g. ssh://user@hostd.containers.run("alpine:3.20", ["echo", "hi"], remove=True)for c in d.containers.list(all=True, filters={"status": "exited"}): c.remove()print(d.images.prune(filters={"dangling": True})["SpaceReclaimed"])
SSH with Fabric (paramiko underneath):
python
from fabric import Connectionwith Connection("web1", user="deploy", connect_timeout=10) as c: r = c.run("systemctl is-active nginx", warn=True, hide=True) if r.exited != 0: c.sudo("systemctl restart nginx") c.put("app.conf", "/tmp/app.conf")
Built-in fixtures to know: tmp_path, monkeypatch, capsys, caplog (assert log records), request. Patch where a name is looked up: if cli.py does from subprocess import run, patch opstool.cli.run.
import boto3, pytestfrom moto import mock_aws # moto 5: one decorator for every service@pytest.fixture(autouse=True)def aws_credentials(monkeypatch): # tests can never hit a real account for k in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"): monkeypatch.setenv(k, "testing") monkeypatch.setenv("AWS_DEFAULT_REGION", "us-east-1") monkeypatch.delenv("AWS_PROFILE", raising=False)@pytest.fixturedef s3(): with mock_aws(): yield boto3.client("s3", region_name="us-east-1")def test_bucket_without_versioning_is_flagged(s3): s3.create_bucket(Bucket="logs") assert "logs" in audit_versioning(s3)
Tip
Detail
Create clients inside the mock
A client created before mock_aws() starts talks to real AWS
Clean EC2 account
MOTO_EC2_LOAD_DEFAULT_AMIS=false skips ~1,300 preloaded AMIs and snapshots
Inject time
Pass now= into your code; moto timestamps are "now" and cannot be backdated
Server mode
moto_server -p 5000 + AWS_ENDPOINT_URL=http://localhost:5000 to test a whole CLI or another language
Old syntax
mock_ec2, mock_s3 were removed in moto 5; use mock_aws
Alternatives
botocore.stub.Stubber for exact request/response assertions; LocalStack for integration tests
mypy src (strict via config); boto3 types: pip install "boto3-stubs[ec2,s3]"
Security lint
ruff check --select S . or bandit -r src
Dependency CVEs
pip-audit -r requirements.lock
Pre-commit hooks
pre-commit install with ruff and mypy hooks
Build sdist and wheel
python -m build (or uv build) → dist/
Inspect a wheel
unzip -l dist/*.whl
Install a built wheel
pip install dist/opstool-0.1.0-py3-none-any.whl
Run as a module
python -m opstool (needs __main__.py)
Version from code
importlib.metadata.version("opstool")
Publish
twine upload dist/*, or trusted publishing (OIDC) from GitHub Actions
Single-file script with dependencies
PEP 723 header # /// script + dependencies = [...], run with uv run script.py
Type hint cheats: list[str], dict[str, int], str | None, Callable[[str], bool], Iterator[dict[str, Any]], TypedDict for JSON shapes, Protocol for duck typing, from __future__ import annotations for forward references.
# Pretty-print / validate JSONpython3 -m json.tool response.jsoncurl -s https://api.github.com/repos/python/cpython | python3 -c 'import sys, json; print(json.load(sys.stdin)["stargazers_count"])'# YAML to JSON (needs PyYAML), then use jqpython3 -c 'import sys, yaml, json; print(json.dumps(yaml.safe_load(sys.stdin), indent=2))' < values.yaml | jq '.image'# Validate every YAML file in a repopython3 -c 'import sys, yaml; [list(yaml.safe_load_all(open(f))) for f in sys.argv[1:]]' $(git ls-files '*.yaml' '*.yml')# Serve the current directory on port 8000 (debugging only)python3 -m http.server 8000 --bind 127.0.0.1# Base64 decode a Kubernetes secret valuekubectl get secret db -o jsonpath='{.data.password}' | python3 -c 'import sys, base64; print(base64.b64decode(sys.stdin.read()).decode())'# Random password / tokenpython3 -c 'import secrets; print(secrets.token_urlsafe(32))'# Epoch to UTC and backpython3 -c 'import datetime as d; print(d.datetime.fromtimestamp(1767225600, d.UTC))'python3 -c 'import time; print(int(time.time()))'# Top 10 client IPs from an access logpython3 -c 'import sys, collections; c = collections.Counter(l.split()[0] for l in sys.stdin if l.strip()); [print(n, ip) for ip, n in c.most_common(10)]' < access.log# Is a port open?python3 -c 'import socket, sys; s = socket.create_connection((sys.argv[1], int(sys.argv[2])), timeout=3); print("open")' db.internal 5432# TLS certificate expirypython3 -c 'import ssl, socket; h = "example.com"; s = ssl.create_default_context().wrap_socket(socket.create_connection((h, 443), timeout=5), server_hostname=h); print(s.getpeercert()["notAfter"])'# SHA-256 of a filepython3 -c 'import hashlib, sys; print(hashlib.file_digest(open(sys.argv[1], "rb"), "sha256").hexdigest())' artifact.tgz# URL-encode a stringpython3 -c 'import urllib.parse, sys; print(urllib.parse.quote(sys.argv[1], safe=""))' 'a b&c=d'# Which Python, venv and site-packages am I usingpython3 -c 'import sys, site; print(sys.executable, sys.prefix, site.getsitepackages())'# Time a snippetpython3 -m timeit -s 'xs = list(range(10_000))' 'sum(x * x for x in xs)'# Profile a scriptpython3 -m cProfile -s cumtime script.py | head -25
Why Python over Bash: real data structures, error handling, tests and SDKs; Bash for glue under ~50 lines, Python once there is parsing, APIs or logic.
Mutable default argument: defaults are evaluated once at def time, so def f(x=[]) shares one list; use None and create it inside.
Generator vs list: a generator yields lazily in constant memory; use it for big files and paginated APIs.
subprocess.run safely: pass a list, check=True, capture_output=True, text=True, timeout=; never shell=True with untrusted input.
yaml.safe_load: plain yaml.load can build arbitrary Python objects, which means code execution from a config file.
requests defaults: no timeout means wait forever; always pass timeout=(connect, read), use a Session, and retry only idempotent calls with backoff on 429/5xx.
boto3 client vs resource: clients map 1:1 to the API and are thread-safe; resources are a feature-frozen OO layer. Sessions are not thread-safe, so one per thread.
Pagination: every list API is paginated; a script without a paginator silently audits only page one.
boto3 errors: catch ClientError and branch on e.response["Error"]["Code"]; use adaptive retry mode for throttling.
Credentials: never in code; the provider chain finds env vars, SSO profiles, IRSA/Pod Identity, ECS task roles or IMDSv2; CI uses OIDC.
GIL: one thread runs bytecode at a time, but I/O releases it; threads for API fan-out, processes for CPU, asyncio for thousands of concurrent connections.
Exit codes and streams: 0 success, non-zero failure, results on stdout, logs on stderr; that is what makes a script usable in CI and pipes.
Logging over print: levels, timestamps and logger names, configured once in main(), JSON to stdout/stderr in containers.
Testing AWS code: pytest with moto's mock_aws exercises real botocore request validation in memory; inject the clock, fake credentials in an autouse fixture.
Reproducible environments: a venv per project, ranges in pyproject.toml, exact pins with hashes in a lock, and a multi-stage non-root image for shipping.