Unfortunately, AWS does not directly provide a creation timestamp for security groups in the standard EC2 DescribeSecurityGroups API response.
However if you have Cloud Trail Enabled you can proceed as below.
CloudTrail: If you have AWS CloudTrail enabled and logs are stored for the period when the security group was created, you can query those logs for the creation event of the security group. This approach is valid for tracking down historical events if CloudTrail was enabled during that time.
Here’s a code example for the this using AWS SDK for Python (Boto3):
import boto3
def find_security_group_creation_date(security_group_id, trail_name):
# Create CloudTrail client
client = boto3.client('cloudtrail')
# Look up events related to the security group in question
response = client.lookup_events(
LookupAttributes=[
{
'AttributeKey': 'ResourceName',
'AttributeValue': security_group_id
},
],
MaxResults=50 # Adjust as necessary. Default is 50, max is 50.
)
# Iterate through the events and find the creation event
for event in response.get('Events', []):
if event['EventName'] == 'CreateSecurityGroup':
return event['EventTime']
return None
# Example usage:
security_group_id = "YOUR_SECURITY_GROUP_ID"
trail_name = "YOUR_CLOUDTRAIL_TRAIL_NAME"
creation_date = find_security_group_creation_date(security_group_id, trail_name)
if creation_date:
print(f"Security Group {security_group_id} was created on {creation_date}")
else:
print(f"Could not determine creation date for Security Group {security_group_id}")
Replace YOUR_SECURITY_GROUP_ID with the ID of your security group, and YOUR_CLOUDTRAIL_TRAIL_NAME with the name of your CloudTrail trail.
Keep in mind that CloudTrail retains events for a limited time unless you’ve configured it to deliver logs to an S3 bucket. Depending on your CloudTrail settings, older events might be inaccessible if they’ve been pruned or were never captured.
2
Answers
Unfortunately, AWS does not directly provide a creation timestamp for security groups in the standard EC2
DescribeSecurityGroups
API response.However if you have Cloud Trail Enabled you can proceed as below.
CloudTrail: If you have AWS CloudTrail enabled and logs are stored for the period when the security group was created, you can query those logs for the creation event of the security group. This approach is valid for tracking down historical events if CloudTrail was enabled during that time.
Here’s a code example for the this using AWS SDK for Python (Boto3):
Replace
YOUR_SECURITY_GROUP_ID
with the ID of your security group, andYOUR_CLOUDTRAIL_TRAIL_NAME
with the name of your CloudTrail trail.Keep in mind that CloudTrail retains events for a limited time unless you’ve configured it to deliver logs to an S3 bucket. Depending on your CloudTrail settings, older events might be inaccessible if they’ve been pruned or were never captured.