Table of Contents

The Error

Error deleting S3 Bucket: BucketNotEmpty: The bucket you tried to delete is not empty

What Causes This

Terraform cannot delete an S3 bucket that still contains objects. This includes regular objects, versioned objects, delete markers, and incomplete multipart uploads.

How to Fix It

Solution 1: Use force_destroy

resource "aws_s3_bucket" "data" {
  bucket        = "my-data-bucket"
  force_destroy = true  # Deletes all objects before destroying bucket
}

Solution 2: Empty Bucket Before Destroy

# Remove all objects
aws s3 rm s3://my-bucket --recursive

# If versioning is enabled, also remove versions and delete markers
aws s3api list-object-versions --bucket my-bucket \
  --query 'Versions[].{Key:Key,VersionId:VersionId}' --output json | \
  jq -c '.[]' | while read obj; do
    key=$(echo $obj | jq -r '.Key')
    vid=$(echo $obj | jq -r '.VersionId')
    aws s3api delete-object --bucket my-bucket --key "$key" --version-id "$vid"
  done

# Remove delete markers too
aws s3api list-object-versions --bucket my-bucket \
  --query 'DeleteMarkers[].{Key:Key,VersionId:VersionId}' --output json | \
  jq -c '.[]' | while read obj; do
    key=$(echo $obj | jq -r '.Key')
    vid=$(echo $obj | jq -r '.VersionId')
    aws s3api delete-object --bucket my-bucket --key "$key" --version-id "$vid"
  done

# Then destroy
terraform destroy

Solution 3: Lifecycle Prevent Destroy

# For critical buckets, prevent accidental deletion
resource "aws_s3_bucket" "critical" {
  bucket = "production-data"

  lifecycle {
    prevent_destroy = true
  }
}

Prevention Tips

  1. Pin provider versions — avoid surprise breaking changes
  2. Use CI/CD — catch errors before they hit production
  3. Test with terraform plan — always review before applying
  4. Keep Terraform updated — newer versions have better error messages
  5. Use terraform validate — catches syntax errors early

Hands-On Courses

Learn to avoid these errors with interactive, project-based courses:

Conclusion

This error is common and fixable. Follow the solutions above, and check our Terraform course for hands-on training that covers real-world troubleshooting scenarios.