Practical Automation Scripts
Let's look at how to implement common DevOps patterns in Python.
1. System Health Monitoring
A script to check if disk usage exceeds a threshold.
import shutil
def check_disk_usage(disk, threshold):
total, used, free = shutil.disk_usage(disk)
percent_used = (used / total) * 100
if percent_used > threshold:
print(f"⚠️ WARNING: Disk usage on {disk} is at {percent_used:.2f}%")
else:
print(f"âś… Disk healthy: {percent_used:.2f}% used")
check_disk_usage("/", 80)2. Interacting with REST APIs
Using the requests library to fetch data and format JSON.
import requests
import json
def fetch_user_data(user_id):
url = f"https://jsonplaceholder.typicode.com/users/{user_id}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(f"Name: {data['name']}")
print(f"Email: {data['email']}")
# Pretty printing JSON
print(json.dumps(data, indent=4))
else:
print(f"Error: {response.status_code}")
fetch_user_data(1)3. File Cleanup Automation
Deleting files older than a certain number of days (simulated here for safety).
import os
import time
def cleanup_logs(directory, days):
seconds = days * 24 * 60 * 60
current_time = time.time()
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
file_age = os.path.getmtime(filepath)
if (current_time - file_age) > seconds:
print(f"Deleting old file: {filename}")
# os.remove(filepath) # Commented for safety
# cleanup_logs("/var/log/myapp", 7)4. Advanced: JSON to Table
Converting complex nested dictionaries into a readable format.
data = [
{"Host": "Web-01", "IP": "10.0.0.1", "Status": "Healthy"},
{"Host": "DB-01", "IP": "10.0.0.5", "Status": "Critical"}
]
print(f"{'HOST':<10} {'IP':<12} {'STATUS'}")
print("-" * 35)
for item in data:
print(f"{item['Host']:<10} {item['IP']:<12} {item['Status']}")[!IMPORTANT] Dry Run! When writing scripts that delete or modify production data, always implement a "dry run" mode (usually a
--dry-runflag) that prints what would happen without actually doing it.