[英]How to add new tags to an AWS S3 Bucket using Boto3 if the existing tags on the bucket contains 'aws:' prefixes?
I am using the following piece of boto3 code to add new tags to the S3 bucket without deleting the existing tags.我正在使用以下 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})
This gets the existing tags, adds a new one, and then puts them all back in.这将获取现有标签,添加一个新标签,然后将它们全部放回原处。
But if my bucket contains 'aws:' as prefix, it gives the following error: 'An error occurred (InvalidParameterValue) when calling the CreateTags operation: Value ( aws:cloudformation:stack-name ) for parameter key is invalid.但是,如果我的存储桶包含“aws:”作为前缀,则会出现以下错误:“调用 CreateTags 操作时发生错误 (InvalidParameterValue):参数键的值 ( aws:cloudformation:stack-name ) 无效。 Tag keys starting with 'aws:' are reserved for internal use.'
以“aws:”开头的标签键保留供内部使用。
How to add new tags without deleting the existing tags in this case using boto3?在这种情况下如何使用 boto3 添加新标签而不删除现有标签?
I have found that while you can't add new tags with a key that begins with "aws:", you can put existing tags back, along with your new tags, without an exception.我发现虽然您无法添加带有以“aws:”开头的键的新标签,但您可以毫无例外地将现有标签连同新标签一起放回原处。 Here is the test code I used;
这是我使用的测试代码; replace the bucket name and add a region as needed:
替换存储桶名称并根据需要添加区域:
#!/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.