如何检查S3存储桶是否有标签

时间:2018-05-16 17:17:09

标签: python amazon-web-services amazon-s3 boto3

我尝试检查现有的s3存储桶是否有标签,如果存储桶没有标签,会添加标签,我试过下面的代码

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

但低于错误

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

我在这里做错了,检查s3桶有没有标签的正确方法是什么

提前感谢您的帮助

3 个答案:

答案 0 :(得分:3)

因为get_bucket_tagging在没有标记时会抛出NoSuchTagSet。捕获异常并创建标记。此外,不要遍历区域,无论您连接到哪个区域端点,都将获得所有存储桶。

请参阅: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"

答案 1 :(得分:1)

以下是完成代码的方法

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
                    },
                ]
            }
        )

答案 2 :(得分:0)

希望此代码有助于跟踪您的s3标签

server.port=8081