Find resources associated to a security group in AWS using Boto3

When it comes to managing security in Amazon Web Services (AWS), Security Groups are an essential tool for controlling access to resources within a VPC (Virtual Private Cloud). Security Groups act as a virtual firewall, controlling inbound and outbound traffic to instances and resources.
One of the most critical aspects of managing Security Groups is understanding which resources are associated with them. In this article, we will discuss how to list all resources associated with a Security Group in AWS using a Boto3, also will discuss a way to find unused Security Groups in your AWS account.
Boto3 is the Amazon Web Services (AWS) Software Development Kit (SDK) for Python, which allows Python developers to write software that makes use of AWS services such as Amazon S3, Amazon EC2, and Amazon DynamoDB.
Boto3 provides a simple and intuitive interface to interact with AWS services, making it easy for developers to build applications that utilize AWS resources. It allows for creating, configuring, and managing AWS services programmatically through Python code.
Boto3 is continuously updated to keep up with new AWS services and features, ensuring that developers have access to the latest tools and resources for their applications. Overall, Boto3 is an essential tool for Python developers working with AWS services, enabling them to build scalable, flexible, and robust applications.
Let the fun begin, and get our hands dirty. We have more than one way to list all resources attached to a Security Group, as mentioned here you can use the Management Console or the AWS CLI, hence we will go with the SDK using a Boto3 script as below:
import boto3
# Enter your AWS region and security group ID
region = 'us-east-1'
security_group_id = 'sg-id'
# Create a session using your AWS access key and secret access key
session = boto3.Session(aws_access_key_id='YOUR_ACCESS_KEY',
aws_secret_access_key='YOUR_SECRET_KEY',
region_name='region')
# Create an EC2 client
ec2 = session.client('ec2')
# Retrieve a list of instances associated with the specified security group
response = ec2.describe_instances(Filters=[
{'Name': 'instance.group-id', 'Values': [security_group_id]}
])
# Print the IDs of the instances associated with the security group
for reservation in response['Reservations']:
for instance in reservation['Instances']:
print(instance['InstanceId'])
# Retrieve a list of network interfaces associated with the specified security group
response = ec2.describe_network_interfaces(Filters=[
{'Name': 'group-id', 'Values': [security_group_id]}
])
# Print the IDs of the network interfaces associated with the security group
for network_interface in response['NetworkInterfaces']:
print(network_interface['NetworkInterfaceId'])
This will list all instances and also all the ENIs associated to the specified in the script.
Ultimately, to find out the unused Security Groups, you can use the below script:
import boto3
# Specify the region you want to check for unused Security Groups
region_name = 'us-east-1'
# Create a new session with your AWS credentials
session = boto3.Session(
aws_access_key_id='YOUR_ACCESS_KEY_ID',
aws_secret_access_key='YOUR_SECRET_ACCESS_KEY'
)
# Create an EC2 client object with the specified region
ec2 = session.client('ec2', region_name=region_name)
# Get all Security Groups within the specified region
all_security_groups = ec2.describe_security_groups()['SecurityGroups']
# Get a list of all instances within the specified region
all_instances = ec2.describe_instances()
# Get a list of all Security Group IDs associated with running instances
running_instance_groups = [group['GroupId'] for reservation in all_instances['Reservations'] for instance in reservation['Instances'] for group in instance['SecurityGroups']]
# Find all Security Groups that are not associated with any running instances
unused_security_groups = [sg for sg in all_security_groups if sg['GroupId'] not in running_instance_groups]
# Print out the list of unused Security Groups
print("Unused Security Groups in " + region_name + ":")
for sg in unused_security_groups:
print(sg['GroupId'])
Replace YOUR_ACCESS_KEY_ID and YOUR_SECRET_ACCESS_KEY with your actual AWS access key ID and secret access key. Additionally, make sure that the user associated with these credentials has the appropriate permissions to list EC2 Security Groups.This script uses the describe_security_groups() method to get all Security Groups in the region, and describe_instances() to get all instances.
Then, it creates a set of all used Security Group IDs by iterating through each instance and adding the Security Group IDs to the set. Finally, it checks each Security Group to see if it's not in the used groups set and prints out the IDs of any unused Security Groups.
Note that this script assumes that there are no unused Security Groups with any existing rules. If there are unused Security Groups with rules, they will not be listed as unused by this script. You may need to modify this script to suit your specific needs.
Problem Solved! We now getting the used and unused Security Groups with our AWS preferred region, without logging to the Management console.
