agent: |
OikFM9ofB868zPE3c1yYList all AWS EC2 Security Groups
List all AWS EC2 Security Groups
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
This task involves retrieving and displaying all EC2 Security Groups across specified or all AWS regions, including details such as Group ID, Group Name, Description, VPC ID, associated instances, and tags.
inputs
outputs
import boto3
from botocore.exceptions import NoCredentialsError, ClientError
creds = _get_creds(cred_label)['creds']
access_key = creds['username']
secret_key = creds['password']
def get_regions(ec2_client):
return [region['RegionName'] for region in ec2_client.describe_regions()['Regions']]
def list_security_groups(ec2_client, region=None):
paginator = ec2_client.get_paginator('describe_security_groups')
security_groups = []
try:
for page in paginator.paginate():
for sg in page['SecurityGroups']:
# Fetching associated instances for each security group
associated_instances = []
reservations = ec2_client.describe_instances(Filters=[{'Name': 'instance.group-id', 'Values': [sg['GroupId']]}])
for reservation in reservations['Reservations']:
for instance in reservation['Instances']:
associated_instances.append(instance['InstanceId'])
# Fetching tags for each security group
tags = {tag['Key']: tag['Value'] for tag in sg.get('Tags', [])}
security_groups.append({
'GroupId': sg['GroupId'],
'GroupName': sg.get('GroupName', 'N/A'),
'Description': sg.get('Description', 'N/A'),
'VpcId': sg.get('VpcId', 'N/A'),
'Region': region,
'AssociatedInstances': associated_instances,
'Tags': tags
})
except ClientError as e:
print(f"Error retrieving security groups in {region}: {e}")
return security_groups
def list_all_security_groups(region_name=None):
"""
List all security groups in a specified region or in all regions if no region is specified.
Args:
region_name (str, optional): AWS region name. Lists security groups in all regions if None. Defaults to None.
"""
# Initialize client for the default region to fetch regions if needed
ec2_client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name='us-east-1')
if region_name:
#print(f"Listing security groups in region: {region_name}")
regions = [region_name]
else:
#print("No specific region provided. Listing security groups in all regions.")
regions = get_regions(ec2_client)
all_security_groups = []
for region in regions:
#print(f"Processing region: {region}")
regional_client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region)
all_security_groups.extend(list_security_groups(regional_client, region))
return all_security_groups
def display_security_groups(security_groups):
# Initialize table with the desired structure and headers
table = context.newtable()
table.title = "Security Group Details"
table.num_cols = 7 # Number of columns according to headers
table.num_rows = 1 # Starts with one row for headers
table.has_header_row = True
# Define header names based on the new structure
headers = ["Region", "GroupId", "GroupName", "Description", "VpcId", "Associated Instances", "Tags"]
# Set headers in the first row
for col_num, header in enumerate(headers):
table.setval(0, col_num, header)
# Sort the security group data by Region for better organization
security_groups.sort(key=lambda x: x['Region'])
# Populate the table with security group data
for row_num, sg in enumerate(security_groups, start=1): # Starting from the second row
table.num_rows += 1 # Add a row for each security group
values = [
sg['Region'],
sg['GroupId'],
sg['GroupName'],
sg['Description'],
sg['VpcId'],
', '.join(sg['AssociatedInstances']),
', '.join([f"{k}: {v}" for k, v in sg['Tags'].items()])
]
for col_num, value in enumerate(values):
table.setval(row_num, col_num, value)
# Example usage
try:
#region_name = None # Set to None to list security groups for all available regions or specify a region
security_groups = list_all_security_groups(region_name)
display_security_groups(security_groups)
except NoCredentialsError:
print("Error: AWS credentials not available. Please configure them.")
except ClientError as e:
print(f"AWS Client error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
copied