Skip to content

Instantly share code, notes, and snippets.

@joshghent
Created August 5, 2019 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshghent/a2b94fba688e35d3fe86a84439d5d063 to your computer and use it in GitHub Desktop.
Save joshghent/a2b94fba688e35d3fe86a84439d5d063 to your computer and use it in GitHub Desktop.
#!/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