← Back to list

11 Python Automation Scripts Every DevOps Engineer Should Build

best DevOps engineers are not the ones manually clicking dashboards all day

Obafemi · 2026-05-25 14:51 · 13 claps · 4.7 min read paywalled
#python-automation-script #python-automation #sre #devops #python
Open on Medium ↗
Wiki topics: ☁️ · DevOps & Cloud 🎬 · Film & Television

11 Python Automation Scripts Every DevOps Engineer Should Build

best DevOps engineers are not the ones manually clicking dashboards all day

It’s possible to waste hours every week on operational tasks that should already be automated like:

  • cloud infrastructure
  • CI/CD pipelines
  • observability
  • platform engineering
  • incident response
  • internal tooling

Bash is excellent for quick terminal tasks but when automation grows larger, Python gives you:

  • better error handling
  • reusable code
  • cloud SDKs and APIs
  • concurrency
  • structured logging
  • maintainable tooling

Prerequisites

Install dependencies:

pip install boto3 kubernetes requests psutil colorama rich tenacity

You’ll also need:

  • Python 3.10+
  • AWS credentials configured
  • kubectl access configured
  • Terraform installed
  • Docker installed

1. Multi-Region EC2 Inventory Exporter

One of the first useful tools many infrastructure teams build is a cloud inventory exporter.

As environments grow, engineers lose visibility into:

  • running instances
  • instance types
  • public exposure
  • unused infrastructure
  • aging workloads

This script collects EC2 metadata across regions and exports it into JSON.

Script

import boto3
import json
from datetime import datetime

regions = ["us-east-1", "us-west-2"]

inventory = []

for region in regions:

    ec2 = boto3.client("ec2", region_name=region)

    paginator = ec2.get_paginator("describe_instances")

    for page in paginator.paginate():

        for reservation in page["Reservations"]:

            for instance in reservation["Instances"]:

                inventory.append({
                    "region": region,
                    "instance_id": instance["InstanceId"],
                    "type": instance["InstanceType"],
                    "state": instance["State"]["Name"],
                    "private_ip": instance.get("PrivateIpAddress"),
                    "public_ip": instance.get("PublicIpAddress"),
                    "launch_time": str(instance["LaunchTime"])
                })

filename = f"ec2_inventory_{datetime.utcnow().date()}.json"

with open(filename, "w") as f:
    json.dump(inventory, f, indent=2)

print(f"Exported {len(inventory)} instances")

This becomes useful for:

  • security audits
  • migration planning
  • CMDB generation
  • patch tracking
  • cost analysis
  • compliance reporting

2. AWS SSM Fleet Health Checker

Newer AWS environments increasingly use:

  • AWS Systems Manager
  • IAM-based access
  • agent-based fleet management
  • immutable infrastructure

This script checks whether EC2 instances are online in AWS SSM.

Script

import boto3

ssm = boto3.client("ssm")

response = ssm.describe_instance_information()

for instance in response["InstanceInformationList"]:

    print(
        f"{instance['InstanceId']} | "
        f"Ping: {instance['PingStatus']} | "
        f"Platform: {instance['PlatformType']}"
    )

It’s useful for:

  • fleet visibility
  • outage investigation
  • patch validation
  • compliance audits
  • operational dashboards

3. Safe Docker Disk Cleanup Tool

Containers consume disk space quickly but aggressive cleanup commands can destroy:

  • build cache
  • CI performance
  • running workloads

This script performs safer cleanup with visibility first.

Script

import subprocess

print("Checking Docker disk usage...\n")

usage = subprocess.run(
    ["docker", "system", "df"],
    capture_output=True,
    text=True
)

print(usage.stdout)

confirm = input("Run safe cleanup of unused containers? (y/n): ")

if confirm.lower() == "y":

    cleanup = subprocess.run(
        ["docker", "container", "prune", "-f"],
        capture_output=True,
        text=True
    )

    print(cleanup.stdout)

else:
    print("Cleanup skipped")

