Delete versioned S3 buckets
Posted: | Updated: | Tags: aws cloud storage tilRecursively deleting all objects in a bucket and the bucket itself can be done with the following command.
aws s3 rb s3://<bucket_name> --force
If the bucket has versioning enabled any object versions and delete markers will fail to delete. The following message will be returned.
remove_bucket failed: s3://<bucket_name> An error occurred (BucketNotEmpty) when calling the DeleteBucket operation: The bucket you tried to delete is not empty. You must delete all versions in the bucket.
The following set of command deletes all objects, versions, delete markers, and the bucket.
bucket_name=<bucket_name>
aws s3api delete-objects \
--bucket ${bucket_name} \
--delete "$(aws s3api list-object-versions \
--bucket "${bucket_name}" \
--output=json \
--query='{Objects: Versions[].{Key:Key,VersionId:VersionId}}')"
aws s3api delete-objects \
--bucket ${bucket_name} \
--delete "$(aws s3api list-object-versions \
--bucket ${bucket_name} \
--query='{Objects: DeleteMarkers[].{Key:Key,VersionId:VersionId}}')"
aws s3 rb s3://${bucket_name} --force