Skip to content

Instantly share code, notes, and snippets.

@lancehunt
Forked from asinghal/prune_aws_security_groups.md
Last active October 31, 2017 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lancehunt/b2d25ac3a080906d313530ebffab8cc9 to your computer and use it in GitHub Desktop.
Save lancehunt/b2d25ac3a080906d313530ebffab8cc9 to your computer and use it in GitHub Desktop.
Clean up AWS Security groups

Commands to get security groups in use and echo names of groups that can not be found in use

Note: Always check manually before deleting security groups. There are various places the groups may be used, and the scripts output may not always be conclusive

aws elb describe-load-balancers --query 'LoadBalancerDescriptions[*].SecurityGroups' --output text | tr '\t' '\n' | sort | uniq > used.txt

aws elbv2 describe-load-balancers --query 'LoadBalancers[*].SecurityGroups' --output text | tr '\t' '\n' | sort | uniq >> used.txt

aws autoscaling describe-launch-configurations --query 'LaunchConfigurations[*].SecurityGroups' --output text | tr '\t' '\n' | sort | uniq >> used.txt

aws ec2 describe-instances --query 'Reservations[*].Instances[*].SecurityGroups[*].GroupId' --output text | tr '\t' '\n' | sort | uniq >> used.txt

aws rds describe-db-instances  --query 'DBInstances[*].VpcSecurityGroups[*].VpcSecurityGroupId' --output text | tr '\t' '\n' | sort | uniq >> used.txt

aws ec2 describe-security-groups --query 'SecurityGroups[*].IpPermissions[*].UserIdGroupPairs[*].GroupId' --output text | tr '\t' '\n' | sort | uniq >> used.txt

aws elasticache describe-cache-clusters --query "CacheClusters[].SecurityGroups[].SecurityGroupId" --output text | tr '\t' '\n' | sort | uniq >> used.txt

comm -23  <(aws ec2 describe-security-groups --query 'SecurityGroups[*].[GroupName,GroupId]' --output text | grep -v "default" | cut  -f2| sort) <(cat used.txt | sort | uniq )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment