Skip to content

Instantly share code, notes, and snippets.

@till
Forked from irontoby/security-group-cleanup.py
Last active January 2, 2016 17:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save till/8334406 to your computer and use it in GitHub Desktop.
Save till/8334406 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import os
import boto
import pprint
del_flag = ''
if len(sys.argv) > 1:
del_flag = sys.argv[1]
pp = pprint.PrettyPrinter(indent=4)
# set credentials
ACCESS_KEY=os.getenv('AWS_ACCESS_KEY_ID')
SECRET_KEY=os.getenv('AWS_SECRET_ACCESS_KEY')
ec2 = boto.connect_ec2(ACCESS_KEY, SECRET_KEY)
allgroups = []
# Get ALL security groups names
groups = ec2.get_all_security_groups()
for groupobj in groups:
allgroups.append(groupobj.name)
# pp.pprint(sorted(allgroups))
# Get [running|stopped] instances security groups
groups_in_use = ['default']
reservations = ec2.get_all_instances()
for r in reservations:
for inst in r.instances:
for group in inst.groups:
if group.name not in groups_in_use:
groups_in_use.append(group.name)
delete_candidates = []
for group in allgroups:
if group not in groups_in_use and not group.startswith('AWS-OpsWorks-'):
delete_candidates.append(group)
if del_flag == '--delete':
print "We will now delete security groups identified to not be in use."
for group in delete_candidates:
ec2.delete_security_group(group)
print "We have deleted %d groups." % (len(delete_candidates))
else:
print "The list of security groups to be removed is below."
print "Run this again with `--delete` to remove them"
pp.pprint(sorted(delete_candidates))
print "Total of %d groups targeted for removal." % (len(delete_candidates))
# For each security group in the total list, if not in the "used" list, flag for deletion
# If running with a "--delete" flag, delete the ones flagged.
@crizCraig
Copy link

You can delete OpsWorks groups in this order:

Solution: First, make sure that no instances are using the security groups. Then, delete the security groups in the following order:

AWS-OpsWorks-Blank-Server

AWS-OpsWorks-Monitoring-Master-Server

AWS-OpsWorks-DB-Master-Server

AWS-OpsWorks-Memcached-Server

AWS-OpsWorks-Custom-Server

AWS-OpsWorks-nodejs-App-Server

AWS-OpsWorks-PHP-App-Server

AWS-OpsWorks-Rails-App-Server

AWS-OpsWorks-Web-Server

AWS-OpsWorks-Default-Server

AWS-OpsWorks-LB-Server

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment