Last active
March 18, 2024 03:26
-
-
Save adamcousins/8777d9d77e718efe5e1dc09ab000d76b to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env python3 | |
""" | |
Originally from Lyle Scott, III // [email protected] | |
https://gist.github.com/LyleScott/fefed8ee9708eece2e6b99c8845efc2d | |
$ python3 rm_empty_s3_buckets.py --help | |
usage: rm_empty_s3_buckets.py [-h] [-p PROFILE] [-b BUCKET_PREFIX] [-ne] | |
optional arguments: | |
-h, --help show this help message and exit | |
-p PROFILE, --profile PROFILE | |
Use a specific profile for bucket operations. Default: | |
"default" profile in ~/.aws/config or AWS_PROFILE | |
environment variable | |
-b BUCKET_PREFIX, --bucket_prefix BUCKET_PREFIX | |
Delete buckets only with this prefix | |
-ne, --not-empty | |
Delete empty and non-empty buckets | |
python3 rm_empty_s3_buckets.py | |
Delete S3 bucket foobarmancan? | |
y/N: y | |
> Deleted: foobarmancan | |
Delete S3 bucket bingbangboom? | |
y/N: | |
""" | |
from __future__ import print_function | |
import argparse | |
import sys | |
import boto3 | |
from botocore.exceptions import ClientError | |
def find_empty_buckets(bucket_prefix=None, profile=None, not_empty=None): | |
"""Delete a bucket (and all object versions).""" | |
kwargs = {} | |
if bucket_prefix: | |
print("deleting all objects and bucket with bucket name prefix " + bucket_prefix) | |
else: | |
print("deleting all objects and buckets") | |
if not_empty: | |
print("deleting empty and non-empty buckets") | |
else: | |
print("deleting empty buckets only") | |
if profile: | |
kwargs['profile_name'] = profile | |
session = boto3.Session(**kwargs) | |
s3 = session.resource(service_name='s3') | |
for bucket in s3.buckets.all(): | |
if bucket.name.startswith(bucket_prefix): | |
is_empty = [] == [i for i in bucket.objects.limit(1).all()] | |
# Bail if the S3 bucket isn't empty. | |
if not is_empty and not_empty == False: | |
continue | |
# Indicate Bucket Empty or Not-Empty Status | |
if is_empty: | |
bucket_emptyness = "empty" | |
elif not is_empty: | |
bucket_emptyness = "not empty" | |
# Prompt if the S3 bucket should be deleted and do so. | |
try: | |
print("S3 Bucket " + bucket.name + " is " + bucket_emptyness) | |
i = input('Delete S3 bucket {}?\ny/N: '.format(bucket.name)) | |
if i.lower() == 'y': | |
bucket.object_versions.delete() | |
bucket.delete() | |
print('> Deleted: {}'.format(bucket.name)) | |
except ClientError as ex: | |
print('error: {}'.format(ex.response['Error'])) | |
sys.exit(1) | |
print('done') | |
def _parse_args(): | |
"""A helper for parsing command line arguments.""" | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-b', '--bucket_prefix', default='', | |
help='Filter on a specific bucket prefix.') | |
parser.add_argument('-p', '--profile', default='', | |
help='Use a specific profile for bucket operations. ' | |
'Default: "default" profile in ~/.aws/config or ' | |
'AWS_PROFILE environment variable') | |
parser.add_argument('-ne', '--not-empty', action='store_true', default=False, | |
help='Delete empty and non-empty buckets') | |
return parser.parse_args() | |
def _main(): | |
"""Script execution handler.""" | |
args = _parse_args() | |
find_empty_buckets(bucket_prefix=args.bucket_prefix, profile=args.profile, not_empty=args.not_empty) | |
if __name__ == '__main__': | |
_main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment