Loading earlier articles…

Python for DevOps Automation

Automate boring ops work with Python — file wrangling, API calls, and a real health-check script you can reuse.

9 min read

Why Python for DevOps?

Bash is great for one-liners, but the moment logic gets real — retries, JSON parsing, error handling — Python wins. Every major DevOps tool (Ansible, boto3, kubernetes-client) speaks Python.

A Real Health-Check Script

import sys
import requests

SERVICES = {
    "api": "https://api.example.com/health",
    "web": "https://example.com",
}

def check_service(name: str, url: str) -> bool:
    try:
        response = requests.get(url, timeout=5)
        healthy = response.status_code == 200
        status = "UP" if healthy else f"DOWN ({response.status_code})"
        print(f"[{status}] {name}: {url}")
        return healthy
    except requests.RequestException as error:
        print(f"[DOWN] {name}: {error}")
        return False

def main() -> None:
    results = [check_service(name, url) for name, url in SERVICES.items()]
    sys.exit(0 if all(results) else 1)

if __name__ == "__main__":
    main()

Exit code 1 on failure means this script plugs straight into cron, CI pipelines, or alerting.

Patterns You Will Reuse

  1. Timeouts always — a script that hangs is worse than one that fails
  2. Exit codes matter — automation chains on them
  3. Log to stdout — let the platform (systemd, Docker, CI) collect it

Practice Task

Extend the script to send a Slack/Discord webhook message when a service is down. You now have real monitoring — built by you.

Loading next article…