Skip to content

Instantly share code, notes, and snippets.

@copernicus
Forked from ehazlett/gist:1754289
Created February 12, 2012 13:42
Show Gist options
  • Save copernicus/1808625 to your computer and use it in GitHub Desktop.
Save copernicus/1808625 to your computer and use it in GitHub Desktop.
AWS EBS Volume Cleanup
#!/usr/bin/env python
from optparse import OptionParser
import boto.ec2
import logging
import sys
def get_ec2_connection(aws_key=None, aws_secret=None, region='us-east-1'):
"""
Returns an EC2Connection to the specified region
:keyword aws_key: AWS key id
:keyword aws_secret: AWS secret
:keyword region: AWS region to connect
:returns: EC2Connection
"""
# find region
conn = None
for r in boto.ec2.regions(aws_access_key_id=aws_key, \
aws_secret_access_key=aws_secret):
if r.name.lower() == region.lower():
conn = r.connect(aws_access_key_id=aws_key, \
aws_secret_access_key=aws_secret)
return conn
def cleanup_ebs_vols(conn=None, owner_id=None):
"""
Removes (deletes) volumes in region that have no snapshot, aren't bound
to an existing instance, or ami
:keyword conn: AWS EC2 connection
:keyword owner_id: AWS Account ID
"""
# gather snapshots
vols = conn.get_all_volumes()
snaps = conn.get_all_snapshots(owner=owner_id)
snap_ids = [x.id for x in snaps]
dead_vols = []
for v in vols:
if v.status == 'available' and v.id not in snap_ids:
dead_vols.append(v)
if dead_vols:
print('The following volumes can be removed: {0}'.format(dead_vols))
prompt = raw_input('Proceed with removal? (y/n): ')
if prompt.lower().strip() == 'y':
for v in dead_vols:
print('Removing {0}...'.format(v.id))
v.delete()
if __name__=='__main__':
op = OptionParser()
op.add_option('--aws-key', dest="aws_key", default=None, \
help="AWS Account Key")
op.add_option('--aws-secret', dest="aws_secret", default=None, \
help="AWS Account Secret")
op.add_option('--aws-account-id', dest="aws_account_id", default=None, \
help="AWS Account ID")
op.add_option('--region', dest="region", default='us-east-1', \
help="AWS Region")
args, opts = op.parse_args()
if not args.aws_key or not args.aws_secret:
op.print_help()
logging.error('You must specify aws_key and aws_secret')
sys.exit(1)
conn = get_ec2_connection(args.aws_key, args.aws_secret, args.region)
cleanup_ebs_vols(conn, args.aws_account_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment