Created
February 18, 2018 06:48
-
-
Save nirbhabbarat/047059f87138e04b2fe83bf678161fff to your computer and use it in GitHub Desktop.
Delete AWS volume snapshots older than 30 days via python boto3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
##### USE ON YOUR OWN RISK - THIS IS GOING TO delete_snapshot OLDER THAN 30 DAYS | |
import datetime | |
import sys | |
import boto3 | |
age = 30 | |
aws_profile_name = 'prod' | |
def days_old(date): | |
date_obj = date.replace(tzinfo=None) | |
diff = datetime.datetime.now() - date_obj | |
return diff.days | |
boto3.setup_default_session(profile_name = aws_profile_name) | |
ec2 = boto3.client('ec2') | |
amis = ec2.describe_snapshots(OwnerIds=[ | |
'self' | |
]) | |
# ], MaxResults=90000) | |
for ami in amis['Snapshots']: | |
create_date = ami['StartTime'] | |
snapshot_id = ami['SnapshotId'] | |
day_old = days_old(create_date) | |
if day_old > age: | |
try: | |
print "deleting -> " + snapshot_id + " as image is " + str(day_old) + " old." | |
# delete the snapshot | |
ec2.delete_snapshot(SnapshotId=snapshot_id) | |
except: | |
print "can't delete " + snapshot_id |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#!/usr/bin/env python
USE ON YOUR OWN RISK - THIS IS GOING TO delete_snapshot OLDER THAN 30 DAYS
import datetime
import sys
import boto3
age = 30
aws_profile_name = 'default'
def days_old(date):
date_obj = date.replace(tzinfo=None)
diff = datetime.datetime.now() - date_obj
return diff.days
boto3.setup_default_session(profile_name = aws_profile_name)
ec2 = boto3.client('ec2')
amis = ec2.describe_snapshots(OwnerIds=[
'self'
])
# ], MaxResults=90000)
for ami in amis['Snapshots']:
create_date = ami['StartTime']
snapshot_id = ami['Snaps
Hi,
Thank you for your response. I have changed it to default as i am using for one environment but m getting error in line no 25. Could you please help me here i have added ec2 full access in execution role.
#!/usr/bin/env python
USE ON YOUR OWN RISK - THIS IS GOING TO delete_snapshot OLDER THAN 30 DAYS
import datetime
import sys
import boto3
age = 30
aws_profile_name = 'default'
def days_old(date):
date_obj = date.replace(tzinfo=None)
diff = datetime.datetime.now() - date_obj
return diff.days
boto3.setup_default_session(profile_name = aws_profile_name)
ec2 = boto3.client('ec2')
amis = ec2.describe_snapshots(OwnerIds=[
'self'
])
# ], MaxResults=90000)
for ami in amis['Snapshots']:
create_date = ami['StartTime']
snapshot_id = ami['SnapshotId']
day_old = days_old(create_date)
if day_old > age:
try:
print "deleting -> " + snapshot_id + " as image is " + str(day_old) + " old."
# delete the snapshot
ec2.delete_snapshot(SnapshotId=snapshot_id)
except:
print "can't delete " + snapshot_id