Last active
April 12, 2022 15:01
-
-
Save guddu07/7a80149e841af21ce5ce0e0ab8a6fab7 to your computer and use it in GitHub Desktop.
Find unused security groups using Boto3 in your AWS account
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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