Created
June 17, 2024 11:53
-
-
Save lmarcondes/2691fba0557da343bec35447d31f3933 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
from argparse import ArgumentParser | |
def delete_objects(bucket): | |
bucket.objects.all().delete() | |
def delete_bucket(bucket): | |
try: | |
delete_objects(bucket) | |
bucket.delete() | |
return | |
except KeyboardInterrupt as exception: | |
raise exception | |
# except: | |
# delete_bucket(bucket) | |
def delete_all_buckets(): | |
s3 = boto3.client('s3') | |
buckets = s3.list_buckets()['Buckets'] | |
print(f''' | |
Buckets to delete:\n{buckets} | |
''') | |
for bucket in buckets: | |
print(f'deleting bucket {bucket}') | |
bucket_name = bucket['Name'] | |
s3_resource = boto3.resource('s3') | |
s3_bucket = s3_resource.Bucket(bucket_name) | |
delete_bucket(s3_bucket) | |
if __name__ == "__main__": | |
parser = ArgumentParser() | |
parser.add_argument('-a','--all', default=False, | |
action='store_true') | |
parser.add_argument('-b', '--bucket', | |
default=None) | |
parser.add_argument('-oo','--only-objects', default=False, | |
action='store_true') | |
args = parser.parse_args() | |
if args.all: | |
print(''' | |
====== CAUTION ====== | |
This script will delete every S3 bucket | |
registered to your account. | |
Use it carefully !! | |
''') | |
if input('Are you sure you want to continue? y/N').lower() == 'y': | |
delete_all_buckets() | |
else: | |
if args.bucket: | |
if args.only_objects: | |
delete_objects(args.bucket) | |
else: | |
delete_bucket(args.bucket) | |
else: | |
raise ValueError('Bucket nao definido') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment