Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Interactively clean up unused VPC security groups.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import boto
import readline # noqa: W0611
def p(string):
sys.stdout.write(string)
sys.stdout.flush()
p('Connecting…')
ec2 = boto.connect_ec2()
empty_sgs = []
nonempty_sgs = []
p('fetching security groups…')
for sg in ec2.get_all_security_groups():
p('.')
num = len(sg.instances())
sg_list = nonempty_sgs if num else empty_sgs
sg_list.append({
'id': sg.id,
'name': sg.name,
'count': len(sg.instances()),
})
p('ok.\n')
def sg_sort_key(sg):
return (sg['count'], sg['id'], sg['name'])
if nonempty_sgs:
print ''
print 'Non-Empty Security Groups:'
for sg in sorted(nonempty_sgs, key=sg_sort_key):
print '{0[count]}\t{0[id]}\t{0[name]}'.format(sg)
if empty_sgs:
print ''
print 'Empty Security Groups:'
for sg in sorted(empty_sgs, key=sg_sort_key):
print '{0[id]}\t{0[name]}'.format(sg)
print ''
for sg in sorted(empty_sgs, key=sg_sort_key):
if sg['name'] == 'default':
continue
confirmation = raw_input('Delete {0[id]}\t{0[name]}? (enter \'Y\') '.format(sg))
if confirmation == 'Y':
print 'Deleting security group {[id]}…'.format(sg),
try:
ec2.delete_security_group(group_id=sg['id'])
except Exception as e:
print 'Error: {}'.format(e)
abort = raw_input('Continue? (enter \'Y\')')
if abort != 'Y':
print 'Aborting.'
sys.exit(-1)
else:
print 'done.'
else:
print 'Skipping security group {[id]}.'.format(sg)
if not nonempty_sgs and not empty_sgs:
print 'No security groups found!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment