This is a complete, hands-on Python for DevOps cheat sheet: install, configure, operate, automate and secure it - with copy-paste commands grouped by task. Bookmark it for day-to-day work, incidents and interviews alike.
Python is the default scripting language for DevOps automation: readable, batteries-included, and backed by SDKs for every cloud and tool, so you can replace brittle Bash with maintainable scripts.
Why you reach for it
- Readable code with a massive standard and third-party library set
- First-class SDKs for AWS (boto3), Kubernetes and more
- Great for CLIs, API glue and data wrangling
Installation
python3 -m venv .venv && source .venv/bin/activate
pip install --upgrade pip
pip install requests boto3Configuration reference
A small, robust API client with retries.
import requests
from requests.adapters import HTTPAdapter, Retry
s = requests.Session()
s.mount('https://', HTTPAdapter(max_retries=Retry(total=3, backoff_factor=0.5,
status_forcelist=[502, 503, 504])))
r = s.get('https://api.example.com/health', timeout=5)
r.raise_for_status()
print(r.json())Core commands you use daily
python script.py
python -m pytest -q
ruff check . && ruff format .Environments & tooling
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
pip-audit
ruff check . && ruff format .
mypy .
pytest -q --covUseful one-liners
python -m http.server 8000
python -m json.tool < data.json
python -c 'import secrets; print(secrets.token_hex(16))'
python -m venv --upgrade-deps .venvUse it in CI/CD
Lint, type-check and test in CI.
- uses: actions/setup-python@v5
with: { python-version: '3.12', cache: pip }
- run: pip install -r requirements.txt ruff mypy pytest
- run: ruff check . && mypy . && pytest -qBest-practice checklist
- Use virtualenvs and pin dependencies (requirements.txt / pip-tools)
- Add type hints and run mypy + ruff in CI
- Prefer SDKs (boto3, kubernetes) over parsing CLI output
Common pitfalls to avoid
- Global installs instead of virtualenvs, creating dependency conflicts
- Bare except: clauses that swallow real errors
- Shelling out for everything instead of using SDKs
Security quick wins
- Pin dependencies and scan them (pip-audit) for CVEs
- Never hardcode secrets; read them from the environment or a vault
Works well with
- Bash & Shell Scripting - The universal glue on every Linux box - with a few rules it becomes safe and reliable automation.
- Ansible - Agentless configuration management and provisioning over plain SSH, described in readable YAML.
- Amazon Web Services - The largest public cloud - compute, storage, networking and managed services, best driven by IaC.
A cheat sheet is muscle memory on paper - keep it close until the commands live in your fingers.
Want senior help putting Python for DevOps to work - or a team bootcamp on it? CodeWizard runs Israel's largest DevOps community and embeds named senior engineers with a transparent hours log. Book a free consult or explore the Academy.