Coding & Scripting

Python for DevOps: Real-World Use Cases & Scripts

Updated March 2024 | 5 Practical Scripts

Do you need to be a software developer to work in DevOps? No. But do you need to know how to write scripts to automate boring tasks? Absolutely Yes.

Python is the most popular language for DevOps because it is easy to read (like English) and has powerful libraries to talk to AWS, Docker, and Linux.

Here are 5 Real-World Scenarios where a DevOps engineer uses Python, along with the actual code.


Use Case 1: The "Cleanup" Script

Scenario: Your server runs out of space every week because application logs keep piling up. You are tired of deleting them manually.

Solution: A Python script that finds files older than 30 days and deletes them automatically.

import os import time # Folder to clean folder_path = "/var/log/my-app" days = 30 seconds = time.time() - (days * 24 * 60 * 60) # Check every file in the folder for file in os.listdir(folder_path): file_path = os.path.join(folder_path, file) # If file is older than 30 days if os.stat(file_path).st_mtime < seconds: os.remove(file_path) print(f"Deleted old file: {file}")

Use Case 2: AWS Cost Saver (Boto3)

Scenario: Developers forget to turn off their testing servers (EC2 instances) on Friday evening. The company pays for the weekend usage for no reason.

Solution: A script using the Boto3 library to stop all "Dev" servers every Friday night.

import boto3 ec2 = boto3.resource('ec2', region_name='us-east-1') # Find all running instances with tag 'Environment: Dev' instances = ec2.instances.filter( Filters=[ {'Name': 'instance-state-name', 'Values': ['running']}, {'Name': 'tag:Environment', 'Values': ['Dev']} ] ) # Stop them for instance in instances: instance.stop() print(f"Stopped instance: {instance.id}")

Use Case 3: Website Health Monitor

Scenario: You want to know immediately if your company website goes down (returns a 500 error or 404).

Solution: A script that checks the website status code. If it's not 200 (OK), it sends you an email or prints an alert.

import requests url = "https://pixalara.com" try: response = requests.get(url) if response.status_code == 200: print("✅ Website is UP and running!") else: print(f"❌ Alert! Website returned {response.status_code}") # Add code here to send an email or Slack message except: print("❌ Website is completely unreachable!")

Use Case 4: Slack Notification Bot

Scenario: When a deployment finishes or a server crashes, you want the team to get a notification in your Slack channel.

Solution: Use a simple "Webhook" to send a message to Slack.

import requests import json webhook_url = "https://hooks.slack.com/services/YOUR/WEBHOOK/URL" message = {"text": "🚨 Alert: The Database Server CPU is at 99%!"} response = requests.post( webhook_url, data=json.dumps(message), headers={'Content-Type': 'application/json'} ) print("Message sent to Slack!")

Use Case 5: System Health Check

Scenario: Before installing a heavy application (like Kubernetes), you need to verify if the server has enough RAM and CPU.

Solution: A script using the psutil library to check system health.

import psutil # Check CPU cpu_usage = psutil.cpu_percent(interval=1) print(f"Current CPU Usage: {cpu_usage}%") # Check Memory (RAM) memory = psutil.virtual_memory() print(f"Total RAM: {memory.total / (1024**3):.2f} GB") print(f"Available RAM: {memory.available / (1024**3):.2f} GB") if memory.percent > 80: print("⚠️ Warning: Memory usage is dangerously high!")
Advice for Beginners: Don't try to memorize syntax. DevOps engineers Google things all the time. Focus on the logic: "I need to open a file, read lines, find the error, and print it."