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
- Pin provider versions — avoid surprise breaking changes
- Use CI/CD — catch errors before they hit production
- Test with
terraform plan— always review before applying - Keep Terraform updated — newer versions have better error messages
- Use
terraform validate— catches syntax errors early
Hands-On Courses
Learn to avoid these errors with interactive, project-based courses:
- Terraform for Beginners on CopyPasteLearn
- Terraform By Example — practical code examples
- Terraform Cheat Sheet — quick reference for all commands
Related Articles
- Terraform Troubleshooting - Common Errors and Solutions
- Terraform Enabling and Using Debugging
- Debugging with TFLint
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.

