Configures replication for AWS S3 buckets including IAM roles and policies for replication permissions.

Terraform Template

data "aws_iam_policy_document" "assume_role" {

  statement {
    actions = ["sts:AssumeRole"]
    effect = "Allow"

    principals {
      identifiers = ["s3.amazonaws.com"]
      type = "Service"
    }
  }
}

data "aws_iam_policy_document" "replication" {

  statement {
    actions = ["s3:GetReplicationConfiguration", "s3:ListBucket"]
    effect = "Allow"
    resources = [aws_s3_bucket.source.arn]
  }

  statement {
    actions = ["s3:GetObjectVersionForReplication", "s3:GetObjectVersionAcl", "s3:GetObjectVersionTagging"]
    effect = "Allow"
    resources = ["${aws_s3_bucket.source.arn}/*"]
  }

  statement {
    actions = ["s3:ReplicateObject", "s3:ReplicateDelete", "s3:ReplicateTags"]
    effect = "Allow"
    resources = ["${aws_s3_bucket.destination.arn}/*"]
  }
}

resource "aws_iam_policy" "replication" {
  name = "tf-iam-role-policy-replication-12345"
  policy = data.aws_iam_policy_document.replication.json
}

resource "aws_iam_role" "replication" {
  assume_role_policy = data.aws_iam_policy_document.assume_role.json
  name = "tf-iam-role-replication-12345"
}

resource "aws_iam_role_policy_attachment" "replication" {
  policy_arn = aws_iam_policy.replication.arn
  role = aws_iam_role.replication.name
}

resource "aws_s3_bucket" "destination" {
  bucket = "tf-test-bucket-destination-12345"
}

resource "aws_s3_bucket" "source" {
  bucket = "tf-test-bucket-source-12345"
  provider = "aws.central"
}

resource "aws_s3_bucket_acl" "source_bucket_acl" {
  acl = "private"
  bucket = aws_s3_bucket.source.id
  provider = "aws.central"
}

resource "aws_s3_bucket_replication_configuration" "replication" {
  bucket = aws_s3_bucket.source.id
  depends_on = ["aws_s3_bucket_versioning.source"]
  provider = "aws.central"
  role = aws_iam_role.replication.arn

  rule {

    destination {
      bucket = aws_s3_bucket.destination.arn
      storage_class = "STANDARD"
    }

    filter {
      prefix = "foo"
    }
    id = "foobar"
    status = "Enabled"
  }
}

resource "aws_s3_bucket_versioning" "destination" {
  bucket = aws_s3_bucket.destination.id

  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_versioning" "source" {
  bucket = aws_s3_bucket.source.id
  provider = "aws.central"

  versioning_configuration {
    status = "Enabled"
  }
}