APURV
  • Home
  • Journey
  • Projects
  • Blogs
  • Interview
  • Exams
Resume
APURV

Building scalable, secure, and production-ready cloud infrastructure. Automation first.

NAVIGATION

HomeExperienceProjectsCertificationsSkills

TECH STACK

AWSGCPK8sCI/CDLinuxDocker

CONNECT

LinkedInGitHubEmailResume

© 2026 Apurv Gujjar. All rights reserved.
Apurv Gujjar
Apurv GujjarDevOps & Cloud Engineer
|Interview Documentation
Portfolio
Handbooks
🎯Linux🐙Git & GitHub🤖GitHub Actions🌐Networking☁AWS🛠Terraform🐳Docker☸Kubernetes📊Monitoring🛡DevSecOps💰Cost Optimization🚨Incident Scenarios👤HR & Behavioral☁GCP🐍Python
Interview DocumentationPythonScenario 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.
Back to all Python questions
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 →
Q1

What is the difference between a List and a Tuple?

Q2

What is the difference between the `==` and `is` operators?

Q3

What are the primary Python data types?

Q4

What is a dictionary and why is it heavily used in DevOps?

Apurv Gujjar - DevOps & Cloud Engineer
Created by

Apurv Gujjar

DevOps & Cloud Engineer

Specialized in:DevOpsAWSGCPKubernetesTerraformDocker
View Portfolio