backup-instance-volume / index.py
index.py
Raw
import boto3
from operator import itemgetter
import schedule
import time

client = boto3.client('ec2')

# Define function to create backup
def create_backup():
    volume_response = client.describe_volumes(
        Filters=[
            {
                'Name': 'tag:Environment',
                'Values': [
                    'Production',
                ]
            },
        ]
    )
    volumes = volume_response["Volumes"]
    volume_ids_list = []
    for volume in volumes:
        volume_ids_list.append(volume["Attachments"]["VolumeId"])
    for id in volume_ids_list:
        snapshot = client.create_snapshot(
            VolumeId=id
        ) 

# Delete old backups
def delete_old_backups():
    snapshot_response = client.describe_snapshots(
        OwnerIds=[
            'self',
        ]
    )
    snapshots = snapshot_response["Snapshots"] 
    sorted_snapshots = sorted(snapshots, key=itemgetter('StartTime'), reverse=True)
    # Remove recent snapshots from the list of sorted snapshots 
    sorted_snapshots.pop(0)
    sorted_snapshots.pop(1)
    for snapshot in sorted_snapshots:
        delete_snapshot_response = client.delete_snapshot(
            SnapshotId=snapshot["SnapshotId"]
        )

# Define interval for backup creation
schedule.every().day.at("00:00").do(
    create_backup
)

# Define interval for deletion of backups
schedule.every().friday.at("00:00").do(
    delete_old_backups
)

while True:
    schedule.run_pending()
    time.sleep(1)