Wednesday, May 22, 2013

Easy way to delete all objects from S3 bucket

I had to delete a bucket from S3 server But the problem is, a bucket can only be deleted if it is empty. Delete objects using User Interface on Amazon S3 management console is a tough job and very time consuming. Take a look at the following screenshot.


If a bucket hold more then 10000 objects then how you will do it?

If you are familier with Amazon SDK PHP2 go with the following code to accomplish this task easily..
require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\S3\Model\ClearBucket;

$s3 = S3Client::factory(array(
    'key' => 'write_your_key_here',
    'secret' => 'write_your_secret_key_here'
));

$bucket = 'your_bucket_name';

$clear = new ClearBucket($s3, $bucket);
$clear->clear();

// Delete the bucket
$result = $s3->deleteBucket(array('Bucket' => $bucket));

// Wait until the bucket is not accessible
$result1 = $s3->waitUntilBucketNotExists(array('Bucket' => $bucket));

Another way to do this..
$bucket = 'your_bucket_name';

$iterator = $s3->getIterator('ListObjects', array(
    'Bucket' => $bucket
));

$s3->registerStreamWrapper();

foreach ($iterator as $object) {
    unlink('s3://'.$bucket.'/'.$object['Key']);
}

No comments:

Post a Comment