Created
October 18, 2020 16:22
-
-
Save patrickpierson/e1173f1adb8c84b17b93746e7c3e6b29 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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