简体   繁体   中英

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

I am using this function:

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

It is deleting the existing tags and I can see only one tag.

I would use the following

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.

I came across the same problem and solved it with my own method:

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

And you add your tags in the function call:

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

This will add new tags and update existing ones

================ Bucket Level Tagging ================

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)

You can tag as many as you want [as many accepted by AWS]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM