Created
January 11, 2019 12:36
-
-
Save kasunbg/776596dbcb76c9c0d70f594ac62f55ab to your computer and use it in GitHub Desktop.
Delete unused AWS security groups
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
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) \ | |
| tee -a unused-security-groups-in-ec2.txt | |
for x in `cat unused-security-groups-in-ec2.txt`; do echo 'deleting sg: $x' ; aws ec2 delete-security-group --group-id $x; done |
WARNING
If you have AWS ECS services with AWSPVC or Fargate launch type and they use the security group, there is no protection, the security group will be removed, leaving the services broken. Unless the services is up and running.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanation:
comm
command compares two outputs from aws-cli operationsdescribe-security-groups
, anddescribe-instances
.The first command in there outputs all the security groups in your AWS account on the region you specified in
~/.aws/config
. If you are unsure, runaws configure
to see the region. I use us-east-1.The second command in there lists the metadata of all the ec2 instances. We only query the security groups used by your ec2 instance.
After that, we compare the two outputs, and write the unused security groups into the file, unused-security-groups-in-ec2.txt.
After that, we iterate the 'unused-security-groups-in-ec2.txt' file line-by-line via a for-loop, and delete the security groups.
Note 1: AWS CLI won't let you delete security groups that are already attached to a resource like EC2, RDS, or ELB/ALB. You'll see an error like following if you attempt to do that. Yes, AWS it fool-proof. :-)
An error occurred (DependencyViolation) when calling the DeleteSecurityGroup operation: resource sg-32c2a2b14ff has a dependent object
Note 2: Above commands only shows the security groups that are not used by ec2 instances. But, other aws resources like RDS, ALB also use security groups. Because of Note 1, you are safe.