Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find Unused Amazon EC2 Security groups

I'm try to find a way to determine orphan security groups so I can clean up and get rid of them. Does anyone know of a way to discover unused security groups.

Either through the console or with the command line tools will work (Running command line tools on linux and OSX machines).

like image 305
Ray Avatar asked Jul 10 '14 20:07

Ray


People also ask

How do I know if my security group is in use?

To confirm which security groups are still being used you should reverse or remove the if len(sg. instances()) == 0 test and print the len(sg. instances()) value out.

How do you find the security group dependency?

The best way to do this in the AWS EC2 console, is to paste in the security group name in the search field in the EC2->Instances section. All instances associated with the pasted security group will then populate-those would be the ec2 objects (dependencies).

How many security groups are there in an EC2 instance?

You can assign up to 5 security groups to a network interface. If you need to increase or decrease this limit, you can contact AWS Support. The maximum is 16.


1 Answers

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:

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) 
like image 193
Ray Avatar answered Sep 28 '22 01:09

Ray