How to Delete All S3 Buckets using python
Before you run this script:
Install Boto3 using pip if you haven't already:
pip install boto3
.Configure your AWS credentials properly. You can either set them up using the AWS CLI (
aws configure
) or set environment variables (AWS_ACCESS_KEY_ID
andAWS_SECRET_ACCESS_KEY
).Ensure that the IAM user associated with your credentials has the necessary permissions to delete S3 buckets and objects. Be cautious about granting such permissions.
Make sure check your I AM console does user contains privileges to delete the Resources. In My case I have provide Admin Privileges to my user.
Also, I have added this code in case you are unable to delete a bucket due to certain reasons.
Code Reference:
import boto3
import botocore
def empty_bucket(s3_client, bucket_name):
# List all objects including versions
response = s3_client.list_object_versions(Bucket=bucket_name)
# Delete all objects including versions
if 'Versions' in response:
for obj in response['Versions']:
s3_client.delete_object(Bucket=bucket_name, Key=obj['Key'], VersionId=obj['VersionId'])
print(f"Deleted versioned object: {obj['Key']}")
# Delete all delete markers
if 'DeleteMarkers' in response:
for marker in response['DeleteMarkers']:
s3_client.delete_object(Bucket=bucket_name, Key=marker['Key'], VersionId=marker['VersionId'])
print(f"Deleted delete marker: {marker['Key']}")
# Empty the bucket
response = s3_client.list_objects_v2(Bucket=bucket_name)
if 'Contents' in response:
for obj in response['Contents']:
s3_client.delete_object(Bucket=bucket_name, Key=obj['Key'])
print(f"Deleted object: {obj['Key']}")
def delete_all_buckets():
# Create an S3 client
s3 = boto3.client('s3')
# List all buckets
response = s3.list_buckets()
# Iterate over each bucket, empty it, then delete it
for bucket in response['Buckets']:
bucket_name = bucket['Name']
print(f"Emptying bucket {bucket_name}...")
# Empty the bucket
try:
empty_bucket(s3, bucket_name)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'AccessDenied':
print(f"Access denied. Skipping bucket deletion: {bucket_name}")
continue
else:
raise
print(f"Deleting bucket {bucket_name}...")
# Delete the bucket
try:
s3.delete_bucket(Bucket=bucket_name)
print(f"Deleted bucket: {bucket_name}")
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'AccessDenied':
print(f"Access denied. Skipping bucket deletion: {bucket_name}")
else:
raise
if __name__ == "__main__":
delete_all_buckets()
Subscribe to my newsletter
Read articles from jeeva B directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
jeeva B
jeeva B
๐ Hey there! I'm Jeeva, a passionate DevOps and Cloud Engineer with a knack for simplifying complex infrastructures and optimizing workflows. With a strong foundation in Python and PySpark, I thrive on designing scalable solutions that leverage the power of the cloud. ๐ ๏ธ In my journey as a DevOps professional, I've honed my skills in automating deployment pipelines, orchestrating containerized environments, and ensuring robust security measures. Whether it's architecting cloud-native applications or fine-tuning infrastructure performance, I'm committed to driving efficiency and reliability at every step. ๐ป When I'm not tinkering with code or diving into cloud platforms, you'll likely find me exploring the latest trends in technology, sharing insights on DevOps best practices, or diving deep into data analysis with PySpark. ๐ Join me on this exhilarating ride through the realms of DevOps, Cloud Engineering where we'll unravel the complexities of modern IT landscapes and empower ourselves with the tools to build a more resilient digital future. Connect with me on LinkedIn: https://www.linkedin.com/in/jeevabalakrishnan