Event History Queries via SDK
LookupEvents is CloudTrail's fastest path to answering "what happened, and who did it" without setting up a trail first.
Busque em todas as páginas da documentação
LookupEvents is CloudTrail's fastest path to answering "what happened, and who did it" without setting up a trail first.
This page covers filtering by event name, actor, and resource, bounding the time window, and paginating through larger result sets.
Quick-reference recipe card - copy-paste ready.
# --- Python (boto3) ---
import boto3
from datetime import datetime, timedelta
client = boto3.client("cloudtrail")
response = client.lookup_events(
LookupAttributes=[{"AttributeKey": "EventName", "AttributeValue": "DeleteBucket"}],
StartTime=datetime.utcnow() - timedelta(days=1),
MaxResults=20,
)
for event in response["Events"]:
print(event["EventTime"], event["Username"], event["EventName"])When to reach for this:
Filter by resource name to find every action taken against a specific S3 bucket in the last 24 hours.
# --- Python (boto3) ---
import boto3
from datetime import datetime, timedelta
client = boto3.client("cloudtrail")
response = client.lookup_events(
LookupAttributes=[
{"AttributeKey": "ResourceName", "AttributeValue": "acme-prod-reports"}
],
StartTime=datetime.utcnow() - timedelta(hours=24),
MaxResults=50,
)
for event in response["Events"]:
print(f"{event['EventTime']} {event['Username']} {event['EventName']}")// --- TypeScript (AWS SDK v3) ---
import { CloudTrailClient, LookupEventsCommand } from "@aws-sdk/client-cloudtrail";
const client = new CloudTrailClient({});
const response = await client.send(new LookupEventsCommand({
LookupAttributes: [
{ AttributeKey: "ResourceName", AttributeValue: "acme-prod-reports" },
],
StartTime: new Date(Date.now() - 24 * 60 * 60 * 1000),
MaxResults: 50,
}));
for (const event of response.Events ?? []) {
console.log(event.EventTime, event.Username, event.EventName);
}What this demonstrates:
ResourceName filters events touching a specific resource, e.g. a bucket, instance, or IAM role name.LookupAttributes entry is allowed per call - you cannot combine ResourceName and EventName in a single filter.StartTime narrows the scan window, reducing pages and improving response latency.CloudTrailEvent JSON string per event with the full raw event detail beyond the summary fields.LookupEvents reads from CloudTrail's internally-managed event history, a rolling 90-day store maintained regardless of whether any trail exists.LookupAttributes filter per call, chosen from a fixed set of keys: EventId, EventName, ReadOnly, Username, ResourceType, ResourceName, EventSource, and AccessKeyId.Event has a summary shape (EventName, EventTime, Username, Resources) plus a CloudTrailEvent field containing the full event as a JSON string, which includes request parameters and response elements not in the summary.The summary fields cover the basics, but request parameters (like what an IAM CreatePolicy call actually contained) live in CloudTrailEvent.
# --- Python (boto3) ---
import json
for event in response["Events"]:
detail = json.loads(event["CloudTrailEvent"])
print(detail["sourceIPAddress"], detail.get("requestParameters"))// --- TypeScript (AWS SDK v3) ---
for (const event of response.Events ?? []) {
const detail = JSON.parse(event.CloudTrailEvent ?? "{}");
console.log(detail.sourceIPAddress, detail.requestParameters);
}| AttributeKey | Matches | Example Value |
|---|---|---|
EventName | Exact API operation name | ConsoleLogin, DeleteBucket |
Username | IAM user or assumed-role session name | deploy-bot, alice |
ResourceName | Name/ID of the resource acted on | acme-prod-reports |
ResourceType | AWS resource type | AWS::S3::Bucket |
EventSource | Service that emitted the event | s3.amazonaws.com |
AccessKeyId | Access key used for the call | AKIA... |
LookupAttributes can be combined - the API only accepts one filter per call; passing more raises a validation error. Fix: filter broadly on the one supported key, then narrow further client-side.LookupEvents silently returns nothing for a StartTime older than the retention window, with no error. Fix: check the window against 90 days first; use CloudTrail Lake for anything older.MaxResults page can miss most of the matching events in an active account. Fix: use the paginator (get_paginator("lookup_events") / paginateLookupEvents) for any non-trivial window.Resources/EventName alone often isn't enough to reconstruct what actually happened. Fix: parse CloudTrailEvent for the full JSON detail, including request parameters.ReadOnly filtering as data-event filtering - ReadOnly distinguishes read vs. write management events, it does not surface S3/Lambda data events, which LookupEvents doesn't cover at all. Fix: use a trail with data events enabled, queried via S3/Athena or Lake, for data-plane activity.| Alternative | Use When | Don't Use When |
|---|---|---|
LookupEvents (this page) | Quick queries within the last 90 days, no trail needed | You need retention or SQL-style filtering beyond 90 days |
CloudTrail Lake StartQuery | SQL joins/aggregations, long retention, complex filters | A single quick lookup answers the question |
| Athena over trail S3 logs | Ad hoc analysis you already run in Athena elsewhere | You don't already have an Athena/Glue setup for this |
| CloudWatch Logs Insights (if trail streams there) | Near-real-time queries with CloudWatch-native tooling | The trail isn't configured to stream to CloudWatch Logs |
No. LookupEvents queries CloudTrail's built-in 90-day event history, which exists independent of any trail.
Not in a single call - LookupAttributes accepts exactly one key/value pair per request. Combine filters by post-processing results client-side or making separate calls.
The call succeeds but returns no matching events for that range - there's no error, just an empty result for anything outside the retention window.
Parse the CloudTrailEvent field, a JSON string included with each event, which contains requestParameters, responseElements, and sourceIPAddress beyond the summary fields.
No. Those are data events, which LookupEvents doesn't surface at all - you'd need a trail with data events enabled, queried through S3/Athena or CloudTrail Lake.
You likely hit a single page's MaxResults limit. Use the paginator to walk every page for the requested time window.
LookupEvents calls and pagination pattern.Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Revisado por Chris St. John·Última atualização: 25 de jul. de 2026