python (boto3) program to delete old snapshots in aws

10,903

Solution 1

I've solved it myself. here is the code:

    import boto3
    import datetime
    client = boto3.client('ec2',region_name='us-west-1')
    snapshots = client.describe_snapshots(OwnerIds=['12345678'])
    for snapshot in snapshots['Snapshots']:
       a= snapshot['StartTime']
       b=a.date()
       c=datetime.datetime.now().date()
       d=c-b
       try:
        if d.days>10:
           id = snapshot['SnapshotId']
           client.delete_snapshot(SnapshotId=id)
       except Exception,e:
        if 'InvalidSnapshot.InUse' in e.message:
           print "skipping this snapshot"
           continue

Solution 2

Thanks Vishal, exactly what I needed to get started. I made a few tweaks due to compliance requirements. I added an exception to keep all backups with a StartTime date of the 1st of the month. I also added an exception to keep my oldest snapshot set.

import boto3
import datetime
client = boto3.client('ec2',region_name='us-west-1')
snapshots = client.describe_snapshots(OwnerIds=['111111111111'])

def lambda_handler(event, context):
    for snapshot in snapshots['Snapshots']:
        a=snapshot['StartTime']
        b=a.date()
        c=datetime.datetime.now().date()
        d=c-b
        f=a.day
        excludeDate=datetime.datetime.strptime('2018-1-10', '%Y-%m-%d').date()
        try:
            if d.days>30 and f!=1 and b!=excludeDate:
                id = snapshot['SnapshotId']
                client.delete_snapshot(SnapshotId=id)
        except Exception,e:
            if 'InvalidSnapshot.InUse' in e.message:
                print "skipping this snapshot"
                continue
Share:
10,903
vishal
Author by

vishal

Updated on June 18, 2022

Comments

  • vishal
    vishal almost 2 years

    I have already written a program to delete old snapshots.But the problem for me now is if the snapshot is attached with an ami then it doesn't get deleted and the program also stops.It displays the following message :

    botocore.exceptions.ClientError: An error occurred (InvalidSnapshot.InUse) when calling the DeleteSnapshot operation: The snapshot snap-12345678 is currently in use by ami-12345

    I want the program to skip those snapshots alone and continue to delete other snapshots. here is my code below:

    import boto3
    import datetime
    client = boto3.client('ec2',region_name='us-west-1')
    snapshots = client.describe_snapshots(OwnerIds=['12345678'])
    for snapshot in snapshots['Snapshots']:
        a= snapshot['StartTime']
        b=a.date()
        c=datetime.datetime.now().date()
        d=c-b
        if d.days>10:
            id = snapshot['SnapshotId']
            client.delete_snapshot(SnapshotId=id)