Q6
Scenario 6: Write a script that creates timestamped daily backups, uploads them to AWS S3, and automatically purges old backups from the bucket that are older than 30 days.
💬Answer
import os
import shutil
import boto3
from datetime import datetime, timezone, timedelta
# Config
BACKUP_DIR = "/opt/app/data"
S3_BUCKET = "my-company-backups"
date_suffix = datetime.now().strftime("%Y_%m_%d")
archive_name = f"/tmp/backup_{date_suffix}"
# 1. Create timestamped backup
archive_file = shutil.make_archive(archive_name, 'zip', BACKUP_DIR)
s3_key = os.path.basename(archive_file)
# Initialize AWS clients
s3 = boto3.client("s3")
s3_res = boto3.resource("s3")
try:
# 2. Upload to S3
s3.upload_file(archive_file, S3_BUCKET, s3_key)
print(f"Uploaded {s3_key} to S3 bucket.")
os.remove(archive_file) # Remove local copy
# 3. Purge objects older than 30 days
bucket = s3_res.Bucket(S3_BUCKET)
now_utc = datetime.now(timezone.utc)
expiration_limit = now_utc - timedelta(days=30)
for obj in bucket.objects.all():
if obj.last_modified < expiration_limit:
print(f"Purging expired backup object: {obj.key} (Modified: {obj.last_modified})")
obj.delete()
except Exception as e:
print(f"Backup operation failed: {e}")
Related Python Questions
View All PythonQuestions →
Created by
Apurv Gujjar
DevOps & Cloud Engineer
Specialized in:DevOpsAWSGCPKubernetesTerraformDocker
View Portfolio