Skip to content

Instantly share code, notes, and snippets.

@patrickpierson
Created October 18, 2020 16: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 patrickpierson/e1173f1adb8c84b17b93746e7c3e6b29 to your computer and use it in GitHub Desktop.
Save patrickpierson/e1173f1adb8c84b17b93746e7c3e6b29 to your computer and use it in GitHub Desktop.
import boto3
import botocore
s3_client = boto3.client('s3')
s3_resource = boto3.resource('s3')
def get_bucket_names():
bucket_names = []
for bucket in s3_client.list_buckets().get('Buckets'):
bucket_names.append(bucket.get('Name'))
return bucket_names
def tag_bucket_with_name(bucket_name):
bucket_tagging = s3_resource.BucketTagging(bucket_name)
try:
tags = bucket_tagging.tag_set
except botocore.exceptions.ClientError as e:
print('No tags exist for %s' % bucket_name)
tags = []
if not any(d['Key'] == 'BucketName' for d in tags):
tags.append({'Key': 'BucketName', 'Value': bucket_name})
set_tag = bucket_tagging.put(Tagging={'TagSet': tags})
if set_tag.get('ResponseMetadata').get('HTTPStatusCode') == 204:
print('Tags Set for %s' % bucket_name)
if __name__ == "__main__":
for name in get_bucket_names():
tag_bucket_with_name(name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment