Q1
Scenario 1: Write a script that checks disk usage. If usage is > 90%, compress old logs and upload them to AWS S3.
💬Answer
import os
import shutil
import boto3
from datetime import datetime
# Configurations
THRESHOLD = 90.0
LOG_DIR = "/var/log/app"
BACKUP_FILE = f"/tmp/logs_backup_{datetime.now().strftime('%Y%m%d')}"
S3_BUCKET = "devops-incident-backups"
# 1. Check disk usage
total, used, free = shutil.disk_usage("/")
percent_used = (used / total) * 100
if percent_used > THRESHOLD:
print(f"Disk alert: {percent_used:.2f}% used! Commencing cleanup...")
# 2. Compress log directory
if os.path.exists(LOG_DIR):
archive_path = shutil.make_archive(BACKUP_FILE, 'gztar', LOG_DIR)
print(f"Logs compressed to: {archive_path}")
# 3. Upload to S3
s3 = boto3.client("s3")
try:
s3.upload_file(archive_path, S3_BUCKET, os.path.basename(archive_path))
print("Compressed archive uploaded to S3 successfully.")
# 4. Cleanup old logs (Optional / Safe truncation)
for file in os.listdir(LOG_DIR):
file_path = os.path.join(LOG_DIR, file)
if os.path.isfile(file_path):
open(file_path, 'w').close() # Truncate content keeping file descriptors open
# Remove temporary archive
os.remove(archive_path)
except Exception as e:
print(f"Backup upload failed: {e}")
Related Python Questions
View All PythonQuestions →
Created by
Apurv Gujjar
DevOps & Cloud Engineer
Specialized in:DevOpsAWSGCPKubernetesTerraformDocker
View Portfolio