Skip to content

Instantly share code, notes, and snippets.

@dhoeric
Last active August 23, 2023 04:27
Show Gist options
  • Save dhoeric/a42e127de043eeb23208e17b035453ff to your computer and use it in GitHub Desktop.
Save dhoeric/a42e127de043eeb23208e17b035453ff to your computer and use it in GitHub Desktop.
Add Name tag by S3 bucket name

Add Name tag by S3 bucket name

S3 bucket usually don't add any tag when creation, which is difficult for us to check the cost spend by each bucket. The add_tags.py basically add/update Name tags to align with S3 bucket name and allow us easier to check the bills.

pipenv shell --three
pipenv install boto3

# Copy add_tags.py into local
python add_tags.py
import boto3
from botocore.exceptions import ClientError
s3_client = boto3.client('s3')
s3_res = boto3.resource('s3')
response = s3_client.list_buckets()
buckets = response['Buckets']
for bucket in buckets:
print('---')
print(bucket)
bucket_obj = s3_res.Bucket(bucket['Name'])
bucket_tagging = bucket_obj.Tagging()
try:
tags = bucket_tagging.tag_set
except ClientError as e:
tags = []
# Add Name tag
name_idx = [i for i in range(len(tags)) if tags[i]['Key'] == 'Name']
if len(name_idx) > 0:
name_idx = name_idx[0]
tags[name_idx]['Value'] = bucket['Name']
else:
tags.append({
'Key': 'Name',
'Value': bucket['Name']
})
res = bucket_tagging.put(Tagging={'TagSet': tags})
print(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment