A security group acts as a virtual firewall for the virtual machines and other resources running on cloud. They are created based on ports and IPs to control incoming and outgoing traffic based on the defined inbound and outbound rules respectively.
Deleting unused security groups ensures that they are not accidentally attached to any instance or any other resource which opens up the cloud resources to attacks for hackers.
Minimized cases of unintentional linking of a security group to a resource. And as a bonus, it keeps the cloud environment clean and also lessens the management overhead to a certain extent.
When a user deletes or terminates a resource, the resource gets deleted but not the security group attached to the resource.
Using AWS CLI:
Get 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
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)
Note: A popup will appear displaying that you cannot delete security groups that are attached to instances, other security groups, or network interfaces, and it will list down all the security groups that you can delete (unused security groups)
6. The security groups that have no associated resources will be deleted.
7. Enter the confirmation text and click on Delete, so that unused groups will get deleted.
8. But if you want to delete specific unused security groups one by one, navigate to Security groups section on EC2 dashboard and select the security groups that you want to delete.
9. Click on Actions and select Delete security groups
10. This deletes only the security groups that you choose to delete.
Using AWS CLI:
Using Security group name:
aws ec2 delete-security-group --group-name [NameOfSecurityGroup]
Using Security group id:
aws ec2 delete-security-group --group-id [sg-903004f8]
You may not be able to revoke changes on AWS since the security groups are deleted permanently.
Instead, you can create a new group with the same configurations that you noted down.