|
| 1 | +data "aws_caller_identity" "current" { |
| 2 | +} |
| 3 | + |
| 4 | +locals { |
| 5 | + account_id = data.aws_caller_identity.current.account_id |
| 6 | + |
| 7 | + # Account IDs that will have access to stream CloudTrail logs |
| 8 | + account_ids = concat([local.account_id], var.allowed_account_ids) |
| 9 | + |
| 10 | + # Format account IDs into necessary resource lists. |
| 11 | + bucket_policy_put_resources = formatlist("${aws_s3_bucket.this.arn}/AWSLogs/%s/*", local.account_ids) |
| 12 | + kms_key_encrypt_resources = formatlist("arn:aws:cloudtrail:*:%s:trail/*", local.account_ids) |
| 13 | +} |
| 14 | + |
| 15 | +resource "aws_s3_bucket" "this" { |
| 16 | + bucket = "${local.account_id}-${var.region}-vpcflowlog" |
| 17 | + acl = "private" |
| 18 | + tags = var.tags |
| 19 | + |
| 20 | + lifecycle_rule { |
| 21 | + enabled = true |
| 22 | + |
| 23 | + transition { |
| 24 | + days = 30 |
| 25 | + storage_class = "STANDARD_IA" |
| 26 | + } |
| 27 | + |
| 28 | + } |
| 29 | + |
| 30 | + logging { |
| 31 | + target_bucket = var.logging_bucket |
| 32 | + target_prefix = "${local.account_id}-${var.region}-vpcflowlog/" |
| 33 | + } |
| 34 | + |
| 35 | + server_side_encryption_configuration { |
| 36 | + rule { |
| 37 | + apply_server_side_encryption_by_default { |
| 38 | + sse_algorithm = "aws:kms" |
| 39 | + kms_master_key_id = aws_kms_key.this.arn |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + } |
| 44 | + |
| 45 | + versioning { |
| 46 | + enabled = true |
| 47 | + } |
| 48 | + |
| 49 | + lifecycle { |
| 50 | + prevent_destroy = true |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +resource "aws_s3_bucket_public_access_block" "this" { |
| 55 | + bucket = aws_s3_bucket.this.id |
| 56 | + block_public_acls = true |
| 57 | + block_public_policy = true |
| 58 | + ignore_public_acls = true |
| 59 | + restrict_public_buckets = true |
| 60 | +} |
| 61 | + |
| 62 | +data "aws_iam_policy_document" "this" { |
| 63 | + statement { |
| 64 | + actions = ["s3:GetBucketAcl"] |
| 65 | + effect = "Allow" |
| 66 | + resources = [aws_s3_bucket.this.arn] |
| 67 | + |
| 68 | + principals { |
| 69 | + type = "Service" |
| 70 | + identifiers = ["delivery.logs.amazonaws.com"] |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + statement { |
| 75 | + actions = ["s3:PutObject"] |
| 76 | + effect = "Allow" |
| 77 | + resources = local.bucket_policy_put_resources |
| 78 | + |
| 79 | + condition { |
| 80 | + test = "StringEquals" |
| 81 | + variable = "s3:x-amz-acl" |
| 82 | + values = ["bucket-owner-full-control"] |
| 83 | + } |
| 84 | + |
| 85 | + principals { |
| 86 | + type = "Service" |
| 87 | + identifiers = ["delivery.logs.amazonaws.com"] |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | +} |
| 92 | + |
| 93 | +resource "aws_s3_bucket_policy" "this" { |
| 94 | + bucket = aws_s3_bucket.this.id |
| 95 | + policy = data.aws_iam_policy_document.this.json |
| 96 | +} |
0 commit comments