Getting an early jump on spring cleaning in the new year? As you may well know you cannot simply delete a non-empty S3 bucket. I’ve created a handy little python script to help. Simply save the below script as s3Deleter.py and execute with s3Deleter.py <bucketname> <list || delete>
import boto3 import sys try: bucketname = sys.argv[1] except: print ("you failed to enter a bucket name, please enter a valid bucket name as the first argument") sys.exit(1) try: action = sys.argv[2].lower() except: print ("you failed to enter a bucket action, please enter a valid bucket action (list or delete) as the second argument") sys.exit(1) allowed_actions = ['list','delete'] if action not in allowed_actions: print("you provided an invalid action argument. Please enter either list or delete as the argument") sys.exit(1) s3 = boto3.resource('s3') bucket = s3.Bucket(bucketname) def bucket_list(): print("listing all files in the following S3 Bucket: " + str(bucketname)) for key in bucket.objects.all(): print(key.key) return def delete_bucket_contents(): print("deleting all files in the following S3 Bucket: " + str(bucketname)) bucket.objects.all().delete() return def delete_bucket(): print("Deleting the bucket: " + str(bucketname)) bucket.delete() return def main(): if action == "list": bucket_list() if action == "delete": delete_bucket_contents() delete_bucket() main()