Skip to content
v2.273.0

AWS CloudTrail Construct Library ​

Trail ​

AWS CloudTrail enables governance, compliance, and operational and risk auditing of your AWS account. Actions taken by a user, role, or an AWS service are recorded as events in CloudTrail. Learn more at the CloudTrail documentation.

The Trail construct enables ongoing delivery of events as log files to an Amazon S3 bucket. Learn more about Creating a Trail for Your AWS Account. The following code creates a simple CloudTrail for your account -

ts
const trail = new cloudtrail.Trail(this, 'CloudTrail');
python
trail = cloudtrail.Trail(self, "CloudTrail")
java
Trail trail = new Trail(this, "CloudTrail");
csharp
var trail = new Trail(this, "CloudTrail");
go
trail := cloudtrail.NewTrail(this, jsii.String("CloudTrail"))

By default, this will create a new S3 Bucket that CloudTrail will write to, and choose a few other reasonable defaults such as turning on multi-region and global service events. The defaults for each property and how to override them are all documented on the TrailProps interface.

Log File Validation ​

In order to validate that the CloudTrail log file was not modified after CloudTrail delivered it, CloudTrail provides a digital signature for each file. Learn more at Validating CloudTrail Log File Integrity.

This is enabled on the Trail construct by default, but can be turned off by setting enableFileValidation to false.

ts
const trail = new cloudtrail.Trail(this, 'CloudTrail', {
  enableFileValidation: false,
});
python
trail = cloudtrail.Trail(self, "CloudTrail",
    enable_file_validation=False
)
java
Trail trail = Trail.Builder.create(this, "CloudTrail")
        .enableFileValidation(false)
        .build();
csharp
var trail = new Trail(this, "CloudTrail", new TrailProps {
    EnableFileValidation = false
});
go
trail := cloudtrail.NewTrail(this, jsii.String("CloudTrail"), &TrailProps{
	EnableFileValidation: jsii.Boolean(false),
})

Notifications ​

Amazon SNS notifications can be configured upon new log files containing Trail events are delivered to S3. Learn more at Configuring Amazon SNS Notifications for CloudTrail. The following code configures an SNS topic to be notified -

ts
const topic = new sns.Topic(this, 'TrailTopic');
const trail = new cloudtrail.Trail(this, 'CloudTrail', {
  snsTopic: topic,
});
python
topic = sns.Topic(self, "TrailTopic")
trail = cloudtrail.Trail(self, "CloudTrail",
    sns_topic=topic
)
java
Topic topic = new Topic(this, "TrailTopic");
Trail trail = Trail.Builder.create(this, "CloudTrail")
        .snsTopic(topic)
        .build();
csharp
var topic = new Topic(this, "TrailTopic");
var trail = new Trail(this, "CloudTrail", new TrailProps {
    SnsTopic = topic
});
go
topic := sns.NewTopic(this, jsii.String("TrailTopic"))
trail := cloudtrail.NewTrail(this, jsii.String("CloudTrail"), &TrailProps{
	SnsTopic: topic,
})

Service Integrations ​

Besides sending trail events to S3, they can also be configured to notify other AWS services -

Amazon CloudWatch Logs ​

CloudTrail events can be delivered to a CloudWatch Logs LogGroup. By default, a new LogGroup is created with a default retention setting. The following code enables sending CloudWatch logs but specifies a particular retention period for the created Log Group.

ts
import * as logs from 'aws-cdk-lib/aws-logs';

const trail = new cloudtrail.Trail(this, 'CloudTrail', {
  sendToCloudWatchLogs: true,
  cloudWatchLogsRetention: logs.RetentionDays.FOUR_MONTHS,
});
python
import aws_cdk.aws_logs as logs


trail = cloudtrail.Trail(self, "CloudTrail",
    send_to_cloud_watch_logs=True,
    cloud_watch_logs_retention=logs.RetentionDays.FOUR_MONTHS
)
java
import software.amazon.awscdk.services.logs.*;


Trail trail = Trail.Builder.create(this, "CloudTrail")
        .sendToCloudWatchLogs(true)
        .cloudWatchLogsRetention(RetentionDays.FOUR_MONTHS)
        .build();
csharp
using Amazon.CDK.AWS.Logs;


var trail = new Trail(this, "CloudTrail", new TrailProps {
    SendToCloudWatchLogs = true,
    CloudWatchLogsRetention = RetentionDays.FOUR_MONTHS
});
go
import logs "github.com/aws/aws-cdk-go/awscdk"


trail := cloudtrail.NewTrail(this, jsii.String("CloudTrail"), &TrailProps{
	SendToCloudWatchLogs: jsii.Boolean(true),
	CloudWatchLogsRetention: logs.RetentionDays_FOUR_MONTHS,
})

If you would like to use a specific log group instead, this can be configured via cloudwatchLogGroup.

Amazon EventBridge ​

Amazon EventBridge rules can be configured to be triggered when CloudTrail events occur using the Trail.onEvent() API. Using APIs available in aws-events, these events can be filtered to match to those that are of interest, either from a specific service, account or time range. See Events delivered via CloudTrail to learn more about the event structure for events from CloudTrail.

The following code filters events for S3 from a specific AWS account and triggers a lambda function.

ts
const myFunctionHandler = new lambda.Function(this, 'MyFunction', {
  code: lambda.Code.fromAsset('resource/myfunction'),
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
});

const eventRule = cloudtrail.Trail.onEvent(this, 'MyCloudWatchEvent', {
  target: new targets.LambdaFunction(myFunctionHandler),
});

eventRule.addEventPattern({
  account: ['123456789012'],
  source: ['aws.s3'],
});
python
my_function_handler = lambda_.Function(self, "MyFunction",
    code=lambda_.Code.from_asset("resource/myfunction"),
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler"
)

event_rule = cloudtrail.Trail.on_event(self, "MyCloudWatchEvent",
    target=targets.LambdaFunction(my_function_handler)
)

event_rule.add_event_pattern(
    account=["123456789012"],
    source=["aws.s3"]
)
java
Function myFunctionHandler = Function.Builder.create(this, "MyFunction")
        .code(Code.fromAsset("resource/myfunction"))
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .build();

Rule eventRule = Trail.onEvent(this, "MyCloudWatchEvent", OnEventOptions.builder()
        .target(new LambdaFunction(myFunctionHandler))
        .build());

eventRule.addEventPattern(EventPattern.builder()
        .account(List.of("123456789012"))
        .source(List.of("aws.s3"))
        .build());
csharp
var myFunctionHandler = new Function(this, "MyFunction", new FunctionProps {
    Code = Code.FromAsset("resource/myfunction"),
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler"
});

var eventRule = Trail.OnEvent(this, "MyCloudWatchEvent", new OnEventOptions {
    Target = new LambdaFunction(myFunctionHandler)
});

eventRule.AddEventPattern(new EventPattern {
    Account = new [] { "123456789012" },
    Source = new [] { "aws.s3" }
});
go
myFunctionHandler := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Code: lambda.Code_FromAsset(jsii.String("resource/myfunction")),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
})

eventRule := cloudtrail.Trail_OnEvent(this, jsii.String("MyCloudWatchEvent"), &OnEventOptions{
	Target: targets.NewLambdaFunction(myFunctionHandler),
})

eventRule.AddEventPattern(&EventPattern{
	Account: []*string{
		jsii.String("123456789012"),
	},
	Source: []*string{
		jsii.String("aws.s3"),
	},
})

Multi-Region & Global Service Events ​

By default, a Trail is configured to deliver log files from multiple regions to a single S3 bucket for a given account. This creates shadow trails (replication of the trails) in all of the other regions. Learn more about How CloudTrail Behaves Regionally and about the IsMultiRegion property.

For most services, events are recorded in the region where the action occurred. For global services such as AWS IAM, AWS STS, Amazon CloudFront, Route 53, etc., events are delivered to any trail that includes global services. Learn more About Global Service Events.

Events for global services are turned on by default for Trail constructs in the CDK.

The following code disables multi-region trail delivery and trail delivery for global services for a specific Trail -

ts
const trail = new cloudtrail.Trail(this, 'CloudTrail', {
  // ...
  isMultiRegionTrail: false,
  includeGlobalServiceEvents: false,
});
python
trail = cloudtrail.Trail(self, "CloudTrail",
    # ...
    is_multi_region_trail=False,
    include_global_service_events=False
)
java
Trail trail = Trail.Builder.create(this, "CloudTrail")
        // ...
        .isMultiRegionTrail(false)
        .includeGlobalServiceEvents(false)
        .build();
csharp
var trail = new Trail(this, "CloudTrail", new TrailProps {
    // ...
    IsMultiRegionTrail = false,
    IncludeGlobalServiceEvents = false
});
go
trail := cloudtrail.NewTrail(this, jsii.String("CloudTrail"), &TrailProps{
	// ...
	IsMultiRegionTrail: jsii.Boolean(false),
	IncludeGlobalServiceEvents: jsii.Boolean(false),
})

Events Types ​

Management events provide information about management operations that are performed on resources in your AWS account. These are also known as control plane operations. Learn more about Management Events.

By default, a Trail logs all management events. However, they can be configured to either be turned off, or to only log 'Read' or 'Write' events.

The following code configures the Trail to only track management events that are of type 'Read'.

ts
const trail = new cloudtrail.Trail(this, 'CloudTrail', {
  // ...
  managementEvents: cloudtrail.ReadWriteType.READ_ONLY,
});
python
trail = cloudtrail.Trail(self, "CloudTrail",
    # ...
    management_events=cloudtrail.ReadWriteType.READ_ONLY
)
java
Trail trail = Trail.Builder.create(this, "CloudTrail")
        // ...
        .managementEvents(ReadWriteType.READ_ONLY)
        .build();
csharp
var trail = new Trail(this, "CloudTrail", new TrailProps {
    // ...
    ManagementEvents = ReadWriteType.READ_ONLY
});
go
trail := cloudtrail.NewTrail(this, jsii.String("CloudTrail"), &TrailProps{
	// ...
	ManagementEvents: cloudtrail.ReadWriteType_READ_ONLY,
})

Data events provide information about the resource operations performed on or in a resource. These are also known as data plane operations. Learn more about Data Events. By default, no data events are logged for a Trail.

AWS CloudTrail supports data event logging for Amazon S3 objects and AWS Lambda functions.

The logAllS3DataEvents() API configures the trail to log all S3 data events while the addS3EventSelector() API can be used to configure logging of S3 data events for specific buckets and specific object prefix. The following code configures logging of S3 data events for fooBucket and with object prefix bar/.

ts
import * as s3 from 'aws-cdk-lib/aws-s3';

const trail = new cloudtrail.Trail(this, 'MyAmazingCloudTrail');
declare const bucket: s3.Bucket;

// Adds an event selector to the bucket foo
trail.addS3EventSelector([{
  bucket,
  objectPrefix: 'bar/',
}]);
python
import aws_cdk.aws_s3 as s3
# bucket: s3.Bucket


trail = cloudtrail.Trail(self, "MyAmazingCloudTrail")

# Adds an event selector to the bucket foo
trail.add_s3_event_selector([
    bucket=bucket,
    object_prefix="bar/"
])
java
import software.amazon.awscdk.services.s3.*;
Bucket bucket;


Trail trail = new Trail(this, "MyAmazingCloudTrail");

// Adds an event selector to the bucket foo
trail.addS3EventSelector(List.of(S3EventSelector.builder()
        .bucket(bucket)
        .objectPrefix("bar/")
        .build()));
csharp
using Amazon.CDK.AWS.S3;
Bucket bucket;


var trail = new Trail(this, "MyAmazingCloudTrail");

// Adds an event selector to the bucket foo
trail.AddS3EventSelector(new [] { new S3EventSelector {
    Bucket = bucket,
    ObjectPrefix = "bar/"
} });
go
import s3 "github.com/aws/aws-cdk-go/awscdk"
var bucket Bucket


trail := cloudtrail.NewTrail(this, jsii.String("MyAmazingCloudTrail"))

// Adds an event selector to the bucket foo
trail.AddS3EventSelector([]S3EventSelector{
	&S3EventSelector{
		Bucket: Bucket,
		ObjectPrefix: jsii.String("bar/"),
	},
})

Similarly, the logAllLambdaDataEvents() configures the trail to log all Lambda data events while the addLambdaEventSelector() API can be used to configure logging for specific Lambda functions. The following code configures logging of Lambda data events for a specific Function.

ts
const trail = new cloudtrail.Trail(this, 'MyAmazingCloudTrail');
const amazingFunction = new lambda.Function(this, 'AnAmazingFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: "hello.handler",
  code: lambda.Code.fromAsset("lambda"),
});

// Add an event selector to log data events for the provided Lambda functions.
trail.addLambdaEventSelector([ amazingFunction ]);
python
trail = cloudtrail.Trail(self, "MyAmazingCloudTrail")
amazing_function = lambda_.Function(self, "AnAmazingFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="hello.handler",
    code=lambda_.Code.from_asset("lambda")
)

# Add an event selector to log data events for the provided Lambda functions.
trail.add_lambda_event_selector([amazing_function])
java
Trail trail = new Trail(this, "MyAmazingCloudTrail");
Function amazingFunction = Function.Builder.create(this, "AnAmazingFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("hello.handler")
        .code(Code.fromAsset("lambda"))
        .build();

// Add an event selector to log data events for the provided Lambda functions.
trail.addLambdaEventSelector(List.of(amazingFunction));
csharp
var trail = new Trail(this, "MyAmazingCloudTrail");
var amazingFunction = new Function(this, "AnAmazingFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "hello.handler",
    Code = Code.FromAsset("lambda")
});

// Add an event selector to log data events for the provided Lambda functions.
trail.AddLambdaEventSelector(new [] { amazingFunction });
go
trail := cloudtrail.NewTrail(this, jsii.String("MyAmazingCloudTrail"))
amazingFunction := lambda.NewFunction(this, jsii.String("AnAmazingFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("hello.handler"),
	Code: lambda.Code_FromAsset(jsii.String("lambda")),
})

// Add an event selector to log data events for the provided Lambda functions.
trail.AddLambdaEventSelector([]IFunction{
	amazingFunction,
})

Organization Trail ​

It is possible to create a trail that will be applied to all accounts in an organization if the current account manages an organization. To enable this, the property isOrganizationTrail must be set. If this property is set and the current account does not manage an organization, the stack will fail to deploy.

ts
new cloudtrail.Trail(this, 'OrganizationTrail', {
  isOrganizationTrail: true,
});
python
cloudtrail.Trail(self, "OrganizationTrail",
    is_organization_trail=True
)
java
Trail.Builder.create(this, "OrganizationTrail")
        .isOrganizationTrail(true)
        .build();
csharp
new Trail(this, "OrganizationTrail", new TrailProps {
    IsOrganizationTrail = true
});
go
cloudtrail.NewTrail(this, jsii.String("OrganizationTrail"), &TrailProps{
	IsOrganizationTrail: jsii.Boolean(true),
})

CloudTrail Insights ​

Set InsightSelector to enable Insight. Insights selector values can be ApiCallRateInsight, ApiErrorRateInsight, or both.

ts
new cloudtrail.Trail(this, 'Insights', {
    insightTypes: [
      cloudtrail.InsightType.API_CALL_RATE,
      cloudtrail.InsightType.API_ERROR_RATE,
    ],
});
python
cloudtrail.Trail(self, "Insights",
    insight_types=[cloudtrail.InsightType.API_CALL_RATE, cloudtrail.InsightType.API_ERROR_RATE
    ]
)
java
Trail.Builder.create(this, "Insights")
        .insightTypes(List.of(InsightType.API_CALL_RATE, InsightType.API_ERROR_RATE))
        .build();
csharp
new Trail(this, "Insights", new TrailProps {
    InsightTypes = new [] { InsightType.API_CALL_RATE, InsightType.API_ERROR_RATE }
});
go
cloudtrail.NewTrail(this, jsii.String("Insights"), &TrailProps{
	InsightTypes: []InsightType{
		cloudtrail.InsightType_API_CALL_RATE(),
		cloudtrail.InsightType_API_ERROR_RATE(),
	},
})

Types ​

NameKindSummary
TrailConstruct (L2)Cloud trail allows you to log events that happen in your AWS account For example:.
CfnChannelConstruct (L1)Contains information about a returned CloudTrail channel.
CfnDashboardConstruct (L1)Creates a custom dashboard or the Highlights dashboard.
CfnEventDataStoreConstruct (L1)Creates a new event data store.
CfnResourcePolicyConstruct (L1)Attaches a resource-based permission policy to a CloudTrail event data store, dashboard, or channel.
CfnTrailConstruct (L1)Creates a trail that specifies the settings for delivery of log data to an Amazon S3 bucket.
AddEventSelectorOptionsStructOptions for adding an event selector.
CfnChannel.DestinationPropertyStructContains information about the destination receiving events.
CfnChannelPropsStructProperties for defining a CfnChannel.
CfnDashboard.FrequencyPropertyStructSpecifies the frequency for a dashboard refresh schedule.
CfnDashboard.RefreshSchedulePropertyStructThe schedule for a dashboard refresh.
CfnDashboard.WidgetPropertyStructContains information about a widget on a CloudTrail Lake dashboard.
CfnDashboardPropsStructProperties for defining a CfnDashboard.
CfnEventDataStore.AdvancedEventSelectorPropertyStructAdvanced event selectors let you create fine-grained selectors for AWS CloudTrail management, data, and network activity events.
CfnEventDataStore.AdvancedFieldSelectorPropertyStructA single selector statement in an advanced event selector.
CfnEventDataStore.ContextKeySelectorPropertyStructAn object that contains information types to be included in CloudTrail enriched events.
CfnEventDataStore.InsightSelectorPropertyStructA JSON string that contains a list of Insights types that are logged on an event data store.
CfnEventDataStorePropsStructProperties for defining a CfnEventDataStore.
CfnResourcePolicyPropsStructProperties for defining a CfnResourcePolicy.
CfnTrail.AdvancedEventSelectorPropertyStructAdvanced event selectors let you create fine-grained selectors for AWS CloudTrail management, data, and network activity events.
CfnTrail.AdvancedFieldSelectorPropertyStructA single selector statement in an advanced event selector.
CfnTrail.AggregationConfigurationPropertyStructAn object that contains configuration settings for aggregating events.
CfnTrail.DataResourcePropertyStructYou can configure the DataResource in an EventSelector to log data events for the following three resource types:.
CfnTrail.EventSelectorPropertyStructUse event selectors to further specify the management and data event settings for your trail.
CfnTrail.InsightSelectorPropertyStructA JSON string that contains a list of Insights types that are logged on a trail.
CfnTrailPropsStructProperties for defining a CfnTrail.
DataResourceTypeEnumResource type for a data event.
InsightTypeClassUtil element for InsightSelector.
ManagementEventSourcesEnumTypes of management event sources that can be excluded.
ReadWriteTypeEnumTypes of events that CloudTrail can log.
S3EventSelectorStructSelecting an S3 bucket and an optional prefix to be logged for data events.
TrailPropsStructProperties for an AWS CloudTrail trail.