Skip to content

Instantly share code, notes, and snippets.

@aashishrbhandari
Created September 10, 2023 07:34
Show Gist options
  • Save aashishrbhandari/47431ff500ce83868d0c18b031186fe0 to your computer and use it in GitHub Desktop.
Save aashishrbhandari/47431ff500ce83868d0c18b031186fe0 to your computer and use it in GitHub Desktop.
/** Enable CloudTrail and Logging to S3 **/
# Create S3 Bucket for CloudTrail Events
resource "aws_s3_bucket" "cloudtrail_s3_bucket" {
bucket_prefix = "aws-cloudtrail-logallapi"
}
# Enable CloudTrail Log to S3
resource "aws_cloudtrail" "cloudtrail_event_api" {
name = "LogAllAPI"
s3_bucket_name = aws_s3_bucket.cloudtrail_s3_bucket.id
is_multi_region_trail = true
enable_log_file_validation = true
}
# CloudTrail S3 Bucket Policy
data "aws_iam_policy_document" "cloudtrail_s3_bucket_policy_document" {
statement {
sid = "AWSCloudTrailAclCheck"
effect = "Allow"
principals {
type = "Service"
identifiers = ["cloudtrail.amazonaws.com"]
}
actions = ["s3:GetBucketAcl"]
resources = [aws_s3_bucket.cloudtrail_s3_bucket.arn]
}
statement {
sid = "AWSCloudTrailWrite"
effect = "Allow"
principals {
type = "Service"
identifiers = ["cloudtrail.amazonaws.com"]
}
actions = ["s3:PutObject"]
resources = ["${aws_s3_bucket.cloudtrail_s3_bucket.arn}/*"]
condition {
test = "StringEquals"
variable = "s3:x-amz-acl"
values = ["bucket-owner-full-control"]
}
}
}
# Attach CloudTrail S3 Bucket Policy
resource "aws_s3_bucket_policy" "cloudtrail_s3_bucket_policy_association" {
bucket = aws_s3_bucket.cloudtrail_s3_bucket.id
policy = data.aws_iam_policy_document.cloudtrail_s3_bucket_policy_document.json
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment