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 -
const trail = new cloudtrail.Trail(this, 'CloudTrail');
trail = cloudtrail.Trail(self, "CloudTrail")
Trail trail = new Trail(this, "CloudTrail");
var trail = new Trail(this, "CloudTrail");
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.
const trail = new cloudtrail.Trail(this, 'CloudTrail', {
enableFileValidation: false,
});
trail = cloudtrail.Trail(self, "CloudTrail",
enable_file_validation=False
)
Trail trail = Trail.Builder.create(this, "CloudTrail")
.enableFileValidation(false)
.build();
var trail = new Trail(this, "CloudTrail", new TrailProps {
EnableFileValidation = false
});
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 -
const topic = new sns.Topic(this, 'TrailTopic');
const trail = new cloudtrail.Trail(this, 'CloudTrail', {
snsTopic: topic,
});
topic = sns.Topic(self, "TrailTopic")
trail = cloudtrail.Trail(self, "CloudTrail",
sns_topic=topic
)
Topic topic = new Topic(this, "TrailTopic");
Trail trail = Trail.Builder.create(this, "CloudTrail")
.snsTopic(topic)
.build();
var topic = new Topic(this, "TrailTopic");
var trail = new Trail(this, "CloudTrail", new TrailProps {
SnsTopic = topic
});
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.
import * as logs from 'aws-cdk-lib/aws-logs';
const trail = new cloudtrail.Trail(this, 'CloudTrail', {
sendToCloudWatchLogs: true,
cloudWatchLogsRetention: logs.RetentionDays.FOUR_MONTHS,
});
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
)
import software.amazon.awscdk.services.logs.*;
Trail trail = Trail.Builder.create(this, "CloudTrail")
.sendToCloudWatchLogs(true)
.cloudWatchLogsRetention(RetentionDays.FOUR_MONTHS)
.build();
using Amazon.CDK.AWS.Logs;
var trail = new Trail(this, "CloudTrail", new TrailProps {
SendToCloudWatchLogs = true,
CloudWatchLogsRetention = RetentionDays.FOUR_MONTHS
});
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.
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'],
});
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"]
)
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());
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" }
});
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 -
const trail = new cloudtrail.Trail(this, 'CloudTrail', {
// ...
isMultiRegionTrail: false,
includeGlobalServiceEvents: false,
});
trail = cloudtrail.Trail(self, "CloudTrail",
# ...
is_multi_region_trail=False,
include_global_service_events=False
)
Trail trail = Trail.Builder.create(this, "CloudTrail")
// ...
.isMultiRegionTrail(false)
.includeGlobalServiceEvents(false)
.build();
var trail = new Trail(this, "CloudTrail", new TrailProps {
// ...
IsMultiRegionTrail = false,
IncludeGlobalServiceEvents = false
});
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'.
const trail = new cloudtrail.Trail(this, 'CloudTrail', {
// ...
managementEvents: cloudtrail.ReadWriteType.READ_ONLY,
});
trail = cloudtrail.Trail(self, "CloudTrail",
# ...
management_events=cloudtrail.ReadWriteType.READ_ONLY
)
Trail trail = Trail.Builder.create(this, "CloudTrail")
// ...
.managementEvents(ReadWriteType.READ_ONLY)
.build();
var trail = new Trail(this, "CloudTrail", new TrailProps {
// ...
ManagementEvents = ReadWriteType.READ_ONLY
});
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/.
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/',
}]);
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/"
])
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()));
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/"
} });
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.
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 ]);
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])
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));
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 });
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.
new cloudtrail.Trail(this, 'OrganizationTrail', {
isOrganizationTrail: true,
});
cloudtrail.Trail(self, "OrganizationTrail",
is_organization_trail=True
)
Trail.Builder.create(this, "OrganizationTrail")
.isOrganizationTrail(true)
.build();
new Trail(this, "OrganizationTrail", new TrailProps {
IsOrganizationTrail = true
});
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.
new cloudtrail.Trail(this, 'Insights', {
insightTypes: [
cloudtrail.InsightType.API_CALL_RATE,
cloudtrail.InsightType.API_ERROR_RATE,
],
});
cloudtrail.Trail(self, "Insights",
insight_types=[cloudtrail.InsightType.API_CALL_RATE, cloudtrail.InsightType.API_ERROR_RATE
]
)
Trail.Builder.create(this, "Insights")
.insightTypes(List.of(InsightType.API_CALL_RATE, InsightType.API_ERROR_RATE))
.build();
new Trail(this, "Insights", new TrailProps {
InsightTypes = new [] { InsightType.API_CALL_RATE, InsightType.API_ERROR_RATE }
});
cloudtrail.NewTrail(this, jsii.String("Insights"), &TrailProps{
InsightTypes: []InsightType{
cloudtrail.InsightType_API_CALL_RATE(),
cloudtrail.InsightType_API_ERROR_RATE(),
},
})
Types
| Name | Kind | Summary |
|---|---|---|
Trail | Construct (L2) | Cloud trail allows you to log events that happen in your AWS account For example:. |
CfnChannel | Construct (L1) | Contains information about a returned CloudTrail channel. |
CfnDashboard | Construct (L1) | Creates a custom dashboard or the Highlights dashboard. |
CfnEventDataStore | Construct (L1) | Creates a new event data store. |
CfnResourcePolicy | Construct (L1) | Attaches a resource-based permission policy to a CloudTrail event data store, dashboard, or channel. |
CfnTrail | Construct (L1) | Creates a trail that specifies the settings for delivery of log data to an Amazon S3 bucket. |
AddEventSelectorOptions | Struct | Options for adding an event selector. |
CfnChannel.DestinationProperty | Struct | Contains information about the destination receiving events. |
CfnChannelProps | Struct | Properties for defining a CfnChannel. |
CfnDashboard.FrequencyProperty | Struct | Specifies the frequency for a dashboard refresh schedule. |
CfnDashboard.RefreshScheduleProperty | Struct | The schedule for a dashboard refresh. |
CfnDashboard.WidgetProperty | Struct | Contains information about a widget on a CloudTrail Lake dashboard. |
CfnDashboardProps | Struct | Properties for defining a CfnDashboard. |
CfnEventDataStore.AdvancedEventSelectorProperty | Struct | Advanced event selectors let you create fine-grained selectors for AWS CloudTrail management, data, and network activity events. |
CfnEventDataStore.AdvancedFieldSelectorProperty | Struct | A single selector statement in an advanced event selector. |
CfnEventDataStore.ContextKeySelectorProperty | Struct | An object that contains information types to be included in CloudTrail enriched events. |
CfnEventDataStore.InsightSelectorProperty | Struct | A JSON string that contains a list of Insights types that are logged on an event data store. |
CfnEventDataStoreProps | Struct | Properties for defining a CfnEventDataStore. |
CfnResourcePolicyProps | Struct | Properties for defining a CfnResourcePolicy. |
CfnTrail.AdvancedEventSelectorProperty | Struct | Advanced event selectors let you create fine-grained selectors for AWS CloudTrail management, data, and network activity events. |
CfnTrail.AdvancedFieldSelectorProperty | Struct | A single selector statement in an advanced event selector. |
CfnTrail.AggregationConfigurationProperty | Struct | An object that contains configuration settings for aggregating events. |
CfnTrail.DataResourceProperty | Struct | You can configure the DataResource in an EventSelector to log data events for the following three resource types:. |
CfnTrail.EventSelectorProperty | Struct | Use event selectors to further specify the management and data event settings for your trail. |
CfnTrail.InsightSelectorProperty | Struct | A JSON string that contains a list of Insights types that are logged on a trail. |
CfnTrailProps | Struct | Properties for defining a CfnTrail. |
DataResourceType | Enum | Resource type for a data event. |
InsightType | Class | Util element for InsightSelector. |
ManagementEventSources | Enum | Types of management event sources that can be excluded. |
ReadWriteType | Enum | Types of events that CloudTrail can log. |
S3EventSelector | Struct | Selecting an S3 bucket and an optional prefix to be logged for data events. |
TrailProps | Struct | Properties for an AWS CloudTrail trail. |