Listen to this Post
Keeping your AWS resources organized is crucial for maintaining a clean and efficient cloud environment. Over time, unused resources like Security Groups can accumulate, leading to unnecessary clutter and potential security risks. Using the AWS SDK, particularly Boto3 for Python, you can automate the process of identifying and cleaning up these unused resources.
You Should Know:
1. Installing Boto3:
To get started, you need to install the Boto3 library. You can do this using pip:
pip install boto3
2. Listing Security Groups:
The following Python script lists all Security Groups in your AWS account:
import boto3
ec2 = boto3.client('ec2')
response = ec2.describe_security_groups()
for sg in response['SecurityGroups']:
print(f"Security Group ID: {sg['GroupId']}, Name: {sg['GroupName']}")
3. Identifying Unused Security Groups:
To find unused Security Groups, you can check if they are associated with any EC2 instances:
used_sgs = set()
instances = ec2.describe_instances()
for instance in instances['Reservations']:
for interface in instance['Instances'][0]['NetworkInterfaces']:
for group in interface['Groups']:
used_sgs.add(group['GroupId'])
all_sgs = set(sg['GroupId'] for sg in response['SecurityGroups'])
unused_sgs = all_sgs - used_sgs
print("Unused Security Groups:")
for sg in unused_sgs:
print(sg)
4. Automating Cleanup with EventBridge:
You can schedule this script to run periodically using AWS EventBridge. Here’s how to set up a rule in EventBridge:
aws events put-rule --name "CleanupUnusedSGs" --schedule-expression "rate(7 days)" aws events put-targets --rule "CleanupUnusedSGs" --targets "Id"="1","Arn"="arn:aws:lambda:us-east-1:123456789012:function:CleanupUnusedSGs"
5. Deleting Unused Security Groups:
Once identified, you can delete the unused Security Groups:
for sg in unused_sgs:
ec2.delete_security_group(GroupId=sg)
print(f"Deleted Security Group: {sg}")
What Undercode Say:
Managing AWS resources efficiently is a critical aspect of cloud operations. Unused Security Groups not only clutter your environment but can also pose security risks if left unattended. By leveraging Python and Boto3, you can automate the identification and cleanup of these resources, ensuring a lean and secure AWS environment. Additionally, integrating this process with AWS EventBridge allows for regular maintenance without manual intervention.
Expected Output:
- Unused Security Groups Identified:
The script will output a list of Security Group IDs that are not associated with any EC2 instances. -
Automated Cleanup:
The script can be scheduled to run periodically, ensuring that your AWS environment remains clean and secure.
For more details, you can refer to the original article: Finding and Validating Unused Security Groups in AWS with Python and Boto3.
References:
Reported By: Darryl Ruggles – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅



