AWS (Listing Unattached security groups in AWS Cloud)

praveen kumar
Sep 6, 2018 · 2 min read

Hi guys when you are working in AWS cloud platform you will come across to get the info about unattached security groups in order to do garbage cleaning, Its a tricky job to do here i am giving aws cli commands to get the un-attached security groups.

Note: this only considers security use in EC2, not other services like RDS. You’ll need to do more work to include security groups used outside EC2.

The good thing is you can’t easily (might not even be possible) to delete active security groups if you miss one associated w/another service.Using the newer AWS CLI tool, I found an easy way to get what I need:

1st Step —

First, get a list of all security groups

aws ec2 describe-security-groups — query ‘SecurityGroups[*].GroupId’ — output text |tr ‘\t’’\n’

Then get all security groups tied to an instance, then piped to sort then uniq:

aws ec2 describe-instances query‘Reservations[*].Instances[*].SecurityGroups[*].GroupId’ — output text |tr ‘\t’’\n’|sort |uniq

Then put it together and compare the 2 lists and see what’s not being used from the master list:

comm -23 <(aws ec2 describe-security-groups — query ‘SecurityGroups[*].GroupId’ — output text | tr ‘\t’’\n’| sort) <(aws ec2 describe-instances — query ‘Reservations[*].Instances[*].SecurityGroups[*].GroupId’ — output text | tr ‘\t’’\n’| sort | uniq)

Bang on it now you can list all unattached security groups which are not used.

Happy clouding

praveen kumar

Written by

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade