Skip to content

Instantly share code, notes, and snippets.

@joshghent

joshghent/empty.py

Created Aug 5, 2019
Embed
What would you like to do?
#!/usr/bin/env python3
"""
Run the following
$ python3 empty.py
You need to install boto3 before by running `pip install boto3 --user`
"""
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.
print('Empty Bucket: {}'.format(bucket.name))
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
You can’t perform that action at this time.