Skip to content

Instantly share code, notes, and snippets.

@okomestudio
Last active January 14, 2016 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okomestudio/27ad5622c85150a1d316 to your computer and use it in GitHub Desktop.
Save okomestudio/27ad5622c85150a1d316 to your computer and use it in GitHub Desktop.
Script to delete S3 bucket with contents.
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
"""Delete a S3 bucket with contents.
"""
from __future__ import absolute_import
from gevent import monkey ; monkey.patch_all()
from argparse import ArgumentParser
import boto3
import botocore
import gevent
import gevent.pool
def main(args):
bucket_name = args.bucket
s3 = boto3.resource('s3')
try:
s3.meta.client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e:
ecode = int(e.response['Error']['Code'])
if ecode == 404:
raise IOError('no bucket named {} found'.format(bucket_name))
else:
bucket = s3.Bucket(bucket_name)
def do_delete(key):
print 'deleting key s3://{}/{}'.format(key.bucket_name, key.key)
if not args.dry_run:
key.delete()
pool = gevent.pool.Pool(100)
for key in bucket.objects.all():
pool.spawn(do_delete, key)
pool.join()
bucket_name = bucket.name
print 'deleting bucket s3://{}'.format(bucket_name)
if not args.dry_run:
while 1:
try:
bucket.delete()
except botocore.exceptions.ClientError:
# retry...
gevent.sleep(1)
else:
break
print 's3://{} deleted'.format(bucket_name)
if __name__ == '__main__':
p = ArgumentParser(description=__doc__.strip())
p.add_argument(
'bucket', type=str,
help='S3 bucket name')
p.add_argument(
'--dry-run', action='store_true', default=False,
help='set for a dry run (not actually delete)')
main(p.parse_args())
@okomestudio
Copy link
Author

Perhaps it is better to make this work like rm, where a bucket cannot be deleted when there are contents inside. Only by supplying an additional argument (e.g., -f or --force), the script goes ahead and delete everything.

That sounds like a safer approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment