How to empty S3 bucket using AWS CLI

Viewed 2919

I'm trying to empty an S3 bucket using CLI.

  1. I tried aws s3 rm --recursive command which doesn't empty my bucket as it has versioned enabled.

  2. I tried aws s3 rb --force command to forcefully delete the bucket, which doesn't work as well. It throws this error BucketNotEmpty: The bucket you tried to delete is not empty. You must delete all versions in the bucket.

I really need to get this done using CLI. Is there a way to do it. Please help. The end goal is to delete the bucket. Thanks in advance.

1 Answers

If you can only use the CLI try this:

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}}')"
Related