Introduction
Every DevOps engineer ends up writing the same five scripts: check whether a service is up, read a config file, run a shell command and react to its output, talk to a cloud API, and glue those steps into something that runs on a schedule. Python is the language those scripts are written in — not because it is the fastest or the most elegant, but because it is readable, it has a library for everything, and it runs everywhere your infrastructure does.
This tutorial is practical, not a language course. It assumes you can already write basic Python and teaches the five patterns DevOps work actually uses, with scripts you can copy and adapt. You need Python installed and the terminal basics from our Linux Commands guide. Where a shell script would do the job better, we say so — our Bash Scripting tutorial covers that side.
Version note (28 Nov 2026): the latest Python is 3.15.2 (the 3.15 line was released on 9 October 2026; 3.14 dates from October 2025). Python 3.10 reached end of life on 1 October 2026 — if your scripts still run on it, upgrade. Library versions used here: requests 2.34.2, boto3 1.44.12, paramiko 5.1.0, PyYAML 6.0.4.
Tested 28 Nov 2026 on Python 3.12.3: the health check returned HTTP 200 for devopsjobupdates.com, the YAML loader printed both services, and the subprocess pattern ran cleanly. The boto3 example needs AWS credentials to run, and kubectl was not installed on the test machine.
Set Up a Project Properly — Virtual Environments
Every Python automation project starts the same way: a virtual environment. It isolates your project’s libraries from the system Python, so upgrading a library for one script cannot break another. venv is the standard tool — it has shipped with Python since 3.5 — and the command is:
python3 -m venv ~/devops-scripts source ~/devops-scripts/bin/activate python3 -m pip install --upgrade pip
Your prompt changes to show the environment is active. Install the libraries this tutorial uses:
pip install requests boto3 pyyaml paramiko
Two habits to adopt now. First, keep a requirements.txt with pinned versions (pip freeze > requirements.txt) so the next person — or the next server — installs exactly what you tested with. Second, never install automation libraries into the system Python: a system upgrade can replace them, and a pip install with sudo can break the operating system’s own tools. A virtual environment costs one command and removes both risks.
Pattern 1 — Call an API and Handle Failure
The most common DevOps script checks whether something is up. Here is a health check that calls a service, times out properly, and exits with a status code a monitoring system or CI pipeline can use:
import sys
import requests
URL = "https://devopsjobupdates.com/"
TIMEOUT_SECONDS = 10
try:
response = requests.get(URL, timeout=TIMEOUT_SECONDS)
response.raise_for_status()
except requests.exceptions.Timeout:
print(f"TIMEOUT: no response from {URL} in {TIMEOUT_SECONDS}s")
sys.exit(2)
except requests.exceptions.RequestException as exc:
print(f"DOWN: {exc}")
sys.exit(2)
print(f"OK: {URL} returned {response.status_code} in {response.elapsed.total_seconds():.2f}s")
Three details matter. First, always pass a timeout — without one, requests.get can hang forever, and a monitoring script that hangs is worse than no monitoring script. Second, raise_for_status() turns HTTP error codes into exceptions, so a 500 is a failure, not a success with a sad body. Third, exit codes: 0 means healthy, non-zero means a problem, and different non-zero codes can mean different problems. This is the contract that lets a shell script, a cron job or a GitHub Actions workflow act on the result.
The same pattern works for any JSON API — deployment webhooks, cloud status pages, internal tools. Parse the response with response.json(), check the fields you care about, and fail loudly when they are wrong.
Pattern 2 — Read Configuration from a YAML File
Hard-coded values are the first thing to remove from a script. Put them in a YAML file instead — the same format Ansible playbooks and Kubernetes manifests use — and load them with PyYAML:
# config.yaml
services:
- name: website
url: https://devopsjobupdates.com/
timeout_seconds: 10
- name: api
url: https://api.example.com/health
timeout_seconds: 5
alert_email: ops@example.com
import yaml
with open("config.yaml") as f:
config = yaml.safe_load(f)
for service in config["services"]:
print(service["name"], service["url"], service["timeout_seconds"])
Always use yaml.safe_load, never yaml.load — the safe loader cannot construct arbitrary Python objects, which is what makes loading an untrusted config file safe. Combine the two patterns and you have a real tool: a health checker that reads its targets from a config file, checks each one, and reports the failures. That is a genuinely useful script, and it is about thirty lines long.
Pattern 3 — Run Shell Commands with subprocess
Python does not replace the shell; it orchestrates it. The subprocess module runs commands and captures their output — the right way to call kubectl, docker, git or any CLI from a script:
import subprocess
result = subprocess.run(
["kubectl", "get", "pods", "--namespace", "default"],
capture_output=True, text=True, timeout=30,
)
if result.returncode != 0:
print("kubectl failed:", result.stderr.strip())
else:
print(result.stdout)
Use the list form of the command, not a string with shell=True. The list form passes arguments exactly, so a filename with a space in it cannot break the command — and a value from an untrusted source cannot inject a second command. Reserve shell=True for the rare cases where you genuinely need shell features, and never use it with input you did not write yourself.
A practical use: wrap this in a loop over a list of namespaces, count pods that are not Running, and print a summary. That is the core of half the “Kubernetes health check” scripts in production — and it is also a good interview exercise, because it tests the same judgement as the real thing.
Pattern 4 — Talk to AWS with boto3
Cloud automation in Python usually means boto3, AWS’s official SDK. It needs credentials — the same ones the AWS CLI uses, from ~/.aws/credentials or environment variables — and it turns API calls into ordinary Python:
import boto3
s3 = boto3.client("s3")
ec2 = boto3.client("ec2", region_name="us-east-1")
print("Buckets:")
for bucket in s3.list_buckets()["Buckets"]:
print(" -", bucket["Name"])
print("\nRunning instances:")
for reservation in ec2.describe_instances(
Filters=[{"Name": "instance-state-name", "Values": ["running"]}]
)["Reservations"]:
for instance in reservation["Instances"]:
print(" -", instance["InstanceId"], instance["InstanceType"])
Two things to learn from this example. First, boto3 has two interfaces — clients (low-level, one method per API call) and resources (higher-level, object-oriented). Clients are the better default for automation: they map directly onto the API documentation, and every example in the AWS docs uses them. Second, every call returns a dictionary — [“Buckets”], [“Reservations”] — so the skill is reading the API reference to know which keys exist, not memorising boto3 itself.
Real boto3 scripts are usually short and boring: list the resources that match a filter, do one thing to each, log what happened. That is the point — a 40-line script that terminates every EC2 instance tagged auto-shutdown: true after hours is worth more than a framework.
Pattern 5 — Put It Together: A Daily Report Script
The four patterns combine into the kind of script DevOps engineers actually keep: one that gathers information from several places and produces a single report. Here is the skeleton of a daily infrastructure report:
import logging
import requests
import yaml
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
def load_config(path="config.yaml"):
with open(path) as f:
return yaml.safe_load(f)
def check_service(service):
try:
response = requests.get(service["url"], timeout=service["timeout_seconds"])
response.raise_for_status()
return True, response.status_code
except requests.exceptions.RequestException as exc:
return False, str(exc)
def main():
config = load_config()
failures = []
for service in config["services"]:
ok, detail = check_service(service)
if ok:
logging.info("%s OK (%s)", service["name"], detail)
else:
logging.error("%s FAILED: %s", service["name"], detail)
failures.append(service["name"])
if failures:
logging.error("Failing services: %s — alert %s", ", ".join(failures), config["alert_email"])
raise SystemExit(1)
logging.info("All services healthy.")
if __name__ == "__main__":
main()
Note the structure: small functions, one job each; logging instead of print so output has timestamps and levels; a main() guarded by if __name__ == “__main__” so the file can be imported without running; and a non-zero exit code on failure so a scheduler can detect it. Run it from cron for a daily check, or from a GitHub Actions workflow on a schedule — the script does not care what calls it, which is exactly the property that makes it reusable.
Python or Bash — Which Script Gets Written?
The honest answer is both, for different jobs. Use Bash when the script is mostly calling other commands in sequence — our Bash Scripting tutorial covers that ground, and a ten-line shell script beats a fifty-line Python program that only shells out. Use Python when the script needs data structures, JSON or YAML parsing, API calls with error handling, or logic more complex than a loop and an if.
A useful rule: if you reach for jq, awk or nested quoting in Bash, rewrite it in Python. If your Python script is mostly subprocess.run calls with no data manipulation, rewrite it in Bash. The engineers who are fastest at automation are not the ones who know one language deeply — they are the ones who pick the right one in ten seconds.
FAQ
Which Python version should I use for DevOps scripts?
The latest stable — 3.15.2 as of November 2026. Anything still on 3.10 or older is past end of life and should be upgraded. For scripts that must run on servers you do not control, target the oldest Python you actually need to support, and say so in the README.
Do I need to learn Python to get a DevOps job?
Almost every DevOps job description lists Python or “a scripting language”. You do not need to be a software engineer, but you do need to write the five patterns in this tutorial comfortably — API calls, config files, subprocess, cloud SDKs and a scheduled script.
Is boto3 the only way to automate AWS from Python?
No — you can call the AWS APIs with plain HTTP requests, or use the AWS CLI from subprocess. boto3 is the standard choice because it handles authentication, retries and pagination for you.
How do I run a Python script on a schedule?
Cron on a server (crontab -e, then 0 9 * * * /path/to/venv/bin/python /path/to/script.py), a systemd timer, or a scheduled CI job. Always use the full path to the virtual environment’s Python, never the bare python3, so the script runs with the libraries you installed.
What about secrets — API keys and passwords in scripts?
Never hard-code them. Read them from environment variables (os.environ[“API_KEY”]), a secrets manager, or your cloud’s secret store. A key committed to Git is a compromised key, even in a private repository.
Conclusion
Python’s value in DevOps is not the language — it is the five patterns: call an API with a timeout, read config from a file, run a command and check its exit code, talk to a cloud SDK, and assemble those pieces into a script with logging and a meaningful exit code. Learn those and you can automate almost anything a DevOps role asks for, from a health check to a daily report to a cleanup job that saves the company money every night.
The next step is to make the scripts run themselves: put the report script in Git, run it from a schedule, and let it tell you when something breaks. That is the difference between a script and a system — and it is what the rest of this site’s automation tutorials are about.
Sources checked 28 Nov 2026: python.org (Python 3.15.2, 3.15.0 released 9 Oct 2026; 3.14 released 7 Oct 2025; 3.13 EOL Oct 2029; 3.12 EOL Oct 2028; 3.10 EOL 1 Oct 2026); PyPI (requests 2.34.2, boto3 1.44.12, paramiko 5.1.0, PyYAML 6.0.4); Python documentation (venv module). Code examples are original and follow the documented APIs. External references: Python venv documentation · boto3 documentation.
—