Instead of just deleting everything, this:

  • shows current usage first
  • avoids image cache destruction
  • adds operator confirmation
  • reduces accidental CI slowdowns

4. Kubernetes Rollout Restart Automation

Sometimes applications become unhealthy because of:

  • memory leaks
  • stale connections
  • failed sidecars
  • broken deployments

Blindly deleting pods is risky so a safer approach is restarting the deployment itself.

Script

from kubernetes import client, config

config.load_kube_config()

apps = client.AppsV1Api()

namespace = "default"
deployment_name = "myapp"

apps.patch_namespaced_deployment(
    name=deployment_name,
    namespace=namespace,
    body={
        "spec": {
            "template": {
                "metadata": {
                    "annotations": {
                        "restart-trigger": "true"
                    }
                }
            }
        }
    }
)

print(f"Restart triggered for {deployment_name}")

This method:

  • respects deployment strategies
  • preserves rolling updates
  • avoids mass pod deletion
  • works with readiness probes
  • reduces outage risk

5. Structured Log Alert Monitor

Because logs are one of the fastest ways to detect operational problems, it’s very important to monitor them.

This script monitors logs and raises alerts for critical events.

Unlike simple keyword scanners, this version supports:

  • regex matching
  • structured alerts
  • rate limiting

Script

import time
import re

LOG_FILE = "/var/log/nginx/error.log"

PATTERNS = [
    r"critical",
    r"connection refused",
    r"segmentation fault"
]

last_alert = 0

with open(LOG_FILE, "r") as file:

    file.seek(0, 2)

    while True:

        line = file.readline()

        if not line:
            time.sleep(1)
            continue

        for pattern in PATTERNS:

            if re.search(pattern, line, re.IGNORECASE):

                current = time.time()

                if current - last_alert > 30:

                    print(f"ALERT: {line.strip()}")

                    last_alert = current

Even with centralized logging platforms, lightweight monitors are useful for:

  • edge systems
  • temporary diagnostics
  • isolated environments
  • internal tooling

6. Terraform Drift Detection Reporter

Infrastructure drift happens when real cloud infrastructure no longer matches Terraform state.

This causes:

  • compliance issues
  • unexpected outages
  • inconsistent deployments

This script safely reports drift results.

Script

import subprocess

result = subprocess.run(
    [
        "terraform",
        "plan",
        "-detailed-exitcode",
        "-lock=false"
    ],
    capture_output=True,
    text=True
)

if result.returncode == 0:

    print("No infrastructure drift detected")

elif result.returncode == 2:

    print("Drift detected\n")

    print(result.stdout)

else:

    print("Terraform execution error")

    print(result.stderr)

Terraform drift detection is useful, but it can produce noise.

It’s safer to combine drift detection with:

  • approval workflows
  • GitOps policies
  • ignored attribute rules
  • scheduled reporting

7. SSL Certificate Expiration Scanner

Expired TLS certificates still cause major outages.

This script scans domains and warns before expiration.

Script

import socket
import ssl
from datetime import datetime

domains = [
    "google.com",
    "github.com"
]

context = ssl.create_default_context()

for hostname in domains:

    try:

        with socket.create_connection((hostname, 443)) as sock:

            with context.wrap_socket(
                sock,
                server_hostname=hostname
            ) as ssock:

                cert = ssock.getpeercert()

                expires = cert["notAfter"]

                expiry_date = datetime.strptime(
                    expires,
                    "%b %d %H:%M:%S %Y %Z"
                )

                days_left = (
                    expiry_date - datetime.utcnow()
                ).days

                print(
                    f"{hostname} expires in "
                    f"{days_left} days"
                )

    except Exception as e:

        print(f"{hostname}: {e}")

Useful for:

  • internal domains
  • vendor endpoints
  • compliance checks
  • monitoring gaps
  • custom infrastructure

8. GitHub Actions Workflow Trigger

DevOps these days relies heavily on API-driven CI/CD.

This script triggers GitHub Actions workflows programmatically.

Script

import os
import requests

TOKEN = os.getenv("GITHUB_TOKEN")

OWNER = "your-org"
REPO = "your-repo"
WORKFLOW = "deploy.yml"

url = (
    f"https://api.github.com/repos/"
    f"{OWNER}/{REPO}/actions/workflows/"
    f"{WORKFLOW}/dispatches"
)

headers = {
    "Authorization": f"Bearer {TOKEN}",
    "Accept": "application/vnd.github+json"
}

payload = {
    "ref": "main"
}

response = requests.post(
    url,
    json=payload,
    headers=headers,
    timeout=10
)

if response.status_code == 204:

    print("Workflow triggered successfully")

else:

    print(response.text)

This enables:

  • ChatOps
  • deployment orchestration
  • self-healing systems
  • automated rollback pipelines
  • incident remediation

9. Disk Usage and Filesystem Analyzer

Disk exhaustion remains one of the most common production incidents.

This script analyzes filesystem usage and highlights risky partitions.

Script

import psutil

THRESHOLD = 80

partitions = psutil.disk_partitions()

for partition in partitions:

    try:

        usage = psutil.disk_usage(partition.mountpoint)

        print(
            f"{partition.mountpoint} | "
            f"{usage.percent}% used"
        )

        if usage.percent > THRESHOLD:

            print(
                f"WARNING: "
                f"{partition.mountpoint} exceeds threshold"
            )

    except PermissionError:
        continue

This provides better visibility than checking only /.

It helps detect:

  • runaway logs
  • full container volumes
  • exhausted mounted disks
  • storage hotspots

10. Backup Restore Verification Tool

If a backup can’t be restored then it’s not exactly useful.

This script validates backup integrity using checksums.

Script

import hashlib
import os

BACKUP_FILE = "/backups/app-backup.tar.gz"

EXPECTED_HASH = "your_expected_sha256_hash"

sha256 = hashlib.sha256()

with open(BACKUP_FILE, "rb") as f:

    while chunk := f.read(8192):

        sha256.update(chunk)

calculated_hash = sha256.hexdigest()

if calculated_hash == EXPECTED_HASH:

    print("Backup integrity verified")

else:

    print("Backup verification failed")

Actual backup verification should eventually include:

  • automated restore testing
  • database consistency checks
  • disaster recovery drills
  • point-in-time recovery testing

But checksum validation is a much safer starting point than checking file size.

11. Cloud Cost Reporting Script

Because cloud costs become difficult to manage as infrastructure grows, this script pulls AWS cost data automatically.

Script

import boto3

ce = boto3.client("ce")

response = ce.get_cost_and_usage(
    TimePeriod={
        "Start": "2026-05-01",
        "End": "2026-05-25"
    },
    Granularity="MONTHLY",
    Metrics=["UnblendedCost"]
)

amount = response["ResultsByTime"][0]["Total"][
    "UnblendedCost"
]["Amount"]

print(f"AWS spend this month: ${amount}")

Cost visibility is now a core DevOps responsibility.

This helps with:

  • budget alerts
  • FinOps reporting
  • environment tracking
  • engineering accountability

[embed]11 Key Linux Performance Tuning Tricks for DevOps Engineers improve application speed, resource usage, and system stability.medium.com

[embed]SSH Setup Every DevOps Engineer Needs once you experience a clean SSH setup, it’s very hard to go backmedium.com

No need spending hours setting up CICD pipelines from scratch, just get production level, ready-to-deploy pipelines from the Production Pipeline Pack. Check it out 👉 CICD


메타데이터
post_id
bc11defd323e
slug
11-python-automation-scripts-every-devops-engineer-should-build-bc11defd323e
url
https://medium.com/@obaff/11-python-automation-scripts-every-devops-engineer-should-build-bc11defd323e
canonical_url
https://medium.com/@obaff/11-python-automation-scripts-every-devops-engineer-should-build-bc11defd323e
author_url
https://medium.com/@obaff
status
ok
fetched_at
2026-06-10 08:17:25