Skip to content

Instantly share code, notes, and snippets.

@ymcdull
Created April 14, 2016 11:29
Show Gist options
  • Save ymcdull/4729491c9ea7f17aa32439ba7c8cf5d6 to your computer and use it in GitHub Desktop.
Save ymcdull/4729491c9ea7f17aa32439ba7c8cf5d6 to your computer and use it in GitHub Desktop.
A simple python file to clean up all unused AWS security groups with boto3
#!/usr/bin/env python
import boto3
### ###
# Need aws credentails already been configured #
### ###
### Code based on https://gist.github.com/miketheman/2630437
client = boto3.client('ec2')
### Pre-defined groups lists
in_use_groups = []
to_delete_groups = []
### Get All security groups
all_groups = [group['GroupName'] for group in client.describe_security_groups()['SecurityGroups']]
### Get All instances
all_instances = client.describe_instances()
### Get All security groups that has been used by some instances
for instances in all_instances['Reservations']:
for inst in instances['Instances']:
for group in inst['SecurityGroups']:
groupName = group['GroupName']
if groupName not in in_use_groups:
in_use_groups.append(groupName)
### Get security group candidates that has not been used and will be deleted
delete_candidates = [item for item in all_groups if item not in in_use_groups]
### Can Add some more filtering conditions like this:
#delete_candidates = [item for item in all_groups if item not in in_use_groups and item.startswith('launch-wizard-') and int(group.split('-')[-1]) > 5]
### Start delete security groups that haven't been used
print("We will now delete security groups.")
for group in to_delete_groups:
client.delete_security_group(GroupName = group)
print("We have deleted %d groups." % (len(to_delete_groups)))
@praveenchaga
Copy link

I tried with the above code.My main requirement is to delete launch wizard security groups automatically (Security groups which we create while launching the instance eg: 'launch-wizard-1 ,launch-wizard-2....etc). So, i used the above code and then i have commented the below lines -(line 31)

Get security group candidates that has not been used and will be deleted

#delete_candidates = [item for item in all_groups if item not in in_use_groups]

and

uncomment the below lines (line 34 ):

Can Add some more filtering conditions like this:

#delete_candidates = [item for item in all_groups if item not in in_use_groups and item.startswith('launch-wizard-') and int(group.split('-')[-1]) > 5]

So, finaly iam getting the error 'dict' object has no attribute 'split'

@Haarkad
Copy link

Haarkad commented May 28, 2018

Hey hey, looking at this I would think that using GroupId would be a better way to do it as GroupName can be duplicated. Otherwise, I like how this functions.

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