Skip to content

Instantly share code, notes, and snippets.

@kasunbg
Created January 11, 2019 12:36
Show Gist options
  • Save kasunbg/776596dbcb76c9c0d70f594ac62f55ab to your computer and use it in GitHub Desktop.
Save kasunbg/776596dbcb76c9c0d70f594ac62f55ab to your computer and use it in GitHub Desktop.
Delete unused AWS security groups
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
@melaraj2
Copy link

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