Created
April 5, 2018 03:31
-
-
Save LyleScott/fefed8ee9708eece2e6b99c8845efc2d to your computer and use it in GitHub Desktop.
Find all S3 buckets that are empty and prompt to delete them
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 | |
""" | |
Lyle Scott, III // [email protected] | |
$ python3 rm_empty_s3_buckets.py --help | |
usage: rm_empty_s3_buckets.py [-h] [-p PROFILE] | |
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 | |
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(profile=None): | |
"""Delete a bucket (and all object versions).""" | |
kwargs = {} | |
if profile: | |
kwargs['profile_name'] = profile | |
session = boto3.Session(**kwargs) | |
s3 = session.resource(service_name='s3') | |
for bucket in s3.buckets.all(): | |
is_empty = [] == [i for i in bucket.objects.limit(1).all()] | |
# Bail if the S3 bucket isn't empty. | |
if not is_empty: | |
continue | |
# Prompt if the S3 bucket should be deleted and do so. | |
try: | |
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('-p', '--profile', default='', | |
help='Use a specific profile for bucket operations. ' | |
'Default: "default" profile in ~/.aws/config or ' | |
'AWS_PROFILE environment variable') | |
return parser.parse_args() | |
def _main(): | |
"""Script execution handler.""" | |
args = _parse_args() | |
find_empty_buckets(profile=args.profile) | |
if __name__ == '__main__': | |
_main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment