Sets up a GuardDuty Publishing Destination with necessary S3 bucket and KMS key configurations.

Terraform Template

data "aws_caller_identity" "current" {
}

data "aws_iam_policy_document" "bucket_pol" {

  statement {
    actions = ["s3:PutObject"]
    resources = ["${aws_s3_bucket.gd_bucket.arn}/*"]
    sid = "Allow PutObject"
  }

  statement {
    actions = ["s3:GetBucketLocation"]
    resources = [aws_s3_bucket.gd_bucket.arn]
    sid = "Allow GetBucketLocation"
  }
}

data "aws_iam_policy_document" "kms_pol" {

  statement {
    actions = ["kms:GenerateDataKey"]
    resources = ["arn:aws:kms:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:key/*"]
    sid = "Allow GuardDuty to encrypt findings"
  }

  statement {
    actions = ["kms:*"]
    resources = ["arn:aws:kms:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:key/*"]
    sid = "Allow all users to modify/delete key (test only)"
  }
}

data "aws_region" "current" {
}

resource "aws_guardduty_detector" "test_gd" {
  enable = true
}

resource "aws_guardduty_publishing_destination" "test" {
  depends_on = ["aws_s3_bucket_policy.gd_bucket_policy"]
  destination_arn = aws_s3_bucket.gd_bucket.arn
  detector_id = aws_guardduty_detector.test_gd.id
  kms_key_arn = aws_kms_key.gd_key.arn
}

resource "aws_kms_key" "gd_key" {
  deletion_window_in_days = 7
  description = "Temporary key for AccTest of TF"
  policy = data.aws_iam_policy_document.kms_pol.json
}

resource "aws_s3_bucket" "gd_bucket" {
  bucket = "example"
  force_destroy = true
}

resource "aws_s3_bucket_acl" "gd_bucket_acl" {
  acl = "private"
  bucket = aws_s3_bucket.gd_bucket.id
}

resource "aws_s3_bucket_policy" "gd_bucket_policy" {
  bucket = aws_s3_bucket.gd_bucket.id
  policy = data.aws_iam_policy_document.bucket_pol.json
}