agent: |
jtE72IY5WRDEnevpEUHqList all AWS CloudTrail Trails
List all AWS CloudTrail Trails
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
This task involves enumerating and retrieving detailed information about every AWS CloudTrail trail that exists across all AWS regions within an AWS account. Each trail captures specific API activity and events, and having a comprehensive list helps in providing visibility into what actions are being logged, where the logs are stored, and how they are configured. This listing process is foundational for subsequent tasks like auditing, analysis, and optimization of AWS CloudTrail, aiding in efficient resource management and security compliance.
inputs
outputs
import boto3
creds = _get_creds(cred_label)['creds']
access_key = creds['username']
secret_key = creds['password']
# Set region to None for all regions, or specify a valid AWS region string for a specific region
#target_region = None
target_region = target_region if target_region else None
try:
# List all available AWS regions
ec2_client = boto3.client('ec2',aws_access_key_id=access_key,aws_secret_access_key=secret_key,region_name='us-east-1')
all_regions = [region['RegionName'] for region in ec2_client.describe_regions()['Regions']]
except Exception as e:
print(f"ERROR: An error occurred while listing AWS regions: {e}")
all_regions = []
# Get trails for all regions or a specific region
regions_to_check = all_regions if target_region is None else [target_region]
all_trails = []
for region in regions_to_check:
try:
# List all trails in AWS CloudTrail for each region
cloudtrail_client = boto3.client('cloudtrail', aws_access_key_id=access_key,aws_secret_access_key=secret_key,region_name=region)
response = cloudtrail_client.describe_trails(includeShadowTrails=False)
trails_in_region = response['trailList']
if not trails_in_region:
print(f"INFO: No trails found in region {region}.")
else:
all_trails.extend(trails_in_region)
except Exception as e:
# Handle exceptions thrown while listing trails for a region
print(f"ERROR: An error occurred while listing trails in region {region}: {e}")
# Print all trails
if not all_trails:
print("INFO: No trails found in all specified regions.")
else:
try:
#print(all_trails) # for downstream task
for trail in all_trails:
print(f"Trail Name: {trail['Name']}, Trail ARN: {trail['TrailARN']}, Home Region: {trail['HomeRegion']}")
except KeyError as ke:
print(f"ERROR: Missing key {ke} in trail information: {trail}")
except Exception as e:
print(f"ERROR: An error occurred while printing trail information: {e}")
print(f"SUMMARY: Processed {len(regions_to_check)} regions and found a total of {len(all_trails)} trails.")
copied