This guide explains how to use an AWS CLI command to identify security group references both within VPC and across VPC peering connections
This guide helps AWS administrators and security teams identify and audit security group dependencies across VPCs and accounts, which is crucial for maintaining security compliance, troubleshooting connectivity issues, and cleaning up unused security group references in complex AWS environments.
Prerequisites
- AWS CLI installed and configured
- Required IAM permissions:
* ec2:DescribeSecurityGroups
* ec2:DescribeSecurityGroupReferences
- Active VPC peering connections (for cross-VPC references)
The Command
for sg in $(aws ec2 describe-security-groups --query 'SecurityGroups[*].GroupId' --output text); do \
echo "Checking SG: $sg"; \
aws ec2 describe-security-group-references \
--group-id $sg \
--query 'SecurityGroupReferenceSet[].{
SourceSG:GroupId,
ReferencingVPC:ReferencingVpcId,
PeeringConnection:VpcPeeringConnectionId
}' \
--output table 2>/dev/null; \
aws ec2 describe-security-groups \
--filters "Name=ip-permission.group-id,Values=$sg" \
--query 'SecurityGroups[].{
ReferencingSG:GroupId,
ReferencingSGName:GroupName,
ReferencingVPC:VpcId
}' \
--output table; \
echo "---------------"; \
done
What This Command Does
The command performs two main actions:
- Lists all security groups in your account.
- Checks in security group references for each security group in same VPC and cross-VPC connected through VPC Peering.
Output Explanation
For each security group, you'll see two tables:
First Table (Cross-VPC References):
- SourceSG: The security group being checked
- ReferencingVPC: VPC ID where the reference exists
- PeeringConnection: VPC peering connection ID
Second Table (Security Group References):
- ReferencingSG: ID of the security group containing the reference
- ReferencingSGName: Name of the referencing security group
- ReferencingVPC: VPC ID of the referencing security group
Troubleshooting Tips
If the command fails:
- Check AWS CLI configuration
- Verify IAM permissions
- Ensure VPC peering connections are active
- Validate security group existence
- Check AWS CLI version
Example Output

Conclusion
This command provides a comprehensive view of security group references across your AWS infrastructure. Regular use helps maintain security group hygiene and understand cross-VPC dependencies.
Remember to:
- Review outputs carefully
- Document findings
- Clean up unused references
- Maintain proper security group documentation
For more information, refer to AWS documentation on: