Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 910
Chandra Avatar asked May 16 '18 17:05

Chandra


Video Answer


1 Answers

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"
like image 99
helloV Avatar answered Sep 23 '22 07:09

helloV