Sub topic 9
Querying historical events with CloudTrail Lake and Athena
Event history only searches the last 90 days of management events, one attribute at a time. This chapter covers the two ways to run SQL over longer periods and over more event types: CloudTrail Lake and Amazon Athena reading the logs your trail delivers to S3.
It assumes you can read a CloudTrail event record, know the difference between management and data events, and have a trail delivering to S3. It also assumes you can run AWS CLI commands and read basic SQL (SELECT, WHERE, GROUP BY).
Why Event history is not enough
lookup-events has three limits that matter in an investigation:
- It covers only the past 90 days.
- It covers only management events.
- It filters on a single attribute, such as
EventNameorUsername. It cannot aggregate or join.
Questions like "which principals got AccessDenied on any S3 bucket last quarter?" need a query engine. You have two main options.
| Aspect | CloudTrail Lake | Athena over trail logs in S3 |
|---|---|---|
| Storage | Managed event data store | Your S3 bucket (the trail's logs) |
| Setup | Create an event data store | Create a table over the S3 prefix |
| Retention | You set it on the data store | You control it with S3 lifecycle rules |
| Query cost | Charged by data scanned | Charged by data scanned by Athena |
| Ingestion cost | Charged per GB ingested | None beyond the trail and S3 |
| Event types | Management, data, Insights, and others, chosen per data store | Whatever the trail records |
| Retroactive | No, only events from creation (or imported) | Yes, anything already in the bucket |
Choose Lake when you want fast setup and a managed store. Choose Athena when logs are already in S3 and you want to avoid a second copy.
CloudTrail Lake
Event data stores
CloudTrail Lake is a managed data lake for CloudTrail events. The unit of storage is an event data store. It holds events you select with advanced event selectors, the same selector style a trail uses. It keeps them for the retention period you set. You then query it with SQL.
Create one with the CLI:
aws cloudtrail create-event-data-store \
--name org-audit-store \
--multi-region-enabled \
--retention-period 365The response includes an EventDataStoreArn. The last segment of that ARN is the event data store ID. You use the ID as the table name in queries.
Writing queries
Lake accepts a read-only SQL dialect. Besides SELECT, it supports WITH and JOIN for combining data stores. Nested fields use dot notation, for example userIdentity.arn.
This query lists the most frequent API calls made by IAM users since the start of the month:
SELECT eventName, COUNT(*) AS calls
FROM <event-data-store-id>
WHERE eventTime > '2026-11-01 00:00:00'
AND userIdentity.type = 'IAMUser'
GROUP BY eventName
ORDER BY calls DESC
LIMIT 10Always put an eventTime condition in the WHERE clause. Lake charges by the amount of data a query scans, and a time bound limits that.
Run a query from the CLI with start-query, then fetch results with the returned query ID:
aws cloudtrail start-query \
--query-statement "SELECT userIdentity.arn, eventName, errorCode FROM <event-data-store-id> WHERE errorCode = 'AccessDenied' AND eventTime > '2026-11-01 00:00:00' LIMIT 50"
aws cloudtrail get-query-results --query-id <query-id>Queries run asynchronously. get-query-results reports a status such as QUEUED, RUNNING, or FINISHED. Call it again until the status is FINISHED.
Lake limits to know
- An event data store records events only from the time you create it. For earlier events, copy or import them from an existing trail's S3 logs.
- Each data store captures the event categories you select. Data events are not captured unless you add them.
- Lake queries are read-only. You cannot delete or edit events.
Athena over trail logs in S3
Athena is a serverless SQL engine that reads files directly from S3. The trail already writes compressed JSON files under a predictable prefix, so you need only a table definition that tells Athena how to read them.
Why partitioning matters
CloudTrail files are laid out like this:
s3://BUCKET/AWSLogs/ACCOUNT_ID/CloudTrail/REGION/YYYY/MM/DD/file.json.gzWithout partitions, Athena scans every file under the prefix on every query, which is slow and expensive. Partition projection solves this. You tell Athena that the date folders follow a pattern, and it computes the partitions itself. You do not need to run MSCK REPAIR TABLE or add partitions by hand.
Creating the table
This definition is trimmed to commonly used columns. It uses the CloudTrail SerDe, which maps the JSON fields to columns by name:
CREATE EXTERNAL TABLE cloudtrail_logs (
eventVersion STRING,
userIdentity STRUCT<
type: STRING,
principalId: STRING,
arn: STRING,
accountId: STRING,
accessKeyId: STRING,
userName: STRING
>,
eventTime STRING,
eventSource STRING,
eventName STRING,
awsRegion STRING,
sourceIpAddress STRING,
userAgent STRING,
errorCode STRING,
errorMessage STRING,
requestParameters STRING,
responseElements STRING,
readOnly STRING,
eventType STRING,
recipientAccountId STRING
)
PARTITIONED BY (`timestamp` STRING)
ROW FORMAT SERDE 'com.amazon.emr.hive.serde.CloudTrailSerde'
STORED AS INPUTFORMAT 'com.amazon.emr.cloudtrail.CloudTrailInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION 's3://my-cloudtrail-logs-bucket/AWSLogs/123456789012/CloudTrail/us-east-1/'
TBLPROPERTIES (
'projection.enabled' = 'true',
'projection.timestamp.type' = 'date',
'projection.timestamp.format' = 'yyyy/MM/dd',
'projection.timestamp.interval' = '1',
'projection.timestamp.interval.unit' = 'DAYS',
'projection.timestamp.range' = '2026/11/01,NOW',
'storage.location.template' = 's3://my-cloudtrail-logs-bucket/AWSLogs/123456789012/CloudTrail/us-east-1/${timestamp}'
)Adjust the bucket name, account ID, Region, and start date to match your trail. The CloudTrail console can also generate a table for you from a trail's event history page, which is a good way to check your definition against the current schema.
Querying with a partition filter
Always filter on the partition column. The filter below limits the scan to three days of files:
SELECT eventTime, userIdentity.arn, eventName, sourceIpAddress
FROM cloudtrail_logs
WHERE "timestamp" BETWEEN '2026/11/18' AND '2026/11/20'
AND eventName = 'StopLogging'
ORDER BY eventTimeNote that eventTime is a string here. ISO 8601 timestamps sort correctly as text, so ordering works, but use from_iso8601_timestamp(eventTime) when you need date arithmetic.
Reading nested JSON
The trimmed table keeps requestParameters and responseElements as strings, because their shape differs for every API. Extract values with JSON functions:
SELECT eventTime,
userIdentity.arn AS actor,
json_extract_scalar(requestParameters, '$.name') AS trail_name
FROM cloudtrail_logs
WHERE "timestamp" >= '2026/11/01'
AND eventSource = 'cloudtrail.amazonaws.com'
AND eventName IN ('StopLogging', 'DeleteTrail', 'UpdateTrail')Choosing between them
Many teams run both: a trail delivers to S3 for long-term, low-cost storage and integrity validation, and a Lake data store handles day-to-day investigation queries.
Useful investigation queries
These patterns work in either engine with small syntax changes. The Athena versions need the partition filter.
Failed calls by principal
Repeated AccessDenied or UnauthorizedOperation errors from one principal often mean credential misuse or probing:
SELECT userIdentity.arn AS actor,
eventName,
errorCode,
COUNT(*) AS attempts
FROM cloudtrail_logs
WHERE "timestamp" >= '2026/11/01'
AND errorCode IN ('AccessDenied', 'Client.UnauthorizedOperation')
GROUP BY userIdentity.arn, eventName, errorCode
ORDER BY attempts DESC
LIMIT 20Console sign-ins from unusual addresses
SELECT eventTime, userIdentity.arn, sourceIpAddress, userAgent
FROM cloudtrail_logs
WHERE "timestamp" >= '2026/11/01'
AND eventName = 'ConsoleLogin'
ORDER BY eventTime DESCCommon errors
- Zero rows in Athena. The usual cause is a partition range that does not include the dates you queried, or a
LOCATIONthat does not match the real prefix. Check the Region folder and the account ID. - Slow, costly Athena queries. You omitted the partition filter. Add a
"timestamp"condition. - Missing events in Lake. The event data store was created after the event happened, or its selectors exclude that category. Check the selectors and the creation date.
- Trail in another Region or account. The table points at one Region and one account prefix. Organization trails write under the organization ID prefix first, so adjust
LOCATIONand the template. - Query fails on a field. Some fields exist only on certain event types. Test with
LIMIT 5before running a broad scan.
Exercises
Exercise
An Athena query over your CloudTrail table returns correct results but takes several minutes and scans far more data than expected. What is the most likely cause, and how do you fix it?
Show answer
The query has no filter on the partition column, so Athena scans every file under the table's location. Add a condition on the partition column, for example WHERE "timestamp" BETWEEN '2026/11/18' AND '2026/11/20', and make sure partition projection is enabled so Athena can prune the date folders.
Exercise
You created a CloudTrail Lake event data store today. Your manager asks you to find who deleted a bucket policy three weeks ago. Why might the query return nothing, and what are two ways to still answer the question?
Show answer
An event data store only collects events from the moment it is created, so earlier events are not in it. You can query the trail's S3 logs with Athena, or use lookup-events in Event history (which holds 90 days of management events). You could also import the older events from the trail's S3 logs into a data store.