Continuing with Boto : Delete EBS snapshot which is 30 days older

31 / Mar / 2015 by Vikash Jha 0 comments

In continuation with my previous blog “Getting Started with Boto ( python Interface for AWS )”,  today we are going to discuss one of the use case that we used to do daily.

Deleting EBS Snapshot which is N days older.


We’ll be writing python script using Boto library to delete EBS snapshots which is 30 days older. For this we will be using three different python modules.

1) boto
2) datetime
3) dateutil

We have already discussed boto module in our previous article.
datetime
datetime module contains classes and methods for manipulating dates and times. e.g
[Python]

  >>> import datetime
  >>>datetime.datetime.now()
   datetime.datetime(2015, 3, 31, 22, 11, 22, 512228)
 
Output : (Year,Month,Day,Minutes,Hour,Seconds)

Now we have to find the date which is 30 days old with respect to current date. For that we will use timedelta objects comes with datetime class.


  >>>import datetime
  >>>datetime.datetime.now() - datetime.timedelta(days=30)
  datetime.datetime(2015, 3, 1, 22, 21, 49, 741196)

As you can see we got the day 1 March 2015 which is 30 days behind from Current Date.

dateutil

Now, we can compare EBS Snapshot Creation time with this time, If ebsSnapshotId.start_time < 30 days we’ll delete the snapshots. For that we have to use another python module dateutil.parser which helps us in extracting date from EBS Start time.

EBS start_time uses 2012-10-09T12:27:30.000Z  format to describe Creation Time for snaphots. We have to extract the date from this. We can achieve this by following snippets.

>>> import dateutil
>>> from dateutil import parser
>>> parser.parse(snapshotID.start_time).date()
datetime.date(2012, 10, 9)

Now we have the current date , 30 days old date and EBS Snapshot Creation Time. So our complete scripts ” To delete snapshot which is 30 days Old ”


import boto 
import datetime
import dateutil
from dateutil import parser
from boto import ec2

connection=ec2.connect_to_region("REGION-NAME")

ebsAllSnapshots=connection.get_all_snapshots(owner='16-DIGIT-AWS-ACCOUNT-NUMBER')

#Get the 30 days old date
timeLimit=datetime.datetime.now() - datetime.timedelta(days=30)  

for snapshot in ebsAllSnapshots:
    
    if parser.parse(snapshot.start_time).date() <= timeLimit.date():
        print " Deleting Snapshot %s  %s "  %(snapshot.id,snapshot.tags)
        connection.delete_snapshot(snapshot.id) 
    else:
        # this section will have all snapshots which is created before 30 days
        print "Only Deleting Snapshots which is 30 days old" 


Note : Please make sure you perform testing before executing this script.


Leave a comment if you have any questions regarding this article.

Tag -

aws boto python
FOUND THIS USEFUL? SHARE IT

Leave a comment -