AWS CloudTrail
LearningTree ยท AWS ยท Management

AWS CloudTrail โ€”
Governance, Compliance & Audit

CloudTrail is the flight recorder for your AWS account. Every API call โ€” console, CLI, SDK, or service-to-service โ€” is captured, timestamped, and stored. It answers the fundamental question: "who did what, when, and from where?"

01
Chapter One ยท Management

What is AWS CloudTrail?

AWS CloudTrail is a governance, compliance, and audit service that continuously records API activity across your AWS infrastructure. Think of it as CCTV for your cloud โ€” every action taken by users, roles, or AWS services is logged as an event.

Mental Model โ€” The Flight Recorder Introductory
โœˆ๏ธ

Aircraft Black Box

  • Records every cockpit action automatically
  • Cannot be tampered with by pilots
  • Used after incidents to understand what happened
  • Always on โ€” you don't choose when to record
โ˜๏ธ

CloudTrail

  • Records every AWS API call automatically
  • Log integrity validation prevents tampering
  • Used for security investigation and compliance proof
  • Always on (90-day Event History) โ€” trails extend retention
CloudTrail vs CloudWatch vs AWS Config Core
ServiceWhat It AnswersFocus
CloudTrailWho did what, when, from where?API activity audit trail
CloudWatchHow is the resource performing?Metrics, logs, alarms, dashboards
AWS ConfigWhat is the resource's configuration (and has it changed)?Configuration history & compliance rules
๐Ÿง  Key Distinction

CloudTrail = "Who deleted the S3 bucket at 3 AM?" CloudWatch = "Is the CPU utilisation above 80%?" Config = "Is the S3 bucket currently public, and when did it change?" All three work together but serve different purposes.

What CloudTrail Records Introductory

Every CloudTrail event (API call record) contains:

๐Ÿ‘ค

Identity

  • IAM user or role ARN
  • Federated identity details
  • Source IP address
  • User agent (Console/CLI/SDK)
๐Ÿ”ง

Action

  • API action name (e.g., RunInstances)
  • Service name (e.g., ec2.amazonaws.com)
  • Request parameters
  • Response elements
โฑ๏ธ

Context

  • Timestamp (UTC)
  • AWS region
  • Resource ARNs affected
  • Error code (if denied)
๐ŸŽฏ Exam Insight
  • "Who terminated the EC2 instance?" โ†’ CloudTrail
  • "What is the current configuration of the security group?" โ†’ AWS Config
  • "Is CPU above 80%?" โ†’ CloudWatch
  • "Audit all API calls for compliance" โ†’ CloudTrail
  • "Default CloudTrail retention" โ†’ 90 days (Event History, free, management events only)
Chapter 01 โ€” Key Takeaway

CloudTrail records WHO did WHAT, WHEN, and FROM WHERE for every API call in your account. It's always on (90-day Event History free). CloudTrail = audit trail, CloudWatch = performance monitoring, Config = configuration compliance. Together they form the three pillars of AWS observability and governance.

02
Chapter Two ยท Management

CloudTrail Events & Trail Types

CloudTrail categorises API activity into three event types โ€” Management Events, Data Events, and Insights Events. Understanding the distinction is critical for both cost management and security coverage.

Event Types Core
โš™๏ธ

Management Events

  • Also called control plane operations
  • Create/modify/delete resources
  • CreateBucket, RunInstances, AttachRolePolicy
  • Logged by default (free in Event History)
  • Read (Describe/List) + Write (Create/Delete) separation
๐Ÿ“ฆ

Data Events

  • Also called data plane operations
  • Operations on resources (high volume)
  • GetObject, PutObject (S3), Invoke (Lambda)
  • Not logged by default (must enable explicitly)
  • Can generate millions of events/day (costly)
๐Ÿง 

Insights Events

  • ML-powered anomaly detection
  • Detects unusual volume of API calls
  • "100ร— more TerminateInstances than baseline"
  • Not enabled by default
  • Separate charge โ€” helps detect compromised credentials
Event History vs Trail Core
FeatureEvent History (Default)Trail (You Create)
CostFreeFree for first management trail; data/insights events charged
Retention90 daysUnlimited (stored in S3)
Event typesManagement events onlyManagement + Data + Insights (configurable)
RegionsCurrent region onlySingle-region or multi-region
DeliveryConsole/API onlyS3 bucket + optional CloudWatch Logs + SNS
Log integrityN/ADigest files for tamper detection
OrganisationPer accountOrganisation trail (all accounts)
โš ๏ธ Critical Exam Point

Event History keeps only 90 days of management events. For compliance requiring longer retention, data events, or cross-region/cross-account visibility, you must create a trail. The first copy of management events delivered to S3 is free โ€” additional copies and data events are charged.

Trail Scope Options Core
๐ŸŒ

Multi-Region Trail (Recommended)

  • Captures events from all regions
  • Includes global services (IAM, STS, CloudFront)
  • Single S3 bucket receives all logs
  • If a new region is launched โ†’ auto-included
  • Best practice for security and compliance
๐Ÿข

Organisation Trail

  • Created in management account
  • Applies to all member accounts
  • Centralises audit in one S3 bucket
  • Member accounts can see the trail but cannot modify/delete
  • Recommended for enterprises
Global Services โ€” The us-east-1 Rule Core

Global services (IAM, STS, CloudFront, WAF, Route 53) operate outside any specific region. CloudTrail handles them specially:

โš ๏ธ

Single-Region Trail (Not us-east-1)

  • Trail in eu-west-1 โ†’ NO IAM events
  • Trail in ap-southeast-1 โ†’ NO STS events
  • Global service events are only delivered to us-east-1
  • Common exam trap: "Why are IAM events missing?"
โœ…

Multi-Region Trail (Best Practice)

  • Captures all regions + global services
  • Global events appear with awsRegion: "us-east-1"
  • No gaps in audit coverage
  • Always use multi-region for production
๐ŸŽฏ Exam Trap

"Why are my IAM events missing from the trail?" โ†’ Trail is single-region in eu-west-1. Global service events (IAM, STS, CloudFront) are only logged to us-east-1. Fix: convert to multi-region trail OR create additional trail in us-east-1.

LookupEvents API โ€” Programmatic Search Core

The LookupEvents API lets you search CloudTrail events programmatically โ€” no S3, Athena, or Lake setup needed.

FeatureDetails
WindowLast 90 days (Event History only)
Event typesManagement events only (no Data events)
CostFree (no additional charges)
ResultsMax 50 per page (paginated)
FilterseventName, eventSource, resourceName, resourceType, username, time range
๐Ÿ“ CLI Example

aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=DeleteBucket --start-time "2026-05-01" --end-time "2026-05-07" --max-results 50

Use cases: Security automation scripts, CI/CD validation, quick incident investigation, compliance spot-checks. Limitation: Not suitable for high-volume queries or complex aggregation โ€” use Athena or Lake for those.

CloudTrail Event Record โ€” Anatomy In-Depth
๐Ÿ“„ Sample Event Record (Simplified)

eventTime: "2026-05-07T14:23:01Z"
eventSource: "s3.amazonaws.com"
eventName: "DeleteBucket"
userIdentity.arn: "arn:aws:iam::123456789012:user/alice"
sourceIPAddress: "203.0.113.42"
userAgent: "aws-cli/2.15.0"
requestParameters.bucketName: "my-production-data"
responseElements: null
errorCode: null (success) or "AccessDenied"

๐ŸŽฏ Exam Insight
  • "Log S3 object-level access" โ†’ Enable data events for S3 (not on by default)
  • "Log Lambda invocations" โ†’ Enable data events for Lambda
  • "Detect unusual API call volume" โ†’ Enable CloudTrail Insights
  • "Global services (IAM, STS)" โ†’ Only captured by multi-region trail (or us-east-1 single-region trail)
  • "Retain audit logs for 7 years" โ†’ Create a trail โ†’ S3 bucket with lifecycle (โ†’ Glacier)
  • "All accounts in organisation" โ†’ Organisation trail from management account
Chapter 02 โ€” Key Takeaway

Management events (control plane) are logged free for 90 days. Data events (S3 GetObject, Lambda Invoke) must be explicitly enabled and incur cost. Insights events use ML to detect anomalous API volume. Trails store events in S3 for unlimited retention โ€” always create a multi-region trail for production. Organisation trails centralise audit across all accounts.

03
Chapter Three ยท Management

Trail Configuration & Delivery

Configuring a trail involves choosing what to log, where to deliver, and how to protect the logs. Get this right and you have an immutable, queryable audit trail for any compliance framework.

Trail Delivery Architecture Core
CloudTrail โ€” Event Delivery Pipeline
API Calls Console / CLI SDK / Services All regions Filter: Mgmt / Data Insights analysis Digest generation ~5-15 min delivery Amazon S3 Long-term storage SSE-S3 or SSE-KMS CW Logs Real-time alerting SNS Topic Notification on delivery CW Alarm Security alerts Athena SQL queries on logs Trail delivers events to S3 (always) + optional CloudWatch Logs + SNS. Query with Athena or CloudTrail Lake.
Delivery Destinations Core
DestinationPurposeLatency
S3 BucketPrimary storage โ€” long-term archival, Athena queries~5โ€“15 min after API call
CloudWatch LogsReal-time metric filters โ†’ alarms (detect root login, IAM changes)~5 min
SNS TopicNotification when new log file delivered to S3~5โ€“15 min
CloudTrail LakeManaged SQL query engine (no S3/Athena setup needed)Near real-time
S3 Bucket Configuration Core
๐Ÿ”

Security Best Practices

  • Separate account โ€” store logs in a dedicated security/log account
  • SSE-KMS encryption โ€” encrypt with customer-managed KMS key
  • Bucket policy โ€” only CloudTrail service can write; prevent delete
  • Object Lock โ€” WORM (Write Once Read Many) for compliance
  • MFA Delete โ€” require MFA to delete log objects
  • Versioning โ€” always enable to prevent overwrite
๐Ÿ“

Log File Structure

  • s3://bucket/AWSLogs/account-id/CloudTrail/region/yyyy/mm/dd/
  • Files are gzipped JSON
  • Multiple events per file (batched)
  • Digest files delivered hourly (for integrity validation)
  • Use S3 lifecycle โ†’ Glacier after 90 days for cost savings
CloudTrail Lake In-Depth

CloudTrail Lake is a managed, immutable data lake that lets you run SQL queries on CloudTrail events without setting up S3 + Athena. Events are stored in a purpose-built event data store.

๐Ÿ—„๏ธ

Lake Features

  • SQL-based query language
  • 7-year default retention (configurable: 7 days โ€“ 7 years)
  • Cross-account event aggregation
  • No S3/Glue/Athena setup required
  • Can import non-AWS events (custom integrations)
๐Ÿ’ฐ

Lake Pricing

  • Ingestion: $2.50 per GB ingested
  • Retention: $0.023/GB/month (after 7 years: tiered)
  • Queries: $0.005 per GB scanned
  • More expensive than S3+Athena for large volumes
  • Better for teams wanting zero-ops querying
CloudTrail Lake vs S3 + Athena โ€” Decision In-Depth
FactorS3 + AthenaCloudTrail Lake
Setup time15โ€“30 min (create table, partition)2 minutes (choose retention)
Partition managementManual or partition projectionAutomatic
Query performanceDepends on partitioning strategyOptimised for time-range queries
PricingS3 ($0.023/GB) + Athena ($5/TB scanned)Ingestion ($2.50/GB) + queries ($0.005/GB)
Cross-accountRequires Lake Formation setupBuilt-in event data store sharing
Non-AWS eventsNot supportedYes โ€” custom integrations (SaaS)
Long-term archivalS3 lifecycle โ†’ Glacier ($0.004/GB)Same rate regardless of age ($0.023/GB)
โœ…

Use CloudTrail Lake When

  • Team lacks Athena/Glue expertise
  • Need cross-account queries built-in
  • Including non-AWS audit logs (SaaS, on-prem)
  • Total archive under 1 TB (cost acceptable)
  • Zero-ops priority over cost optimisation
๐Ÿ’ฐ

Use S3 + Athena When

  • High-volume logs (>10 GB/day) โ€” scanning is cheaper
  • Already have Athena/Glue infrastructure
  • Long-term retention (Glacier = 20ร— cheaper than Lake)
  • Cost-sensitive for large data volumes
  • Need custom partitioning strategies
๐Ÿ’ฐ Cost Comparison โ€” 100 GB/day (3 TB/month)

CloudTrail Lake: 3,000 GB ร— $2.50 ingestion = $7,500/month. S3 + Athena: 3,000 GB ร— $0.023 storage = $69/month + Athena queries. Move to Glacier after 90 days โ†’ $0.004/GB. Lake is 100ร— more expensive at this volume. Best practice: Use Lake for selective security events only; use S3+Athena for full archive.

๐ŸŽฏ Exam Insight
  • "Query CloudTrail without Athena setup" โ†’ CloudTrail Lake
  • "Log delivery time" โ†’ ~5โ€“15 minutes (NOT real-time)
  • "Real-time alerting on API calls" โ†’ Trail โ†’ CloudWatch Logs โ†’ metric filter โ†’ alarm
  • "Prevent log deletion" โ†’ S3 Object Lock (WORM) + MFA Delete
  • "Encrypt trail logs" โ†’ SSE-KMS (customer-managed key recommended)
  • "Cross-account log storage" โ†’ Configure trail to deliver to S3 bucket in security account (bucket policy must allow)
  • "10 TB/year for 7 years cheaply" โ†’ S3 + lifecycle to Glacier Deep Archive (NOT Lake โ€” cost prohibitive)
  • "Zero-ops cross-account query" โ†’ CloudTrail Lake with org event data store
Chapter 03 โ€” Key Takeaway

A trail delivers events to S3 (primary storage, ~15 min delay), optionally to CloudWatch Logs (for real-time alerting), and SNS (for notifications). Protect the S3 bucket with encryption (KMS), versioning, Object Lock, and MFA Delete. Use Athena for SQL queries on S3 logs or CloudTrail Lake for zero-ops querying. Always store logs in a separate security account for defence in depth.

04
Chapter Four ยท Management

Security, Integrity & Compliance

CloudTrail's value depends entirely on trust in the logs. If an attacker can modify or delete audit records, they're worthless. AWS provides multiple mechanisms to ensure log immutability and detect tampering.

Log File Integrity Validation Core
Digest File โ€” Integrity Validation Chain
Log Files (hourly) SHA-256 hash of each file computed Digest File (hourly) Contains hashes of all log files + prev digest hash RSA Signature AWS signs each digest with private key Validate aws cloudtrail validate-logs Chain of digests = blockchain-like integrity. If any log file is modified/deleted, validation fails.

How it works:

  1. CloudTrail computes SHA-256 hash for each log file delivered to S3
  2. Every hour, a digest file is created containing all log file hashes + the hash of the previous digest (chain)
  3. Each digest is signed with an AWS RSA private key
  4. Run aws cloudtrail validate-logs to verify the entire chain โ€” detects modifications, deletions, or insertions
Security Best Practices Core
๐Ÿ›ก๏ธ

Protect the Trail

  • Enable log file integrity โ€” always (detect tampering)
  • Separate security account โ€” logs can't be deleted by compromised account
  • S3 Object Lock (Compliance mode) โ€” even root can't delete
  • SSE-KMS encryption โ€” key policy restricts decryption
  • Deny cloudtrail:StopLogging โ€” SCP in Organizations
  • CloudWatch alarm โ€” alert on StopLogging/DeleteTrail API calls
โš ๏ธ

Attack Vectors to Prevent

  • StopLogging โ€” attacker disables trail before malicious actions
  • DeleteTrail โ€” destroy the audit mechanism entirely
  • Delete S3 objects โ€” remove evidence after the fact
  • Modify bucket policy โ€” redirect logs elsewhere
  • Put lifecycle rule โ€” auto-delete logs after 1 day
  • Disable KMS key โ€” make logs unreadable
CloudTrail + CloudWatch Logs โ€” Security Alerting Core

Sending CloudTrail events to CloudWatch Logs enables real-time security alerting via metric filters:

Alert OnMetric Filter PatternWhy
Root account login{"$.userIdentity.type" = "Root"}Root should never be used for daily operations
Console login without MFA{"$.eventName" = "ConsoleLogin" && $.additionalEventData.MFAUsed != "Yes"}MFA bypass attempt
IAM policy changes{"$.eventName" = "Put*Policy" || $.eventName = "Attach*Policy"}Privilege escalation
Security group changes{"$.eventName" = "AuthorizeSecurityGroup*" || $.eventName = "RevokeSecurityGroup*"}Network exposure
Trail stopped{"$.eventName" = "StopLogging" || $.eventName = "DeleteTrail"}Evidence destruction
Failed sign-in attempts{"$.eventName" = "ConsoleLogin" && $.errorMessage = "Failed*"}Brute force detection
โœ… CIS AWS Benchmark

The CIS AWS Foundations Benchmark requires CloudTrail metric filters for: root login, IAM changes, CloudTrail config changes, console auth failures, CMK deletion, S3 bucket policy changes, VPC changes, and more. This is a common compliance framework tested in AWS exams.

Compliance Frameworks Supported Introductory
๐Ÿ“‹

SOC 2

CloudTrail provides audit evidence for access control and change management requirements

๐Ÿฅ

HIPAA

PHI access logging โ€” who accessed health data resources and when

๐Ÿ’ณ

PCI DSS

Requirement 10: track all access to cardholder data environments

๐Ÿ‡ช๐Ÿ‡บ

GDPR

Demonstrate who accessed personal data and when for data subject requests

๐Ÿ›๏ธ

FedRAMP / GovCloud

Federal audit requirements โ€” immutable logging with integrity validation

๐Ÿ”’

ISO 27001

Control A.12.4 โ€” logging and monitoring of information processing activities

๐ŸŽฏ Exam Insight
  • "Prove logs haven't been tampered with" โ†’ Enable log file integrity validation + validate-logs CLI command
  • "Prevent anyone from disabling CloudTrail" โ†’ SCP denying cloudtrail:StopLogging and cloudtrail:DeleteTrail
  • "Alert when root account is used" โ†’ CloudTrail โ†’ CloudWatch Logs โ†’ metric filter on Root identity โ†’ alarm
  • "Immutable log storage for compliance" โ†’ S3 Object Lock in Compliance mode (even root can't delete within retention)
  • "CIS Benchmark foundational control" โ†’ Multi-region trail + log integrity + CW metric filters for critical events
Chapter 04 โ€” Key Takeaway

CloudTrail integrity validation uses a chain of SHA-256 digests signed by AWS โ€” like a blockchain for audit logs. Protect trails with: separate security account, S3 Object Lock, MFA Delete, KMS encryption, and SCPs preventing StopLogging. Send events to CloudWatch Logs for real-time alerting on security-critical actions (root login, IAM changes, trail modification). This pattern satisfies CIS, SOC 2, HIPAA, PCI DSS, and other compliance frameworks.

05
Chapter Five ยท Management

Integration Patterns & Cost Optimisation

CloudTrail integrates deeply with the AWS ecosystem โ€” from EventBridge for real-time reactions to Athena for investigation to Organizations for enterprise governance. Understanding integration patterns and cost levers is essential for production deployments.

EventBridge Integration Core

Every management event delivered to CloudTrail is also emitted to Amazon EventBridge (default event bus) in near real-time. This enables instant automated responses:

CloudTrail + EventBridge โ€” Real-Time Automation
API Call e.g., DeleteBucket Records event Pattern match rule Lambda (auto-remediate) SNS (alert team) Step Functions (workflow) EventBridge receives CloudTrail events in near real-time โ€” faster than CW Logs metric filters

Common EventBridge rules triggered by CloudTrail events:

  • Auto-remediation: S3 bucket made public โ†’ Lambda removes public access immediately
  • Compliance enforcement: Security group opened to 0.0.0.0/0 โ†’ Lambda revokes the rule
  • Notification: IAM user created โ†’ SNS alert to security team
  • Workflow: EC2 instance launched without tags โ†’ Step Functions workflow adds mandatory tags
โšก EventBridge vs CloudWatch Logs for Alerting

EventBridge is faster (seconds) and pattern-matches JSON natively โ€” ideal for automated responses. CloudWatch Logs metric filters are better for aggregate counting and threshold-based alarms (e.g., "more than 5 failed logins in 10 minutes"). Use both together for defence in depth.

Querying CloudTrail with Athena Core

For ad-hoc investigation of historical events in S3, use Amazon Athena (serverless SQL engine):

๐Ÿ”

Setup

  • CloudTrail console โ†’ "Create Athena table" (auto-generates DDL)
  • Partition by region/year/month/day for performance
  • Use partition projection to avoid MSCK REPAIR TABLE
  • Pay only for data scanned ($5/TB)
๐Ÿ“

Common Queries

  • "Who deleted S3 bucket X?" โ†’ filter on eventName + requestParameters
  • "All API calls from IP Y" โ†’ filter on sourceIPAddress
  • "Failed access attempts in last 7 days" โ†’ filter on errorCode
  • "All IAM changes this month" โ†’ filter on eventSource = iam
CloudTrail + AWS Organizations In-Depth
FeatureDetails
Organisation TrailCreated in management account โ€” applies to all member accounts automatically
Delegated AdminDesignate a security account to manage trails (doesn't need management account access)
SCPs for ProtectionDeny StopLogging, DeleteTrail, UpdateTrail for all accounts except security team
CloudTrail Lake (Org)Aggregate events from all accounts into one event data store
Central S3 BucketAll accounts deliver to one bucket in security account โ€” bucket policy lists all account IDs
CloudTrail Insights โ€” Anomaly Detection In-Depth

CloudTrail Insights analyses management event patterns and alerts when API call volumes deviate significantly from your baseline:

๐Ÿง 

How Insights Works

  • Establishes a baseline of normal API call rates (7-day learning)
  • Detects spikes: e.g., 100ร— normal TerminateInstances calls
  • Generates Insights event with: baseline rate, anomaly rate, period
  • Delivered to S3 (separate prefix) and optionally EventBridge
๐Ÿšจ

Detection Examples

  • Credential compromise โ€” sudden burst of DescribeInstances across regions
  • Misconfigured automation โ€” RunInstances looping due to bug
  • Denial of wallet โ€” massive resource creation driving up costs
  • Data exfiltration attempt โ€” unusual GetObject volume
CloudTrail Pricing Core
ComponentCostNotes
Event History (90 days)FreeManagement events only, per-region view
First trail (management events)Free delivery to S3First copy free; S3 storage costs apply
Additional trail copies$2.00 per 100K eventsSecond+ trails delivering same events
Data events$0.10 per 100K eventsS3 object / Lambda invoke events
Insights events$0.35 per 100K events analysedOnly charged when anomalies found
CloudTrail Lake ingestion$2.50 per GBHigher than S3 but zero-ops
CloudTrail Lake queries$0.005 per GB scannedSame as Athena pricing
Cost Optimisation In-Depth
๐Ÿ’ฐ

Save on Storage

  • S3 Lifecycle rules โ€” move logs to Glacier after 90 days, Deep Archive after 1 year
  • S3 Intelligent Tiering โ€” auto-tier based on access patterns
  • Avoid duplicate trails โ€” one multi-region trail per account (or org trail)
  • Compress โ€” logs are gzipped by default (already optimised)
๐Ÿ“‰

Save on Events

  • Filter data events โ€” log only specific S3 buckets, not all
  • Exclude read events โ€” if compliance only requires write events
  • Use advanced event selectors โ€” fine-grained resource-level filtering
  • Evaluate Insights cost โ€” disable if baseline is stable enough
Advanced Event Selectors โ€” Cost-Saving Patterns In-Depth

Advanced event selectors replace the older "basic" selectors and provide fine-grained control over which events a trail records. They support: Equals, NotEquals, StartsWith, EndsWith.

Selector FieldOperatorsExample
eventCategoryEqualsData or Management
resources.typeEqualsAWS::S3::Object, AWS::Lambda::Function
resources.ARNStartsWith, Equalsarn:aws:s3:::my-sensitive-bucket/
readOnlyEqualstrue (reads) or false (writes)
eventNameEquals, NotEqualsPutObject, DeleteObject
eventSourceEquals, NotEqualss3.amazonaws.com
๐Ÿ’ฐ

Pattern 1 โ€” Sensitive Buckets Only

  • eventCategory = Data
  • resources.type = AWS::S3::Object
  • resources.ARN StartsWith arn:aws:s3:::customer-pii/
  • readOnly = false (writes only)
  • Result: 95% cost reduction vs logging all S3
๐Ÿ“‰

Pattern 2 โ€” Exclude Noisy Services

  • eventCategory = Management
  • eventSource NotEquals:
    • monitoring.amazonaws.com
    • trustedadvisor.amazonaws.com
  • Result: Cleaner logs, lower noise
๐Ÿ’ก Cost Example

An application makes 10M S3 GetObject calls/month. Logging all S3 data events = $10/month. Using advanced selectors to log only PutObject and DeleteObject on 2 sensitive buckets might reduce events by 95% โ†’ $0.50/month. Always scope data events to what compliance requires.

EventBridge Pattern Matching โ€” Examples In-Depth

CloudTrail events appear in EventBridge with source = "aws.cloudtrail". The detail field contains the full event. Here are production-ready patterns:

๐Ÿšจ

Root Login Detection

  • source: aws.cloudtrail
  • detail.userIdentity.type: Root
  • detail.eventName: ConsoleLogin
  • Action: SNS โ†’ page security team
๐Ÿ—‘๏ธ

S3 Bucket Deletion

  • source: aws.cloudtrail
  • detail.eventSource: s3.amazonaws.com
  • detail.eventName: DeleteBucket
  • Action: Lambda โ†’ verify if intentional
๐Ÿ”‘

IAM Privilege Escalation

  • source: aws.cloudtrail
  • detail.eventSource: iam.amazonaws.com
  • detail.eventName: CreateRole, AttachRolePolicy, PutRolePolicy
  • Action: Step Functions โ†’ investigation workflow
๐Ÿ›ก๏ธ

Trail Modification

  • source: aws.cloudtrail
  • detail.eventSource: cloudtrail.amazonaws.com
  • detail.eventName: StopLogging, DeleteTrail, UpdateTrail
  • Action: Lambda โ†’ re-enable + alert
EventBridge Field Reference Core
Field PathWhat It ContainsPattern Matching
detail.eventSourceService called (e.g., s3.amazonaws.com)Equals
detail.eventNameAPI action (e.g., DeleteBucket)Equals, anything-but
detail.userIdentity.typeRoot, IAMUser, AssumedRole, AWSServiceEquals
detail.userIdentity.arnFull ARN of callerPrefix
detail.sourceIPAddressOriginating IP or AWS service nameEquals, prefix
detail.errorCodeAccessDenied, null (success)Exists, equals
detail.readOnlytrue (read) / false (write)Equals
detail.awsRegionRegion of call (us-east-1 for global)Equals
โšก Speed Comparison

EventBridge: receives CloudTrail events in seconds (near real-time). CloudWatch Logs metric filters: ~5 minutes delay. For automated security responses (auto-remediation, instant alerts), always prefer EventBridge rules.

Query Method Decision Matrix Core
Use CaseBest ToolWhy
"Did user X do action Y in last 3 days?"LookupEvents APIFree, simple, programmatic
"Who deleted S3 bucket Z last month?"Athena on S3Cost-effective for historical data
"Count failed logins by user per day"Athena (aggregation)GROUP BY, stats, complex queries
"Investigate compromised user across accounts"CloudTrail LakeCross-account, JOINs, zero-ops
"Trace attacker path through services"Amazon DetectiveVisualises relationships from CloudTrail
"Real-time alert when bucket deleted"EventBridge ruleSub-second automated response
"Search 10 accounts for specific API"CloudTrail Lake (Org)Built-in cross-account queries
"Cheapest 7-year audit compliance"S3 โ†’ Glacier Deep Archive$0.004/GB โ€” 50ร— cheaper than Lake
CloudTrail vs GuardDuty vs Detective Core
ServicePurposeHow It Relates to CloudTrail
CloudTrailRecord all API calls (the raw data)โ€”
GuardDutyML-powered threat detectionAnalyses CloudTrail events + VPC Flow Logs + DNS to find threats
DetectiveInvestigation and root cause analysisVisualises CloudTrail data to trace attacker activity
Security HubCentralised security findingsAggregates findings from GuardDuty, Config, etc.
๐ŸŽฏ Exam Insight
  • "Automated response to API event" โ†’ CloudTrail โ†’ EventBridge rule โ†’ Lambda/SNS/Step Functions
  • "Query who did what last month" โ†’ Athena on CloudTrail S3 logs (or CloudTrail Lake SQL)
  • "Detect compromised credentials" โ†’ CloudTrail Insights (unusual API volume) or GuardDuty
  • "Cost of logging all S3 access" โ†’ Data events at $0.10/100K events โ€” use advanced selectors to filter
  • "Organisation-wide audit" โ†’ Organisation trail + delegated admin + SCP protection
  • "Real-time response (seconds)" โ†’ EventBridge (not CloudWatch Logs which is minutes)
  • "Long-term retention cheaply" โ†’ S3 + lifecycle to Glacier (not CloudTrail Lake which is $2.50/GB)
  • "Non-AWS events in CloudTrail" โ†’ CloudTrail Lake custom integrations (SaaS audit logs)
  • "Quick programmatic check (90 days)" โ†’ LookupEvents API (free, management events only)
  • "Log only PutObject to specific bucket" โ†’ Advanced selector: eventCategory=Data, resources.type=S3::Object, ARN StartsWith, eventName=PutObject
  • "Global services missing from trail" โ†’ Trail is single-region not in us-east-1. Fix: multi-region trail
Chapter 05 โ€” Key Takeaway

CloudTrail integrates with EventBridge for real-time automated responses (faster than CloudWatch Logs). Use Athena for SQL investigation on S3 logs; CloudTrail Lake for zero-ops querying. Organisation trails centralise audit across all accounts โ€” protect with SCPs. Insights detects anomalous API patterns. Control costs with advanced event selectors (scope data events to specific buckets/functions) and S3 lifecycle rules (Glacier after 90 days). GuardDuty and Detective consume CloudTrail data for threat detection and investigation.

CloudTrail โ€” Complete Domain Summary

  • Purpose โ€” records WHO did WHAT, WHEN, FROM WHERE for every API call. The audit backbone of AWS governance.
  • Event Types โ€” Management (free/default), Data (opt-in, high volume), Insights (ML anomaly detection)
  • Global Services โ€” IAM, STS, CloudFront only logged to multi-region trails or us-east-1 single-region trails
  • Delivery โ€” S3 (primary, ~15 min), CloudWatch Logs (alerting), SNS (notification), CloudTrail Lake (SQL, zero-ops)
  • Security โ€” integrity validation (digest chain + RSA signature), S3 Object Lock, KMS encryption, SCPs, separate security account
  • Integration โ€” EventBridge (real-time automation, seconds), Athena (SQL queries), LookupEvents API (free, 90 days), GuardDuty, Detective, Organizations
  • Cost Control โ€” advanced event selectors (scope by ARN, readOnly, eventName), S3 lifecycle to Glacier for long-term, Lake for zero-ops under 1 TB
AWS CloudTrail ยท Governance, Compliance & Audit ยท AWS ยท LearningTree ยท 2026