Sep 19, 2018

How to delete a S3 bucket

A S3 bucket needs to be completely empty before it can be deleted. You must delete all the objects manually or setup a lifecycle policy to remove everything after 24 hours or you may use 3rd party tool, s3nukem.

Delete a Bucket:
You can delete a bucket and its content programmatically using AWS SDK. You can also use lifecycle configuration on a bucket to empty its content and then delete the bucket.

-->>> There are additional options, such as using Amazon S3 console and AWS CLI, but there are limitations on this method based on the number of objects in your bucket and the bucket's versioning status.<----

Here are some CLI commands that you can use to delete everything from the bucket:

-= Delete all the versions =-
aws s3api list-object-versions --bucket mybucket --output json --query 'Versions[].[Key, VersionId]' | jq -r '.[] | "--key '\''" + .[0] + "'\'' --version-id " + .[1]' | xargs -L1 aws s3api delete-object --bucket mybucket

-= Delete ALL the delete markers =-
aws s3api list-object-versions --bucket mybucket --output json --query 'DeleteMarkers[].[Key, VersionId]' | jq -r '.[] | "--key '\''" + .[0] + "'\'' --version-id " + .[1]' | xargs -L1 aws s3api delete-object --bucket mybucket

-= Delete all my multipart versions
aws s3api list-multipart-uploads --bucket mybucket --output json --query 'Uploads[*].[Key,UploadId]' | jq -r '.[] | "--key '\''" + .[0] + "'\'' --upload-id " + .[1]' | xargs -L1 aws s3api abort-multipart-upload --bucket mybucket --region myregion