Skip to content

Instantly share code, notes, and snippets.

@JEEN
Created August 17, 2018 12:48
Show Gist options
  • Save JEEN/c7e28eeff0a418b98a7380f88777e3e9 to your computer and use it in GitHub Desktop.
Save JEEN/c7e28eeff0a418b98a7380f88777e3e9 to your computer and use it in GitHub Desktop.
check-unused-security-groups.sh
#!/bin/bash
rm -rf security-groups
rm -rf inuse-sg
rm -rf uniq-inuse
rm -rf unused-security-groups.txt
aws ec2 describe-security-groups --output json | jq -r '.SecurityGroups[].GroupId' | sort > security-groups
aws ec2 describe-instances --output json | jq -r '.Reservations[].Instances[].SecurityGroups[].GroupId' > inuse-sg
aws elb describe-load-balancers --output json | jq -r '.LoadBalancerDescriptions[].SecurityGroups[]' >> inuse-sg
aws elbv2 describe-load-balancers --output json | jq -r '.LoadBalancers[].SecurityGroups[]' >> inuse-sg
aws rds describe-db-instances --output json | jq -r '.DBInstances[].VpcSecurityGroups[].VpcSecurityGroupId' >> inuse-sg
aws elasticache describe-cache-clusters --output json | jq -r '.CacheClusters[].SecurityGroups[].SecurityGroupId' >> inuse-sg
aws redshift describe-clusters --output json | jq -r '.Clusters[] | (.ClusterSecurityGroups[] .ClusterSecurityGroupId), (.VpcSecurityGroups[] .VpcSecurityGroupId)' >> inuse-sg
aws efs describe-file-systems | jq -r ".FileSystems[] .FileSystemId" \
| xargs -I {} aws efs describe-mount-targets --file-system-id {} | jq -r ".MountTargets[] .MountTargetId" \
| xargs -I {} aws efs describe-mount-target-security-groups --mount-target-id {} | jq -r ".SecurityGroups[]" \
>> inuse-sg
cat inuse-sg | sort | uniq > uniq-inuse
diff security-groups uniq-inuse | grep sg | cut -c 3-22 | xargs -I {} aws ec2 describe-security-groups --group-ids {} | jq -r ".SecurityGroups[] | [.GroupId, .GroupName] | @tsv"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment