locals { buckets = { cloudtrail = coalesce(var.bucket_names.cloudtrail, "${var.name_prefix}-cloudtrail-logs") flowlogs = coalesce(var.bucket_names.flowlogs, "${var.name_prefix}-flowlogs") } bucket_ids = merge( { for key, bucket in aws_s3_bucket.protected : key => bucket.id }, { for key, bucket in aws_s3_bucket.unprotected : key => bucket.id }, ) vault_kms_key_id = var.protect_from_destroy ? aws_kms_key.vault_protected[0].key_id : aws_kms_key.vault_unprotected[0].key_id trail_arn = "arn:aws:cloudtrail:${var.region}:${var.account_id}:trail/${var.trail_name}" kms_policy = jsonencode({ Version = "2012-10-17" Id = "key-consolepolicy-3" Statement = [{ Sid = "Enable IAM User Permissions" Effect = "Allow" Principal = { AWS = "arn:aws:iam::${var.account_id}:root" } Action = "kms:*" Resource = "*" }] }) bucket_policies = { cloudtrail = jsonencode({ Version = "2012-10-17" Statement = [ { Sid = "AWSCloudTrailAclCheck20150319-fbd4fef1-e790-49e5-8746-eb45d0ff5866" Effect = "Allow" Principal = { Service = "cloudtrail.amazonaws.com" } Action = "s3:GetBucketAcl" Resource = "arn:aws:s3:::${local.buckets.cloudtrail}" Condition = { StringEquals = { "AWS:SourceArn" = local.trail_arn } } }, { Sid = "AWSCloudTrailWrite20150319-2640129e-451d-4772-b3b0-faea699af22a" Effect = "Allow" Principal = { Service = "cloudtrail.amazonaws.com" } Action = "s3:PutObject" Resource = "arn:aws:s3:::${local.buckets.cloudtrail}/AWSLogs/${var.account_id}/*" Condition = { StringEquals = { "AWS:SourceArn" = local.trail_arn "s3:x-amz-acl" = "bucket-owner-full-control" } } }, ] }) flowlogs = jsonencode({ Version = "2012-10-17" Id = "AWSLogDeliveryWrite20150319" Statement = [ { Sid = "AWSLogDeliveryWrite" Effect = "Allow" Principal = { Service = "delivery.logs.amazonaws.com" } Action = "s3:PutObject" Resource = "arn:aws:s3:::${local.buckets.flowlogs}/AWSLogs/${var.account_id}/*" Condition = { StringEquals = { "s3:x-amz-acl" = "bucket-owner-full-control" "aws:SourceAccount" = var.account_id } ArnLike = { "aws:SourceArn" = "arn:aws:logs:${var.region}:${var.account_id}:*" } } }, { Sid = "AWSLogDeliveryAclCheck" Effect = "Allow" Principal = { Service = "delivery.logs.amazonaws.com" } Action = "s3:GetBucketAcl" Resource = "arn:aws:s3:::${local.buckets.flowlogs}" Condition = { StringEquals = { "aws:SourceAccount" = var.account_id } ArnLike = { "aws:SourceArn" = "arn:aws:logs:${var.region}:${var.account_id}:*" } } }, ] }) } lifecycle_rules = { cloudtrail = { id = "DeleteAfter3months" expiration_days = 90 } flowlogs = { id = "Housekeep" expiration_days = 7 } } }