15 DevOps Task Automations Using Python

15 Python automations for DevOps with code: Slack alerts, stale PRs, Prometheus reports, Terraform destroy guard, IAM key audit, Trivy gate and more.

Dec 30, 2025 - 12:27
Nov 10, 2026 - 15:09
 0  98
TOPICDevOps BasicsPractical guide
15 DevOps Task Automations Using Python

Python is best for DevOps tasks that call APIs, parse JSON or apply rules: posting pipeline alerts, reporting stale pull requests, querying Prometheus, guarding Terraform plans, auditing IAM keys and Kubernetes pods, gating builds on scan results and running commands across servers. The fifteen automations below each include working Python 3 code you can adapt.

This is the second of our Python automation guides. Top 10 Python scripts for DevOps automation covers EC2 scheduling, EBS cleanup, S3 backups, health and TLS checks, pod health, scaling, Docker cleanup, log analysis and YAML validation. None of those are repeated here. This post focuses on the glue between tools: Git hosting, chat, monitoring, Terraform, Ansible, security scanners and access audits. Library calls were checked against the official docs for Requests, boto3, the Kubernetes Python client, psutil, Fabric and dnspython in November 2026.

Key takeaways

  • Most of these scripts follow one pattern: read from an API or a JSON file, apply a rule, then report or fail with a non-zero exit code.
  • Exit codes are how a script talks to a pipeline. Return 1 when a check fails and the CI job stops on its own.
  • Read tokens from environment variables or a secrets manager. Never hard-code them.
  • Set a timeout on every HTTP call; Requests waits forever by default.
  • When a script starts managing long-lived infrastructure, move that logic to Terraform or Ansible.

The 15 automations at a glance

#AutomationMain libraryRuns from
1Pipeline result to SlackrequestsCI job
2Stale pull request reportrequests (GitHub REST API)Scheduled job
3Merged branch reportsubprocess + gitLaptop or CI
4Prometheus error-rate reportrequestsScheduled job
5Host resource checkpsutilCron on host
6Command across many serversFabricLaptop or bastion
7Terraform destroy guardjson + subprocessCI job
8Ansible dynamic inventory from EC2 tagsboto3Ansible
9Old IAM access key auditboto3Scheduled job
10DNS record verificationdnspythonCI or cron
11Kubernetes image policy auditkubernetes clientScheduled job
12Missing resource requests auditkubernetes clientScheduled job
13Trivy report gatejsonCI job
14Pre-commit secret pattern checkreGit hook
15Old log compression and cleanuppathlib + gzipCron on host

Setup that applies to every script

python3 -m venv .venv
source .venv/bin/activate
pip install requests boto3 kubernetes psutil fabric dnspython

Pin versions in a requirements.txt once a script goes into a pipeline. Give each script a dedicated identity with the least permission it needs: a read-only IAM role, a Kubernetes service account bound to a read-only ClusterRole, a fine-grained GitHub token limited to one repository.

1. Send a pipeline result to Slack

Slack incoming webhooks accept a JSON body with a text field. Store the webhook URL as a CI secret.

import os
import sys
import requests

def notify(status: str, job: str, url: str) -> None:
    webhook = os.environ["SLACK_WEBHOOK_URL"]
    icon = ":white_check_mark:" if status == "success" else ":x:"
    payload = {"text": f"{icon} {job} finished with status *{status}*\n{url}"}
    resp = requests.post(webhook, json=payload, timeout=10)
    resp.raise_for_status()

if __name__ == "__main__":
    notify(sys.argv[1], sys.argv[2], sys.argv[3])

Call it in a final pipeline step that runs whether earlier steps passed or failed, for example python notify.py failure build-api "$BUILD_URL". Microsoft Teams and Google Chat have similar webhook features with different payload formats.

2. Report stale pull requests on GitHub

Open pull requests that nobody has touched in a week slow everyone down. This script lists them using the GitHub REST API.

