Home > Mobile >  Terraform - Manage destroy of everything except the S3 bucket
Terraform - Manage destroy of everything except the S3 bucket

Time:01-10

We create all our AWS resources using Terraform and we are having issues with our S3 bucket. We are in a development environnement so sometimes we wants to destroy everything and recreate everything except the S3 Bucket.

We tried to implement the following attribute for our S3 Bucket :

resource "aws_s3_bucket" "bucket" {
  bucket = "${var.name}-${var.environment}-data"

  lifecycle {
    prevent_destroy = true
  }
}

It seems like the prevent_destroy attribute is not working as we thought it would work. Instead of skipping the deletion of the bucket and terminate the terraform destroy with a success state, it fails instead (as if this attribute tells terraform to fail on purpose).

I've found out similar conclusions already on stackoverflow but what would be the best way to avoid that issue and also the way that would be the best practice please ?

We use also github actions so we have thought of using it to create the bucket but if there's a solution using terraform, it will be easier for us (as there are other resources that are linked to the bucket id).

Thanks in advance !

CodePudding user response:

prevent_destroy is used as a safety measure to ensure that the deletion of the resource does not occur. It is expected that it errors out. From the docs:

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

so you shouldn't be using this meta-argument for your purposes.

Instead, if you want to delete everything except the bucket, you will need to remove the bucket from the terraform state before running the destroy operation, e.g.:

terraform state rm aws_s3_bucket.bucket
terraform destroy

for your next deployment, you will then need to import the bucket back into the terraform state before running the apply:

terraform import aws_s3_bucket.bucket bucket-name
terraform apply
  • Related