gpt4 book ai didi

python - 如何检查S3 bucket是否有标签

转载 作者:行者123 更新时间:2023-11-28 22:18:37 25 4
gpt4 key购买 nike

我尝试检查现有的 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 桶是否有标签的正确方法是什么

预先感谢您的帮助

最佳答案

因为 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"

关于python - 如何检查S3 bucket是否有标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50376650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com