import os
from datetime import datetime, timedelta, timezone
import requests

OWNER, REPO = "my-org", "my-repo"
STALE_AFTER = timedelta(days=7)

headers = {
    "Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
    "Accept": "application/vnd.github+json",
    "X-GitHub-Api-Version": "2022-11-28",
}
url = f"https://api.github.com/repos/{OWNER}/{REPO}/pulls"
params = {"state": "open", "per_page": 100}
now = datetime.now(timezone.utc)

while url:
    resp = requests.get(url, headers=headers, params=params, timeout=15)
    resp.raise_for_status()
    for pr in resp.json():
        updated = datetime.fromisoformat(pr["updated_at"].replace("Z", "+00:00"))
        if now - updated > STALE_AFTER:
            age = (now - updated).days
            print(f"#{pr['number']} {age}d {pr['user']['login']}: {pr['title']} {pr['html_url']}")
    url = resp.links.get("next", {}).get("url")
    params = None  # the next link already carries the query

The loop follows the Link header so repositories with more than 100 open pull requests are covered. Pipe the output into script 1 to post a weekly digest. GitLab offers the same data through its merge requests API.

3. List branches already merged into main

import subprocess

PROTECTED = {"main", "master", "develop"}

def git(*args: str) -> str:
    return subprocess.run(["git", *args], check=True, capture_output=True, text=True).stdout

git("fetch", "--prune", "origin")
merged = git("branch", "-r", "--merged", "origin/main").split()
for ref in merged:
    name = ref.removeprefix("origin/")
    if name in PROTECTED or "->" in ref or name == "HEAD":
        continue
    print(name)

The script only prints. Review the list, then delete with git push origin --delete <branch> or enable automatic branch deletion on merge in your Git host. Squash-merged branches do not show up as merged because their commits differ from the squashed commit; the host's "delete branch on merge" setting handles those.

4. Daily error-rate report from Prometheus

The Prometheus HTTP API answers instant queries at /api/v1/query. This script reports the 24-hour 5xx ratio per service.

import os
import requests

PROM = os.environ.get("PROM_URL", "http://prometheus.monitoring.svc:9090")
QUERY = (
    'sum by (service) (increase(http_requests_total{code=~"5.."}[24h]))'
    ' / sum by (service) (increase(http_requests_total[24h]))'
)

resp = requests.get(f"{PROM}/api/v1/query", params={"query": QUERY}, timeout=30)
resp.raise_for_status()
body = resp.json()
if body["status"] != "success":
    raise SystemExit(f"query failed: {body}")

for series in sorted(body["data"]["result"], key=lambda s: float(s["value"][1]), reverse=True):
    service = series["metric"].get("service", "unknown")
    ratio = float(series["value"][1])
    flag = "  <-- above 1%" if ratio > 0.01 else ""
    print(f"{service:30} {ratio:.4%}{flag}")

Change the metric and label names to match what your services export. Each result's value is a pair of timestamp and value-as-string, which is why the code converts it with float(). For dashboards, use Grafana; this kind of script is for a text summary in chat or email. See using Prometheus and Grafana together.

5. Host resource check with psutil

import shutil
import sys
import psutil

LIMITS = {"cpu": 90.0, "memory": 90.0, "disk": 85.0}

usage = {
    "cpu": psutil.cpu_percent(interval=1),
    "memory": psutil.virtual_memory().percent,
    "disk": psutil.disk_usage("/").percent,
}
problems = [f"{k} {v:.1f}% (limit {LIMITS[k]}%)" for k, v in usage.items() if v > LIMITS[k]]

if problems:
    print("WARN: " + "; ".join(problems))
    sys.exit(1)
print("OK: " + ", ".join(f"{k} {v:.1f}%" for k, v in usage.items()))

Use this on hosts with no monitoring agent yet, or as a pre-flight check in a deploy job that refuses to proceed on a full disk. A host with a real monitoring stack should alert from node_exporter instead.

