Guest User

Untitled

a guest
Nov 20th, 2017
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. """
  2. Lyle Scott, III // lyle@ls3.io
  3.  
  4. $ python nuke_s3_bucket.py --help
  5. usage: nuke_s3_bucket.py [-h] [-p PROFILE] bucket_name
  6.  
  7. positional arguments:
  8. bucket_name The bucket name to delete.
  9.  
  10. optional arguments:
  11. -h, --help show this help message and exit
  12. -p PROFILE, --profile PROFILE
  13. Use a specific profile for bucket operations. Default:
  14. "default" profile in ~/.aws/config or AWS_PROFILE
  15. environment variable
  16.  
  17. $ python3 nuke_s3_bucket.py bucket-name-goes-here
  18. Deleting bucket-name-goes-here ...done
  19.  
  20. $ python3 nuke_s3_bucket.py bucket-name-goes-here
  21. Deleting bucket-name-goes-here ...error: {'Code': 'NoSuchBucket', 'Message': 'The specified bucket does not exist', 'BucketName': 'bucket-name-goes-here'}
  22.  
  23. NOTE: S3 buckets don't need a region to be deleted; they are account global.
  24. """
  25. from __future__ import print_function
  26.  
  27. import argparse
  28. import sys
  29.  
  30. import boto3
  31. from botocore.exceptions import ClientError
  32.  
  33.  
  34. def delete_bucket(bucket_name, profile=None):
  35. """Delete a bucket (and all object versions)."""
  36. kwargs = {}
  37. if profile:
  38. kwargs['profile_name'] = profile
  39.  
  40. session = boto3.Session(**kwargs)
  41. print('Deleting {} ...'.format(bucket_name), end='')
  42.  
  43. try:
  44. s3 = session.resource(service_name='s3')
  45. bucket = s3.Bucket(bucket_name)
  46. bucket.object_versions.delete()
  47. bucket.delete()
  48. except ClientError as ex:
  49. print('error: {}'.format(ex.response['Error']))
  50. sys.exit(1)
  51.  
  52. print('done')
  53.  
  54.  
  55. def _parse_args():
  56. """A helper for parsing command line arguments."""
  57. parser = argparse.ArgumentParser()
  58. parser.add_argument('bucket_name', help='The bucket name to delete.')
  59. parser.add_argument('-p', '--profile', default='',
  60. help='Use a specific profile for bucket operations. '
  61. 'Default: "default" profile in ~/.aws/config or '
  62. 'AWS_PROFILE environment variable')
  63. return parser.parse_args()
  64.  
  65.  
  66. def _main():
  67. """Script execution handler."""
  68. args = _parse_args()
  69. delete_bucket(args.bucket_name, profile=args.profile)
  70.  
  71.  
  72. if __name__ == '__main__':
  73. _main()
Add Comment
Please, Sign In to add comment