J. Patwary
J. Patwary

Reputation: 477

Terraform update existing S3 configuration

Is there a way for Terraform to make changes to an existing S3 bucket without affecting the creation or deletion of the bucket?

For example, I want to use Terraform to enable S3 replication across several AWS accounts. The S3 buckets already exist, and I simply want to enable a replication rule (via a pipeline) without recreating, deleting, or emptying the bucket.

My code looks like this:

data "aws_s3_bucket" "test" {
  bucket = "example_bucket"
}

data "aws_iam_role" "s3_replication" {
  name = "example_role"
}

resource "aws_s3_bucket" "source" {
  bucket = data.aws_s3_bucket.example_bucket.id

  versioning {
    enabled = true
  }

  replication_configuration {
    role = data.aws_iam_role.example_role.arn

    rules {
          id = "test"
          status = "Enabled"

          destination {
            bucket = "arn:aws:s3:::dest1"
          }
    }
    rules {
          id = "test2"
          status = "Enabled"

          destination {
            bucket = "arn:aws:s3:::dest2"
          }
    }
  }
}

When I try to do it this way, Terraform apply tries to delete the existing bucket and create a new one instead of just updating the configuration. I don't mind trying terraform import, but my concern is that this will destroy the bucket when I run terraform destroy as well. I would like to simply apply and destroy the replication configuration, not the already existing bucket.

Upvotes: 1

Views: 2582

Answers (1)

Marcin
Marcin

Reputation: 238985

I would like to simply apply and destroy the replication configuration, not the already existing bucket.

Sadly, you can't do this. Your bucket must be imported to TF so that it can be managed by it.

I don't mind trying terraform import, but my concern is that this will destroy the bucket when I run terraform destroy as well.

To protect against this, you can use prevent_destroy:

This meta-argument, when set to true, will cause Terraform to reject with an error any plan that would destroy the infrastructure object associated with the resource, as long as the argument remains present in the configuration.

Upvotes: 3

Related Questions