Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save guddu07/7a80149e841af21ce5ce0e0ab8a6fab7 to your computer and use it in GitHub Desktop.
Save guddu07/7a80149e841af21ce5ce0e0ab8a6fab7 to your computer and use it in GitHub Desktop.
Find unused security groups using Boto3 in your AWS account
import boto3 #Calling Boto3 library
ec2 = boto3.resource('ec2', region_name='us-west-2')
sgs = ec2.security_groups.all() # Fetching all security groups in AWS account
all_sgs = set([sg.group_name for sg in sgs]) # Creating a list of only security group names
instances = ec2.instances.all() # Getting all instances in AWS account
inssgs = set([sg['GroupName'] for ins in instances for sg in ins.security_groups]) # Getting all security groups attached to any instances
unused_sgs = all_sgs - inssgs # Removing duplicate SGs
for sg in unused_sgs:
print(sg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment