I want to identify unused security groups in Amazon Elastic Compute Cloud (Amazon EC2).
Resolution
Note: If you receive errors when you run AWS Command Line Interface (AWS CLI) commands, then see Troubleshooting errors for the AWS CLI. Also, make sure that you're using the most recent AWS CLI version.
To identify unnecessary security groups, complete the following steps:
-
To list all security group IDs in your AWS Region, run the following describe-security-groups command:
aws ec2 describe-security-groups --region region-ID --query 'SecurityGroups[*].GroupId' --output text | tr '\t' '\n'
Note: Replace region-ID with your Region.
-
To list all security groups in a Region that have an attached network interface status, run the following describe-network-interfaces command:
aws ec2 describe-network-interfaces --region region-ID --filters Name=attachment.status,Values=attached --query 'NetworkInterfaces[].Groups[].GroupId' --output text | tr '\t' '\n'| sort | uniq
Note: Replace region-ID with your Region. The preceding command's output includes information for all AWS services in the Region, such as Amazon EC2 or Elastic Load Balancing (ELB).
-
To find all unused security groups, run the following comm command to compare the output of both commands:
comm -23 <(aws ec2 describe-security-groups --region region-ID --query 'SecurityGroups[*].GroupId' --output text | tr '\t' '\n' | sort) <(aws ec2 describe-network-interfaces --region region-ID --query 'NetworkInterfaces[*].Groups[*].GroupId' --output text| tr '\t' '\n' | sort | uniq)
Note: Replace region-ID with your AWS Region.
Related information
Delete an Amazon EC2 security group