Skip to content

Instantly share code, notes, and snippets.

@nand0p
Forked from miketheman/security-group-cleanup.py
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nand0p/a6e8775bf0dfa8c4ff7e to your computer and use it in GitHub Desktop.
Save nand0p/a6e8775bf0dfa8c4ff7e to your computer and use it in GitHub Desktop.
delete unused aws security groups based on secgroup name matching
#!/usr/bin/env python
import os
import re
import sys
import boto
import pprint
del_match = sys.argv[1]
del_flag = ''
if len(sys.argv) == 3:
del_flag = sys.argv[2]
print "del_match: %s" % del_match
print "del_flag: %s" % del_flag
pp = pprint.PrettyPrinter(indent=4)
ec2 = boto.connect_ec2(os.environ['AWS_ACCESS_KEY_ID'],os.environ['AWS_SECRET_ACCESS_KEY'])
del_groups = []
groups = ec2.get_all_security_groups()
for group in groups:
if re.search(del_match, group.name):
del_groups.append(group.id)
if del_flag == '--delete':
print "delete security groups:"
for group in del_groups:
try:
ec2.delete_security_group(group_id=group)
except Exception, dontstop:
print "%s is in use" % group
else:
print "The list of security groups to be removed if not used is below."
print "Run this again with `--delete` to remove them"
pp.pprint(sorted(del_groups))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment