CloudTrail Basics
Seven examples to get you started with CloudTrail via SDK - five basic and two intermediate.
Busca en todas las páginas de la documentación
Seven examples to get you started with CloudTrail via SDK - five basic and two intermediate.
Each example shows the same operation in both Python (boto3) and TypeScript (AWS SDK for JavaScript v3).
pip install boto3 (boto3 1.43.x, Python 3.10+). TypeScript: npm install @aws-sdk/client-cloudtrail (Node.js 18+).aws configure, environment variables, or an IAM role, with cloudtrail:LookupEvents and cloudtrail:*Trail* permissions as needed.LookupEvents works against any account's built-in event history.Query the last 90 days of management events without any trail setup.
# --- Python (boto3) ---
import boto3
client = boto3.client("cloudtrail", region_name="us-east-1")
response = client.lookup_events(MaxResults=10)
for event in response["Events"]:
print(event["EventName"], event["EventTime"], event["Username"])// --- TypeScript (AWS SDK v3) ---
import { CloudTrailClient, LookupEventsCommand } from "@aws-sdk/client-cloudtrail";
const client = new CloudTrailClient({ region: "us-east-1" });
const response = await client.send(new LookupEventsCommand({ MaxResults: 10 }));
for (const event of response.Events ?? []) {
console.log(event.EventName, event.EventTime, event.Username);
}LookupEvents reads the account's built-in event history, not a trail's S3 logs.MaxResults caps a single page; use pagination for larger windows.Username may be empty for service-linked or unauthenticated calls.Related: Event History Queries via SDK - filtering with
LookupAttributes.
Narrow results to a specific API call, like console sign-ins.
# --- Python (boto3) ---
import boto3
client = boto3.client("cloudtrail")
response = client.lookup_events(
LookupAttributes=[{"AttributeKey": "EventName", "AttributeValue": "ConsoleLogin"}],
MaxResults=10,
)
for event in response["Events"]:
print(event["EventTime"], event["Username"])// --- 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: "EventName", AttributeValue: "ConsoleLogin" }],
MaxResults: 10,
}));
for (const event of response.Events ?? []) {
console.log(event.EventTime, event.Username);
}LookupAttributes accepts exactly one attribute key/value pair per call.EventName matches the exact API operation name, case-sensitive.StartTime/EndTime window to bound the search further.Stand up a trail that delivers events to S3 for durable retention.
# --- Python (boto3) ---
import boto3
client = boto3.client("cloudtrail")
trail = client.create_trail(
Name="baseline-trail",
S3BucketName="my-account-cloudtrail-logs",
IsMultiRegionTrail=True,
EnableLogFileValidation=True,
)
print(trail["TrailARN"])// --- TypeScript (AWS SDK v3) ---
import { CloudTrailClient, CreateTrailCommand } from "@aws-sdk/client-cloudtrail";
const client = new CloudTrailClient({});
const trail = await client.send(new CreateTrailCommand({
Name: "baseline-trail",
S3BucketName: "my-account-cloudtrail-logs",
IsMultiRegionTrail: true,
EnableLogFileValidation: true,
}));
console.log(trail.TrailARN);S3BucketName must already exist and have a bucket policy allowing CloudTrail to write to it.IsMultiRegionTrail: true captures events from every region into this one trail.CreateTrail only defines the trail; logging doesn't start until you call StartLogging.EnableLogFileValidation turns on digest-file delivery for tamper-evidence.Related: Trails, S3 Delivery & Log File Validation - the full setup including org-wide trails.
A newly created trail doesn't log until you explicitly start it.
# --- Python (boto3) ---
import boto3
client = boto3.client("cloudtrail")
client.start_logging(Name="baseline-trail")// --- TypeScript (AWS SDK v3) ---
import { CloudTrailClient, StartLoggingCommand } from "@aws-sdk/client-cloudtrail";
const client = new CloudTrailClient({});
await client.send(new StartLoggingCommand({ Name: "baseline-trail" }));StartLogging is a separate call from CreateTrail - creating a trail alone delivers nothing.Name parameter accepts the trail name or its full ARN.StopLogging is the corresponding call to pause delivery without deleting the trail.Confirm whether a trail is actively logging right now.
# --- Python (boto3) ---
import boto3
client = boto3.client("cloudtrail")
status = client.get_trail_status(Name="baseline-trail")
print(status["IsLogging"], status.get("LatestDeliveryTime"))// --- TypeScript (AWS SDK v3) ---
import { CloudTrailClient, GetTrailStatusCommand } from "@aws-sdk/client-cloudtrail";
const client = new CloudTrailClient({});
const status = await client.send(new GetTrailStatusCommand({ Name: "baseline-trail" }));
console.log(status.IsLogging, status.LatestDeliveryTime);IsLogging is a boolean reflecting the trail's current state, not its historical uptime.LatestDeliveryTime tells you when the last log file successfully landed in S3.LatestDeliveryError) surface permission or bucket-policy problems.StartLogging to confirm the trail is actually delivering, not just enabled.Narrow event history to a specific IAM principal's activity.
# --- Python (boto3) ---
import boto3
client = boto3.client("cloudtrail")
response = client.lookup_events(
LookupAttributes=[{"AttributeKey": "Username", "AttributeValue": "deploy-bot"}],
MaxResults=20,
)
for event in response["Events"]:
print(event["EventName"], event["EventTime"])// --- 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: "Username", AttributeValue: "deploy-bot" }],
MaxResults: 20,
}));
for (const event of response.Events ?? []) {
console.log(event.EventName, event.EventTime);
}Username matches the IAM user or role session name that made the call.role-name/session-name in some event fields.StartTime to bound a specific deploy window.Walk multiple pages of event history for a longer lookback window.
# --- Python (boto3) ---
import boto3
from datetime import datetime, timedelta
client = boto3.client("cloudtrail")
paginator = client.get_paginator("lookup_events")
start = datetime.utcnow() - timedelta(days=7)
for page in paginator.paginate(StartTime=start):
for event in page["Events"]:
print(event["EventName"], event["EventTime"])// --- TypeScript (AWS SDK v3) ---
import { CloudTrailClient, paginateLookupEvents } from "@aws-sdk/client-cloudtrail";
const client = new CloudTrailClient({});
const start = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const pages = paginateLookupEvents({ client }, { StartTime: start });
for await (const page of pages) {
for (const event of page.Events ?? []) {
console.log(event.EventName, event.EventTime);
}
}get_paginator("lookup_events"); SDK v3 ships paginateLookupEvents.StartTime/EndTime bound the query; omitting both defaults to the full 90-day history.Related: CloudTrail Lake for SQL-Based Audit Queries - long-retention, SQL-based querying.
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 actualización: 25 jul 2026