agent: |
YlFJyXUlKKJewMG2oMAKCheck which AWS EC2 Instances have a Public IP Associated: SOC2 Compliance
Check which AWS EC2 Instances have a Public IP Associated: SOC2 Compliance
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
This task is focused on identifying EC2 instances in an AWS environment that are assigned public IP addresses. It plays a crucial role in maintaining SOC2 compliance by identifying potential security risks associated with public internet exposure.
inputs
outputs
import boto3
from botocore.exceptions import ClientError, BotoCoreError
creds = _get_creds(cred_label)['creds']
access_key = creds['username']
secret_key = creds['password']
def check_public_ip(ec2_client, region):
"""
Check EC2 instances in a region for public IPs and categorize them as compliant or non-compliant.
:param ec2_client: The boto3 EC2 client.
:param region: The AWS region to check.
:return: A compliance report dictionary.
"""
compliance_report = {'compliant': [], 'non_compliant': []}
try:
# Retrieve all instances in the specified region
response = ec2_client.describe_instances()
# Iterate over each instance to check for public IP
for reservation in response.get('Reservations', []):
for instance in reservation.get('Instances', []):
instance_id = instance.get('InstanceId')
public_ip = instance.get('PublicIpAddress')
# Categorize based on public IP presence
if public_ip:
compliance_report['non_compliant'].append({'InstanceId': instance_id, 'Region': region, 'PublicIP': public_ip})
else:
compliance_report['compliant'].append({'InstanceId': instance_id, 'Region': region})
except ClientError as e:
print(f"ClientError checking instances in region {region}: {e}")
except BotoCoreError as e:
print(f"BotoCoreError occurred: {e}")
except Exception as e:
print(f"Unexpected error occurred in region {region}: {e}")
return compliance_report
def evaluate_ec2_instances(region_name=None):
"""
Evaluate EC2 instances for public IP compliance in a specific region or all regions.
:param region_name: Specific region name or None for all regions.
:return: A global compliance report dictionary.
"""
global_compliance_report = {'compliant': [], 'non_compliant': []}
try:
ec2_client = boto3.client('ec2',aws_access_key_id=access_key,aws_secret_access_key=secret_key, region_name='us-east-1')
# Determine regions to check
regions = [region_name] if region_name else [region['RegionName'] for region in ec2_client.describe_regions()['Regions']]
# Check each region for public IP compliance
for region in regions:
print(f"Checking instances in region: {region}")
ec2_region_client = boto3.client('ec2',aws_access_key_id=access_key,aws_secret_access_key=secret_key, region_name=region)
region_compliance_report = check_public_ip(ec2_region_client, region)
# Aggregate results
global_compliance_report['compliant'].extend(region_compliance_report['compliant'])
global_compliance_report['non_compliant'].extend(region_compliance_report['non_compliant'])
except ClientError as e:
print(f"ClientError while evaluating EC2 instances: {e}")
except BotoCoreError as e:
print(f"BotoCoreError occurred: {e}")
except Exception as e:
print(f"Unexpected error occurred: {e}")
return global_compliance_report
# Example usage
#region_name = None #'ap-south-1' # Specify a region or set to None for all regions
compliance_report = evaluate_ec2_instances(region_name)
# Display compliance summary
print("\nCompliance Summary:")
# Print details for compliant and non-compliant instances
if compliance_report['compliant']:
print("\nCompliant Instances:")
for instance in compliance_report['compliant']:
print(f"InstanceId: {instance['InstanceId']}, Region: {instance['Region']}")
else:
print("\nNo Compliant Instances Found.")
if compliance_report['non_compliant']:
print("\nNon-Compliant Instances (with Public IP):")
for instance in compliance_report['non_compliant']:
print(f"InstanceId: {instance['InstanceId']} \nRegion: {instance['Region']} \nPublic IP: {instance['PublicIP']}\n" + "-"*40)
else:
print("\nNo Non-Compliant Instances Found.")
context.skip_sub_tasks=True
copied