· 6 years ago · Aug 29, 2019, 07:54 PM
1#!/usr/bin/env python
2
3import sys
4import boto
5import pprint
6
7del_flag = ''
8if len(sys.argv) > 1:
9 del_flag = sys.argv[1]
10
11pp = pprint.PrettyPrinter(indent=4)
12
13# set credentials
14ACCESS_KEY="<access key>"
15SECRET_KEY="<security key>"
16
17ec2 = boto.connect_ec2(ACCESS_KEY, SECRET_KEY)
18
19allgroups = []
20# Get ALL security groups names
21groups = ec2.get_all_security_groups()
22for groupobj in groups:
23 allgroups.append(groupobj.name)
24# pp.pprint(sorted(allgroups))
25
26# Get [running|stopped] instances security groups
27groups_in_use = ['default']
28for state in ['running','stopped']:
29 reservations = ec2.get_all_instances(filters={'instance-state-name': state})
30 for r in reservations:
31 for inst in r.instances:
32 if inst.groups[0].name not in groups_in_use:
33 groups_in_use.append(inst.groups[0].name)
34
35delete_candidates = []
36for group in allgroups:
37 if group not in groups_in_use and not group.startswith('AWS-OpsWorks-'):
38 delete_candidates.append(group)
39
40if del_flag == '--delete':
41 print "We will now delete security groups identified to not be in use."
42 for group in delete_candidates:
43 ec2.delete_security_group(group)
44 print "We have deleted %d groups." % (len(delete_candidates))
45else:
46 print "The list of security groups to be removed is below."
47 print "Run this again with `--delete` to remove them"
48 pp.pprint(sorted(delete_candidates))
49 print "Total of %d groups targeted for removal." % (len(delete_candidates))
50
51
52
53
54# For each security group in the total list, if not in the "used" list, flag for deletion
55# If running with a "--delete" flag, delete the ones flagged.