You can use the below script to delete all objects (files) and keys (folders) in an S3 bucket using boto3.
Step 1: Install and configure boto3
https://cloudaffaire.com/how-to-install-python-boto3-sdk-for-aws/
https://cloudaffaire.com/how-to-configure-python-boto3-sdk-for-aws/
https://pypi.org/project/argparse/
Step 2: Create a python script to delete all objects in an S3 bucket
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
## Create a python script to delete all objects in S3 bucket cat << EOF > delete_objects.py import argparse import boto3 from botocore.exceptions import ClientError parser = argparse.ArgumentParser(description='Delete all objects in an s3 bucket') parser.add_argument('--bucket_name', type=str, help='The name of the bucket') args = parser.parse_args() def delete_objects(bucket_name): try: s3 = boto3.resource('s3') s3_bucket = s3.Bucket(bucket_name) bucket_versioning = s3.BucketVersioning(bucket_name) if bucket_versioning.status == 'Enabled': s3_bucket.object_versions.delete() else: s3_bucket.objects.all().delete() #s3_bucket.delete() ##if u want to delete the bucket as well print("all objects deleted!") except ClientError as e: print(e) bucket_name = args.bucket_name delete_objects(bucket_name) EOF |
Step 3: Execute the script to delete all objects in an S3 bucket
1 2 |
## Delete all objects in an s3 bucket python3 delete_object.py --bucket_name cloudaffaire |