Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to empty s3 bucket using boto3?

I was thinking about deleting and then re-creating bucket (bad option which I realised later).

Then how can delete all objects from the bucket?

I tried this : http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.delete_objects

But it deletes multiple objects not all.

can you suggest what is the best way to empty bucket ?

like image 577
Tushar Niras Avatar asked Apr 10 '17 14:04

Tushar Niras


People also ask

How do I quickly clear my S3 bucket?

Sign in to the AWS Management Console and open the Amazon S3 console at https://console.aws.amazon.com/s3/ . In the Bucket name list, select the option next to the name of the bucket that you want to empty, and then choose Empty.

How long does it take AWS to delete an S3 bucket?

Deleting S3 buckets, option 1: out-of-the-box tools According to AWS support, it can take up to several days for the bucket to be emptied!


2 Answers

Just use aws cli.

aws s3 rm s3://mybucket --recursive 

Well, for longer answer if you insists to use boto3. This will send a delete marker to s3. No folder handling required. bucket.Object.all will create a iterator that not limit to 1K .

import boto3     s3 = boto3.resource('s3') bucket = s3.Bucket('my-bucket') # suggested by Jordon Philips  bucket.objects.all().delete() 
like image 65
mootmoot Avatar answered Sep 17 '22 21:09

mootmoot


If versioning is enabled, there's a similar call to the other answer to delete all object versions:

import boto3 s3 = boto3.resource('s3') bucket = s3.Bucket('bucket-name') bucket.object_versions.delete() 
like image 26
kgutwin Avatar answered Sep 18 '22 21:09

kgutwin