6. Run a command across many servers with Fabric

Fabric wraps Paramiko and runs SSH commands in parallel.

from fabric import ThreadingGroup
from fabric.exceptions import GroupException

hosts = ["web1.internal", "web2.internal", "web3.internal"]
group = ThreadingGroup(*hosts, user="deploy")

try:
    results = group.run("uptime && df -h / | tail -1", hide=True)
except GroupException as exc:
    results = exc.result  # still contains the hosts that succeeded

for conn, result in results.items():
    if isinstance(result, Exception):
        print(f"{conn.host}: FAILED {result}")
    else:
        print(f"{conn.host}: {result.stdout.strip()}")

Fabric is good for ad hoc read-only checks. For changes you want repeatable and idempotent, write an Ansible playbook instead; see our guide to automating server configuration with Ansible playbooks.

7. Block Terraform plans that destroy resources

terraform show -json turns a saved plan into JSON. Each entry in resource_changes has a list of actions; a replace appears as ["delete", "create"] or ["create", "delete"].

import json
import subprocess
import sys

plan = json.loads(subprocess.run(
    ["terraform", "show", "-json", "tfplan"],
    check=True, capture_output=True, text=True,
).stdout)

destructive = [
    (rc["address"], "/".join(rc["change"]["actions"]))
    for rc in plan.get("resource_changes", [])
    if "delete" in rc["change"]["actions"]
]

if destructive:
    print("Plan deletes or replaces resources:")
    for address, actions in destructive:
        print(f"  {address}: {actions}")
    sys.exit(1)
print("No destructive changes.")

Run it after terraform plan -out=tfplan. A failing exit makes the pipeline require a human approval stage before apply. The JSON format is described in the Terraform JSON output format docs.

8. Ansible dynamic inventory from EC2 tags

The supported route is the amazon.aws.aws_ec2 inventory plugin. A small script is still useful when you need custom grouping logic. Ansible calls inventory scripts with --list and expects JSON with groups and a _meta.hostvars block.

#!/usr/bin/env python3
import json
import sys
import boto3

def build() -> dict:
    ec2 = boto3.client("ec2")
    inv = {"_meta": {"hostvars": {}}}
    pages = ec2.get_paginator("describe_instances").paginate(
        Filters=[{"Name": "instance-state-name", "Values": ["running"]},
                 {"Name": "tag-key", "Values": ["Role"]}]
    )
    for page in pages:
        for res in page["Reservations"]:
            for inst in res["Instances"]:
                tags = {t["Key"]: t["Value"] for t in inst.get("Tags", [])}
                ip = inst.get("PrivateIpAddress")
                if not ip:
                    continue
                group = tags["Role"]
                inv.setdefault(group, {"hosts": []})["hosts"].append(ip)
                inv["_meta"]["hostvars"][ip] = {"instance_id": inst["InstanceId"],
                                                "env": tags.get("Env", "unknown")}
    return inv

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "--host":
        print(json.dumps({}))
    else:
        print(json.dumps(build(), indent=2))

Make it executable and run ansible-inventory -i ec2_inventory.py --graph to check the groups. Returning everything under _meta lets Ansible skip calling --host for each machine.

9. Audit IAM access keys older than 90 days

from datetime import datetime, timezone
import boto3

MAX_AGE_DAYS = 90
iam = boto3.client("iam")
now = datetime.now(timezone.utc)

for page in iam.get_paginator("list_users").paginate():
    for user in page["Users"]:
        keys = iam.list_access_keys(UserName=user["UserName"])["AccessKeyMetadata"]
        for key in keys:
            age = (now - key["CreateDate"]).days
            if key["Status"] == "Active" and age > MAX_AGE_DAYS:
                print(f"{user['UserName']}: {key['AccessKeyId']} active for {age} days")

The script needs iam:ListUsers and iam:ListAccessKeys. It reports and does not disable keys. The longer-term fix is fewer static keys: IAM Identity Center for people and roles for workloads. AWS also produces a credential report that includes key age.

10. Verify DNS records after a change

import sys
import dns.resolver

EXPECTED = {
    ("api.example.com", "A"): {"203.0.113.10", "203.0.113.11"},
    ("example.com", "MX"): {"10 mail.example.com."},
}

failed = False
for (name, rtype), want in EXPECTED.items():
    try:
        got = {r.to_text() for r in dns.resolver.resolve(name, rtype)}
    except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer) as exc:
        got = set()
        print(f"{name} {rtype}: {exc.__class__.__name__}")
    if got != want:
        failed = True
        print(f"MISMATCH {name} {rtype}: want {sorted(want)} got {sorted(got)}")
sys.exit(1 if failed else 0)

Run it after a DNS change to confirm the records your resolver sees, keeping TTLs in mind. The addresses above are from the documentation range in RFC 5737; replace them with yours.

11. Find pods that break your image policy

This audit flags containers using the latest tag, no tag at all, or a registry outside your approved list.

from kubernetes import client, config

APPROVED = ("registry.example.com/", "public.ecr.aws/")

config.load_kube_config()  # use config.load_incluster_config() inside a pod
v1 = client.CoreV1Api()

for pod in v1.list_pod_for_all_namespaces().items:
    for c in pod.spec.containers + (pod.spec.init_containers or []):
        image = c.image
        last = image.rsplit("/", 1)[-1]
        untagged = ":" not in last and "@" not in last
        reasons = []
        if untagged or last.endswith(":latest"):
            reasons.append("latest/untagged")
        if not image.startswith(APPROVED):
            reasons.append("unapproved registry")
        if reasons:
            print(f"{pod.metadata.namespace}/{pod.metadata.name} {c.name} {image}: {', '.join(reasons)}")

An audit script tells you what already runs. To block new violations, use an admission policy such as Kubernetes ValidatingAdmissionPolicy, Kyverno or OPA Gatekeeper.

12. Find containers without resource requests

from kubernetes import client, config

config.load_kube_config()
v1 = client.CoreV1Api()
SKIP = {"kube-system"}

for pod in v1.list_pod_for_all_namespaces().items:
    if pod.metadata.namespace in SKIP:
        continue
    for c in pod.spec.containers:
        requests_ = (c.resources.requests or {}) if c.resources else {}
        missing = [r for r in ("cpu", "memory") if r not in requests_]
        if missing:
            print(f"{pod.metadata.namespace}/{pod.metadata.name}/{c.name} missing requests: {missing}")

Pods without requests get the BestEffort QoS class when they also lack limits, and they are the first evicted when a node runs short of memory. The scheduler also cannot place them well. A LimitRange per namespace can set defaults so this list stays short.

13. Fail a build on critical Trivy findings

Trivy can fail by itself with --exit-code 1 --severity CRITICAL. A script helps when you need custom rules, such as ignoring findings with no fix available, or a readable summary.

trivy image --format json --output trivy.json registry.example.com/orders-api:7b41d0e
import json
import sys

report = json.load(open("trivy.json"))
blocking = []
for result in report.get("Results", []):
    for v in result.get("Vulnerabilities") or []:
        if v["Severity"] == "CRITICAL" and v.get("FixedVersion"):
            blocking.append(f"{v['VulnerabilityID']} {v['PkgName']} "
                            f"{v['InstalledVersion']} -> {v['FixedVersion']}")

if blocking:
    print(f"{len(blocking)} fixable critical vulnerabilities:")
    print("\n".join(blocking))
    sys.exit(1)
print("No fixable critical vulnerabilities.")

Agree the policy with your security team and write it down. A gate that fails every build gets switched off.

14. Pre-commit check for obvious secrets

#!/usr/bin/env python3
import re
import subprocess
import sys

PATTERNS = {
    "AWS access key ID": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
    "Private key block": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
    "GitHub token": re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b"),
}

staged = subprocess.run(["git", "diff", "--cached", "--name-only", "--diff-filter=ACM"],
                        capture_output=True, text=True, check=True).stdout.split()
hits = []
for path in staged:
    try:
        text = open(path, encoding="utf-8", errors="ignore").read()
    except OSError:
        continue
    for label, pattern in PATTERNS.items():
        if pattern.search(text):
            hits.append(f"{path}: possible {label}")

if hits:
    print("\n".join(hits))
    print("Commit blocked. Remove the secret, or rotate it if it was ever pushed.")
    sys.exit(1)

Save it as .git/hooks/pre-commit and make it executable. This is a teaching example with three patterns. For real use, adopt a maintained scanner such as Gitleaks or your Git host's push protection, which ship hundreds of tested rules.

15. Compress and clean old logs

import gzip
import shutil
import time
from pathlib import Path

LOG_DIR = Path("/var/log/myapp")
COMPRESS_AFTER = 1 * 86400
DELETE_AFTER = 30 * 86400
now = time.time()

for path in LOG_DIR.glob("*.log.*"):
    age = now - path.stat().st_mtime
    if path.suffix == ".gz":
        if age > DELETE_AFTER:
            path.unlink()
            print(f"deleted {path}")
    elif age > COMPRESS_AFTER:
        with path.open("rb") as src, gzip.open(f"{path}.gz", "wb") as dst:
            shutil.copyfileobj(src, dst)
        path.unlink()
        print(f"compressed {path}")

On most Linux servers, logrotate already does this and is the better choice. Use a script when an application writes logs somewhere logrotate is not configured, or inside a container image that has no logrotate.

Running these safely

HabitWhy
Report first, act laterEvery script above prints findings. Add an --apply flag before letting one change anything.
Non-zero exit on failureLets CI and cron monitoring notice problems.
Timeouts and retriesA hung API call should not hang the pipeline.
Structured loggingUse the logging module, or JSON lines, once a script runs unattended.
Least privilegeA read-only role cannot delete production by accident.
Version control and reviewScripts are code. Keep them in Git with tests for the parsing logic.

Where to go next

If you want to practise for interviews with these libraries, try the scenario-based Python interview questions and the Python coding and scripting questions. For containerising a script as a CronJob, see 12 Dockerfile examples. Python automation is part of our DevOps training in Pune, delivered in Kharadi and live online.

Frequently asked questions

What can I automate with Python in DevOps?

Anything that involves an API or structured data: chat notifications, Git host reports, monitoring queries, Terraform plan checks, inventory generation, access audits, Kubernetes audits, security gates and log housekeeping.

Should I use Python or Bash for DevOps scripts?

Use Bash for short sequences of shell commands. Use Python when you parse JSON, call REST APIs, need error handling, or the script is growing past a few dozen lines.

How do I stop a Python script from failing a CI pipeline silently?

Exit with a non-zero code when a check fails, using sys.exit(1) or raise SystemExit. CI systems treat any non-zero exit as a failed step.

Is Fabric or Ansible better for running commands on servers?

Fabric suits quick, ad hoc commands from Python. Ansible suits repeatable configuration because its modules are idempotent and its playbooks are easier for a team to review.

How do Python scripts authenticate to AWS safely?

Use boto3's default credential chain with an IAM role: an instance profile, a task or pod role, or OIDC federation from CI. Avoid long-lived access keys in files or variables.

Can I replace Trivy's built-in exit code with a Python script?

You can, but only do it when you need custom rules such as ignoring unfixed findings. For a simple severity threshold, Trivy's --exit-code and --severity flags are enough.

Where should these scripts run?

Checks that gate a change belong in CI. Periodic reports fit a scheduled pipeline or a Kubernetes CronJob. Host-level checks can run from cron on the host.

References

Interested in learning more?Get a callback from our training advisors.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.