![](/img/trans.png)
[英]How to add tags to an S3 Bucket without deleting the existing tags using boto3?
[英]How to add new tags to an AWS S3 Bucket using Boto3 if the existing tags on the bucket contains 'aws:' prefixes?
我正在使用以下 boto3 代码向 S3 存储桶添加新标签,而不删除现有标签。
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})
这将获取现有标签,添加一个新标签,然后将它们全部放回原处。
但是,如果我的存储桶包含“aws:”作为前缀,则会出现以下错误:“调用 CreateTags 操作时发生错误 (InvalidParameterValue):参数键的值 ( aws:cloudformation:stack-name ) 无效。 以“aws:”开头的标签键保留供内部使用。
在这种情况下如何使用 boto3 添加新标签而不删除现有标签?
我发现虽然您无法添加带有以“aws:”开头的键的新标签,但您可以毫无例外地将现有标签连同新标签一起放回原处。 这是我使用的测试代码; 替换存储桶名称并根据需要添加区域:
#!/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}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.