You can directly delete an empty S3 bucket using a boto3 client or resource. If the bucket contains objects then you need to first delete all the objects and then only you can delete the bucket.
Note: If S3 versioning is enabled, you also need to disable the versioning first.
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 as s3 bucket with objects
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 a s3 bucket cat << EOF > delete_bucket.py import argparse import boto3 from botocore.exceptions import ClientError parser = argparse.ArgumentParser(description='Delete a s3 bucket') parser.add_argument('--bucket_name', type=str, help='The name of the bucket you want to delete') args = parser.parse_args() def delete_bucket(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() print("S3 bucket deleted successfully!") except ClientError as e: print(e) bucket_name = args.bucket_name delete_bucket(bucket_name) EOF |
Step 3: Execute the script to force delete an S3 bucket with objects
1 2 |
## Delete a s3 bucket using python boto3 python3 delete_bucket.py --bucket_name cloudaffaire |