Skip to content

Resource: awsCloudtrail

Provides a CloudTrail resource.

-> Tip: For a multi-region trail, this resource must be in the home region of the trail.

-> Tip: For an organization trail, this resource must be in the master account of the organization.

Example Usage

Basic

Enable CloudTrail to capture all compatible management events in region. For capturing events from services like IAM, includeGlobalServiceEvents must be enabled.

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsS3BucketFoo = new aws.s3Bucket.S3Bucket(this, "foo", {
  bucket: "tf-test-trail",
  forceDestroy: true,
});
const dataAwsCallerIdentityCurrent =
  new aws.dataAwsCallerIdentity.DataAwsCallerIdentity(this, "current", {});
const dataAwsIamPolicyDocumentFoo =
  new aws.dataAwsIamPolicyDocument.DataAwsIamPolicyDocument(this, "foo_2", {
    statement: [
      {
        actions: ["s3:GetBucketAcl"],
        effect: "Allow",
        principals: [
          {
            identifiers: ["cloudtrail.amazonaws.com"],
            type: "Service",
          },
        ],
        resources: [awsS3BucketFoo.arn],
        sid: "AWSCloudTrailAclCheck",
      },
      {
        actions: ["s3:PutObject"],
        condition: [
          {
            test: "StringEquals",
            values: ["bucket-owner-full-control"],
            variable: "s3:x-amz-acl",
          },
        ],
        effect: "Allow",
        principals: [
          {
            identifiers: ["cloudtrail.amazonaws.com"],
            type: "Service",
          },
        ],
        resources: [
          `\${${awsS3BucketFoo.arn}}/prefix/AWSLogs/\${${dataAwsCallerIdentityCurrent.accountId}}/*`,
        ],
        sid: "AWSCloudTrailWrite",
      },
    ],
  });
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
dataAwsIamPolicyDocumentFoo.overrideLogicalId("foo");
new aws.cloudtrail.Cloudtrail(this, "foobar", {
  includeGlobalServiceEvents: false,
  name: "tf-trail-foobar",
  s3BucketName: awsS3BucketFoo.id,
  s3KeyPrefix: "prefix",
});
const awsS3BucketPolicyFoo = new aws.s3BucketPolicy.S3BucketPolicy(
  this,
  "foo_4",
  {
    bucket: awsS3BucketFoo.id,
    policy: dataAwsIamPolicyDocumentFoo.json,
  }
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsS3BucketPolicyFoo.overrideLogicalId("foo");

Data Event Logging

CloudTrail can log Data Events for certain services such as S3 objects and Lambda function invocations. Additional information about data event configuration can be found in the following links:

Logging All Lambda Function Invocations By Using Basic Event Selectors

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.cloudtrail.Cloudtrail(this, "example", {
  eventSelector: [
    {
      dataResource: [
        {
          type: "AWS::Lambda::Function",
          values: ["arn:aws:lambda"],
        },
      ],
      includeManagementEvents: true,
      readWriteType: "All",
    },
  ],
});

Logging All S3 Object Events By Using Basic Event Selectors

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.cloudtrail.Cloudtrail(this, "example", {
  eventSelector: [
    {
      dataResource: [
        {
          type: "AWS::S3::Object",
          values: ["arn:aws:s3"],
        },
      ],
      includeManagementEvents: true,
      readWriteType: "All",
    },
  ],
});

Logging Individual S3 Bucket Events By Using Basic Event Selectors

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsS3BucketImportantBucket = new aws.dataAwsS3Bucket.DataAwsS3Bucket(
  this,
  "important-bucket",
  {
    bucket: "important-bucket",
  }
);
new aws.cloudtrail.Cloudtrail(this, "example", {
  eventSelector: [
    {
      dataResource: [
        {
          type: "AWS::S3::Object",
          values: [`\${${dataAwsS3BucketImportantBucket.arn}}/`],
        },
      ],
      includeManagementEvents: true,
      readWriteType: "All",
    },
  ],
});

Logging All S3 Object Events Except For Two S3 Buckets By Using Advanced Event Selectors

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsS3BucketNotImportantBucket1 =
  new aws.dataAwsS3Bucket.DataAwsS3Bucket(this, "not-important-bucket-1", {
    bucket: "not-important-bucket-1",
  });
const dataAwsS3BucketNotImportantBucket2 =
  new aws.dataAwsS3Bucket.DataAwsS3Bucket(this, "not-important-bucket-2", {
    bucket: "not-important-bucket-2",
  });
new aws.cloudtrail.Cloudtrail(this, "example", {
  advancedEventSelector: [
    {
      fieldSelector: [
        {
          equalTo: ["Data"],
          field: "eventCategory",
        },
        {
          field: "resources.ARN",
          notStartsWith: [
            `\${${dataAwsS3BucketNotImportantBucket1.arn}}/`,
            `\${${dataAwsS3BucketNotImportantBucket2.arn}}/`,
          ],
        },
        {
          equalTo: ["AWS::S3::Object"],
          field: "resources.type",
        },
      ],
      name: "Log all S3 objects events except for two S3 buckets",
    },
    {
      fieldSelector: [
        {
          equalTo: ["Management"],
          field: "eventCategory",
        },
      ],
      name: "Log readOnly and writeOnly management events",
    },
  ],
});

Logging Individual S3 Buckets And Specific Event Names By Using Advanced Event Selectors

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsS3BucketImportantBucket1 = new aws.dataAwsS3Bucket.DataAwsS3Bucket(
  this,
  "important-bucket-1",
  {
    bucket: "important-bucket-1",
  }
);
const dataAwsS3BucketImportantBucket2 = new aws.dataAwsS3Bucket.DataAwsS3Bucket(
  this,
  "important-bucket-2",
  {
    bucket: "important-bucket-2",
  }
);
const dataAwsS3BucketImportantBucket3 = new aws.dataAwsS3Bucket.DataAwsS3Bucket(
  this,
  "important-bucket-3",
  {
    bucket: "important-bucket-3",
  }
);
new aws.cloudtrail.Cloudtrail(this, "example", {
  advancedEventSelector: [
    {
      fieldSelector: [
        {
          equalTo: ["Data"],
          field: "eventCategory",
        },
        {
          equalTo: ["PutObject", "DeleteObject"],
          field: "eventName",
        },
        {
          equalTo: [
            `\${${dataAwsS3BucketImportantBucket1.arn}}/`,
            `\${${dataAwsS3BucketImportantBucket2.arn}}/`,
          ],
          field: "resources.ARN",
        },
        {
          equalTo: ["false"],
          field: "readOnly",
        },
        {
          equalTo: ["AWS::S3::Object"],
          field: "resources.type",
        },
      ],
      name: "Log PutObject and DeleteObject events for two S3 buckets",
    },
    {
      fieldSelector: [
        {
          equalTo: ["Data"],
          field: "eventCategory",
        },
        {
          field: "eventName",
          startsWith: ["Delete"],
        },
        {
          equalTo: [
            `\${${dataAwsS3BucketImportantBucket3.arn}}/important-prefix`,
          ],
          field: "resources.ARN",
        },
        {
          equalTo: ["false"],
          field: "readOnly",
        },
        {
          equalTo: ["AWS::S3::Object"],
          field: "resources.type",
        },
      ],
      name: "Log Delete* events for one S3 bucket",
    },
  ],
});

Sending Events to CloudWatch Logs

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsCloudwatchLogGroupExample =
  new aws.cloudwatchLogGroup.CloudwatchLogGroup(this, "example", {
    name: "Example",
  });
const awsCloudtrailExample = new aws.cloudtrail.Cloudtrail(this, "example_1", {
  cloudWatchLogsGroupArn: `\${${awsCloudwatchLogGroupExample.arn}}:*`,
});
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsCloudtrailExample.overrideLogicalId("example");

Argument Reference

The following arguments are required:

  • name - (Required) Name of the trail.
  • s3BucketName - (Required) Name of the S3 bucket designated for publishing log files.

The following arguments are optional:

  • advancedEventSelector - (Optional) Specifies an advanced event selector for enabling data event logging. Fields documented below. Conflicts with eventSelector.
  • cloudWatchLogsGroupArn - (Optional) Log group name using an ARN that represents the log group to which CloudTrail logs will be delivered. Note that CloudTrail requires the Log Stream wildcard.
  • cloudWatchLogsRoleArn - (Optional) Role for the CloudWatch Logs endpoint to assume to write to a user’s log group.
  • enableLogFileValidation - (Optional) Whether log file integrity validation is enabled. Defaults to false.
  • enableLogging - (Optional) Enables logging for the trail. Defaults to true. Setting this to false will pause logging.
  • eventSelector - (Optional) Specifies an event selector for enabling data event logging. Fields documented below. Please note the CloudTrail limits when configuring these. Conflicts with advancedEventSelector.
  • includeGlobalServiceEvents - (Optional) Whether the trail is publishing events from global services such as IAM to the log files. Defaults to true.
  • insightSelector - (Optional) Configuration block for identifying unusual operational activity. See details below.
  • isMultiRegionTrail - (Optional) Whether the trail is created in the current region or in all regions. Defaults to false.
  • isOrganizationTrail - (Optional) Whether the trail is an AWS Organizations trail. Organization trails log events for the master account and all member accounts. Can only be created in the organization master account. Defaults to false.
  • kmsKeyId - (Optional) KMS key ARN to use to encrypt the logs delivered by CloudTrail.
  • s3KeyPrefix - (Optional) S3 key prefix that follows the name of the bucket you have designated for log file delivery.
  • snsTopicName - (Optional) Name of the Amazon SNS topic defined for notification of log file delivery.
  • tags - (Optional) Map of tags to assign to the trail. If configured with a provider defaultTags configuration block present, tags with matching keys will overwrite those defined at the provider-level.

eventSelector

  • dataResource - (Optional) Configuration block for data events. See details below.
  • excludeManagementEventSources (Optional) - A set of event sources to exclude. Valid values include: kmsAmazonawsCom and rdsdataAmazonawsCom. includeManagementEvents must be set totrue to allow this.
  • includeManagementEvents - (Optional) Whether to include management events for your trail. Defaults to true.
  • readWriteType - (Optional) Type of events to log. Valid values are readOnly, writeOnly, all. Default value is all.

dataResource

  • type - (Required) Resource type in which you want to log data events. You can specify only the following value: "AWS::S3::Object", "AWS::Lambda::Function" and "AWS::DynamoDB::Table".
  • values - (Required) List of ARN strings or partial ARN strings to specify selectors for data audit events over data resources. ARN list is specific to single-valued type. For example, arn:aws:s3:::<bucketName>/ for all objects in a bucket, arn:aws:s3:::<bucketName>/key for specific objects, arn:aws:lambda for all lambda events within an account, arn:aws:lambda:<region>:<accountNumber>:function:<functionName> for a specific Lambda function, arn:aws:dynamodb for all DDB events for all tables within an account, or arn:aws:dynamodb:<region>:<accountNumber>:table/<tableName> for a specific DynamoDB table.

insightSelector

  • insightType - (Optional) Type of insights to log on a trail. Valid values are: apiCallRateInsight and apiErrorRateInsight.

Advanced Event Selector Arguments

  • fieldSelector (Required) - Specifies the selector statements in an advanced event selector. Fields documented below.
  • name (Optional) - Name of the advanced event selector.

Field Selector Arguments

  • field (Required) - Field in an event record on which to filter events to be logged. You can specify only the following values: readOnly, eventSource, eventName, eventCategory, resourcesType, resourcesArn.
  • endsWith (Optional) - A list of values that includes events that match the last few characters of the event record field specified as the value of field.
  • equals (Optional) - A list of values that includes events that match the exact value of the event record field specified as the value of field. This is the only valid operator that you can use with the readOnly, eventCategory, and resourcesType fields.
  • notEndsWith (Optional) - A list of values that excludes events that match the last few characters of the event record field specified as the value of field.
  • notEquals (Optional) - A list of values that excludes events that match the exact value of the event record field specified as the value of field.
  • notStartsWith (Optional) - A list of values that excludes events that match the first few characters of the event record field specified as the value of field.
  • startsWith (Optional) - A list of values that includes events that match the first few characters of the event record field specified as the value of field.

Attributes Reference

In addition to all arguments above, the following attributes are exported:

  • arn - ARN of the trail.
  • homeRegion - Region in which the trail was created.
  • id - Name of the trail.
  • tagsAll - Map of tags assigned to the resource, including those inherited from the provider defaultTags configuration block.

Import

Cloudtrails can be imported using the name, e.g.,

$ terraform import aws_cloudtrail.sample my-sample-trail