簡體   English   中英

如何使用 boto3 在不刪除現有標簽的情況下向 S3 存儲桶添加標簽?

[英]How to add tags to an S3 Bucket without deleting the existing tags using boto3?

我正在使用這個功能:

s3 = boto3.resource('s3')
bucket_tagging = s3.BucketTagging(bucket)
Set_Tag = bucket_tagging.put(Tagging={'TagSet':[{'Key':'Owner', 'Value': owner}]})

它正在刪除現有標簽,我只能看到一個標簽。

我會使用以下

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

這將獲取現有標簽,添加一個新標簽,然后將它們全部放回原處。

我遇到了同樣的問題並用我自己的方法解決了它:

import boto3

def set_object_keys(bucket, key, update=True, **new_tags):
    """
    Add/Update/Overwrite tags to AWS S3 Object

    :param bucket_key: Name of the S3 Bucket
    :param update: If True: appends new tags else overwrites all tags with **kwargs
    :param new_tags: A dictionary of key:value pairs 
    :return: True if successful 
    """

    #  I prefer to have this var outside of the method. Added for completeness
    client = boto3.client('s3')   

    old_tags = {}

    if update:
        old = client.get_object_tagging(
            Bucket=bucket,
            Key=key,
        )

        old_tags = {i['Key']: i['Value'] for i in old['TagSet']}

    new_tags = {**old_tags, **new_tags}

    response = client.put_object_tagging(
        Bucket=bucket,
        Key=key,
        Tagging={
            'TagSet': [{'Key': str(k), 'Value': str(v)} for k, v in new_tags.items()]
        }
    )

    return response['ResponseMetadata']['HTTPStatusCode'] == 200

然后在函數調用中添加標簽:

set_object_keys(....., name="My Name", colour="purple")

這將添加新標簽並更新現有標簽

================ 桶級標記 ================

import boto3

session = boto3.session.Session(profile_name='default')
client = session.client('s3', 'ap-southeast-2')

def set_bucket_tags(bucket, update=True, **new_tags):
    old_tags = {}

    if update:
        try:
            old = client.get_bucket_tagging(Bucket=bucket)
            old_tags = {i['Key']: i['Value'] for i in old['TagSet']}
        except Exception as e:
            print(e)
            print("There was no tag")

    new_tags = {**old_tags, **new_tags}

    response = client.put_bucket_tagging(
        Bucket=bucket,
        Tagging={
            'TagSet': [{'Key': str(k), 'Value': str(v)} for k, v in new_tags.items()]
        }
    )

    print(response)

您可以根據需要標記任意數量 [AWS 接受的數量]

set_bucket_tags("selim.online", True, key1="value1", key2="value2", key3="value3")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM