Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python (boto3) program to delete old snapshots in aws

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)
like image 784
vishal Avatar asked Jan 06 '18 04:01

vishal


2 Answers

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
like image 135
vishal Avatar answered Sep 20 '22 02:09

vishal


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
like image 34
David Saelee Avatar answered Sep 18 '22 02:09

David Saelee