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.
>>> import datetime
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.
>>>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.
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
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 ”
from dateutil import parser
from boto import ec2
#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)
# 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.