Chandra
Chandra

Reputation: 91

How to check S3 bucket have tags or not

I tried to check the existing s3 buckets have tags or not, if bucket not have tags, will add the tags, i tried below code

for region in region_list:
    s3 = boto3.resource('s3', region)
    s3_client = boto3.client('s3', region)
        for bucket in s3.buckets.all():
            s3_bucket = bucket
            s3_bucket_name = s3_bucket.name
            response = s3_client.get_bucket_tagging(Bucket=s3_bucket_name)
            tagset = response['TagSet']
                if len(response['TagSet'])==0:
                    print "s3 bucket not have tags, adding tags"
                else:
                    pass

but getting below error

Traceback (most recent call last):
File "C:\Python27\ec2info.py", line 235, in <module>
response = s3_client.get_bucket_tagging(Bucket=s3_bucket_name)
File "C:\Python27\lib\site-packages\botocore\client.py", line 314, in 
_api_call
return self._make_api_call(operation_name, kwargs)
File "C:\Python27\lib\site-packages\botocore\client.py", line 612, in 
_make_api_call
raise error_class(parsed_response, operation_name)
ClientError: An error occurred (NoSuchTagSet) when calling the 
GetBucketTagging operation: The TagSet does not exist

where i am doing wrong here, what is the correct way of checking s3 bucket have tags or not

Thanks in advance for your help

Upvotes: 8

Views: 11258

Answers (4)

b0tting
b0tting

Reputation: 637

To expand on the correct answer of helloV, catch the correct exception as following:

s3_client = boto3.client('s3')
bucket_name = 'mybucket'
try:
    response = s3_client.get_bucket_tagging(Bucket=bucket_name)
    tags = response["TagSet"]
except ClientError as e:
    if e.response['Error']['Code'] == 'NoSuchTagSet':
        tags = {}
    else:
        raise e

Upvotes: 2

Dheeraj Inampudi
Dheeraj Inampudi

Reputation: 1457

Hope this code helps to keep track of your s3 tags

#s3 Buckets
import boto3
from botocore.exceptions import ClientError
s3_client = boto3.client('s3')
dict_of_s3_buckets = s3_client.list_buckets()
list_of_s3_buckets= [each['Name'] for each in dict_of_s3_buckets['Buckets']]
i=0
s3_bucket_tag_status={}
while i<len(list_of_s3_buckets):
    s3_bucket_name = list_of_s3_buckets[i]
    try:
        response = s3_client.get_bucket_tagging(Bucket=s3_bucket_name)
        tags = response['TagSet']
        s3_bucket_tag_status[s3_bucket_name]=tags
    except ClientError:
        #print(s3_bucket_name, "does not have tags")
        no_tags='does not have tags'
        s3_bucket_tag_status[s3_bucket_name]=no_tags
    i+=1
#changing to pandas dataframe (if required)
import pandas as pd
s3_bucket_tags= pd.DataFrame.from_dict(s3_bucket_tag_status,orient='index').reset_index().rename(columns={'index':'bucketName',0:'Tags'})

Upvotes: 1

Mausam Sharma
Mausam Sharma

Reputation: 892

here is the complete code how you will do it

import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3')
s3_re = boto3.resource('s3')

for bucket in s3_re.buckets.all():
    s3_bucket = bucket
    s3_bucket_name = s3_bucket.name
    bucket_tagging = s3_re.BucketTagging(s3_bucket_name)
    try:
        response = s3.get_bucket_tagging(Bucket=s3_bucket_name)
    except ClientError:
        print (bucket+ ",does not have tags, add tag")
        print("give key : ")
        inp_key = input()
        print("give value : ")
        inp_val = input()
        response = bucket_tagging.put(
            Tagging={
                'TagSet': [
                    {
                        'Key': inp_key, 
                        'Value': inp_val
                    },
                ]
            }
        )

Upvotes: 1

helloV
helloV

Reputation: 52393

Because get_bucket_tagging throws NoSuchTagSet when there are no tags. Catch the exception and create tags. Also, do not loop through regions, you will get all buckets irrespective of the region endpoint you connect to.

See: NoSuchTagSet when calling the GetBucketTagging operation

from botocore.exceptions import ClientError

for bucket in s3.buckets.all():
    s3_bucket = bucket
    s3_bucket_name = s3_bucket.name
    try:
        response = s3_client.get_bucket_tagging(Bucket=s3_bucket_name)
        #print response
        #tagset = response['TagSet']
    except ClientError:
        print s3_bucket_name, "does not have tags, adding tags"

Upvotes: 9

Related Questions