Skip to content

Instantly share code, notes, and snippets.

@adamanthil
Created March 19, 2018 22:32
Show Gist options
  • Save adamanthil/771c77df42af7941955930827010a74e to your computer and use it in GitHub Desktop.
Save adamanthil/771c77df42af7941955930827010a74e to your computer and use it in GitHub Desktop.
#!/bin/bash
# Finds and deletes unused aws security groups, following template for determining unused groups here:
# https://stackoverflow.com/a/24704644
region=$1
comm -23 <(aws ec2 describe-security-groups --query 'SecurityGroups[*].GroupId' \
--output text --region $region | tr '\t' '\n'| sort) \
<(aws ec2 describe-instances --query 'Reservations[*].Instances[*].SecurityGroups[*].GroupId' \
--output text --region $region | tr '\t' '\n' | sort | uniq) \
| while read groupid; do
echo "Deleting $groupid"
aws ec2 delete-security-group --dry-run --region $region --group-id $groupid
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment