Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active October 3, 2025 03:28
Show Gist options
  • Save magnetikonline/afd637ef8c154eb721120952de38d141 to your computer and use it in GitHub Desktop.
Save magnetikonline/afd637ef8c154eb721120952de38d141 to your computer and use it in GitHub Desktop.
Locate unused AWS security groups.

Locate unused AWS security groups

For an AWS Security Group to be considered in-use/active it will be assigned to an Elastic network interface (ENI's).

The following Python script will determine currently unused security groups by:

  • Query AWS for all active ENI's in an account region.
  • For each interface, extract the attached security group(s).
  • Query AWS for all security groups within the same account region.
  • Determine where and output a security group which currently has zero assignments to any active ENI's.
#!/usr/bin/env python3
import boto3
def main():
ec2_client = boto3.client("ec2")
# determine all security groups used across all active ENI's
eni_list = ec2_client.describe_network_interfaces()["NetworkInterfaces"]
used_security_group_set = set()
for eni in eni_list:
for group in eni["Groups"]:
used_security_group_set.add(group["GroupId"])
security_group_list = ec2_client.describe_security_groups()["SecurityGroups"]
for security_group in security_group_list:
group_id = security_group["GroupId"]
if group_id not in used_security_group_set:
print(f"Unused security group: {group_id} | {security_group['GroupName']}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment