Skip to content

Trail

Source: src/AWS/CloudTrail/Trail.ts

An AWS CloudTrail trail that records AWS API activity and delivers log files to an S3 bucket.

The destination bucket must carry a bucket policy that allows the cloudtrail.amazonaws.com service principal to call s3:GetBucketAcl on the bucket and s3:PutObject under AWSLogs/{accountId}/*, both scoped with an aws:SourceArn condition on the trail’s ARN.

Basic Trail

import * as AWS from "alchemy/AWS";
const bucket = yield* AWS.S3.Bucket("TrailLogs", {
bucketName: `audit-logs-${accountId}`,
forceDestroy: true,
policy: [
{
Effect: "Allow",
Principal: { Service: "cloudtrail.amazonaws.com" },
Action: ["s3:GetBucketAcl"],
Resource: `arn:aws:s3:::audit-logs-${accountId}`,
Condition: { StringEquals: { "aws:SourceArn": trailArn } },
},
{
Effect: "Allow",
Principal: { Service: "cloudtrail.amazonaws.com" },
Action: ["s3:PutObject"],
Resource: `arn:aws:s3:::audit-logs-${accountId}/AWSLogs/${accountId}/*`,
Condition: {
StringEquals: {
"s3:x-amz-acl": "bucket-owner-full-control",
"aws:SourceArn": trailArn,
},
},
},
],
});
const trail = yield* AWS.CloudTrail.Trail("Audit", {
trailName: "audit-trail",
s3BucketName: bucket.bucketName,
});

Multi-Region Trail with Log File Validation

const trail = yield* AWS.CloudTrail.Trail("Audit", {
trailName: "org-audit-trail",
s3BucketName: bucket.bucketName,
isMultiRegionTrail: true,
enableLogFileValidation: true,
});
const trail = yield* AWS.CloudTrail.Trail("Audit", {
trailName: "audit-trail",
s3BucketName: bucket.bucketName,
isLogging: false,
});
const trail = yield* AWS.CloudTrail.Trail("Audit", {
trailName: "audit-trail",
s3BucketName: bucket.bucketName,
advancedEventSelectors: [
{
name: "Management events only",
fieldSelectors: [
{ field: "eventCategory", equals: ["Management"] },
],
},
],
insightSelectors: [{ insightType: "ApiCallRateInsight" }],
});