Python 如果AWS S3存储桶上的现有标记包含',如何使用Boto3将新标记添加到AWS S3存储桶中;aws:';前缀?
我使用下面的boto3代码向S3 bucket添加新标记,而不删除现有标记Python 如果AWS S3存储桶上的现有标记包含',如何使用Boto3将新标记添加到AWS S3存储桶中;aws:';前缀?,python,amazon-web-services,amazon-s3,boto3,Python,Amazon Web Services,Amazon S3,Boto3,我使用下面的boto3代码向S3 bucket添加新标记,而不删除现有标记 s3 = boto3.resource('s3') bucket_tagging = s3.BucketTagging('bucket_name') tags = bucket_tagging.tag_set tags.append({'Key':'Owner', 'Value': owner}) Set_Tag = bucket_tagging.put(Tagging={'TagSet':tags}) 这将获取现有标
s3 = boto3.resource('s3')
bucket_tagging = s3.BucketTagging('bucket_name')
tags = bucket_tagging.tag_set
tags.append({'Key':'Owner', 'Value': owner})
Set_Tag = bucket_tagging.put(Tagging={'TagSet':tags})
这将获取现有标记,添加一个新标记,然后将它们全部放回
但如果我的bucket包含“aws:”作为前缀,则会出现以下错误:
'调用CreateTags操作时发生错误(InvalidParameterValue):参数键的值(aws:cloudformation:stack name)无效。以“aws:”开头的标记键保留供内部使用
在这种情况下,如何使用boto3添加新标记而不删除现有标记?我发现,虽然不能使用以“aws:”开头的键添加新标记,但可以毫无例外地将现有标记与新标记一起放回。 这是我使用的测试代码;替换bucket名称并根据需要添加区域:
#!/usr/bin/env python3
import boto3
tag_data = [{'Key':'Owner', 'Value': "my owner tag here"}]
bucket_name = "mybucket"
print (f"Updating tags in bucket: {bucket_name}")
s3 = boto3.resource('s3')
try:
bucket_tagging = s3.BucketTagging( bucket_name)
tags = bucket_tagging.tag_set
for tag in tags:
# Avoid error by not adding duplicate keys from current tag list.
key_test = tag.get("Key")
Found=False
for new_tag in tag_data:
if new_tag.get("Key") == key_test:
found=True
if not found:
tag_data.append(tag)
except Exception as error:
print ("Error getting tags: ", error)
print ("Setting new tag set to: ", tag_data)
response = bucket_tagging.put(
Tagging={
'TagSet': tag_data
}
)
if response is not None and response['ResponseMetadata']['HTTPStatusCode'] == 204:
print ("success")
else:
print (f"Warning, unable to update tags for bucket: {bucket_name}")
有趣的难题。问题:在没有标记的情况下放置新标记集是否仍然会覆盖“内部”标记?