OSS allows you to configure object tagging to classify objects. You can configure object lifecycle rules and ACLs based on tags.

Background information

When you configure object tagging, note the following items:

  • You can add tags to an object when you upload it or add tags to an uploaded object. If you add tags to an object that already has tags, the original tags are overwritten. For more information about how to configure object tagging, see PutObjectTagging.
  • To add tags to an object, you must have the permissions to call PutObjectTagging.
  • The Last-Modified value of an object is not updated when its tags are changed.
  • The key and value of the tag can contain letters, digits, spaces, and the following special characters:

    + ‑ = . _ : /

    Note If you configure the tags in the HTTP header and the tags contain any characters, you can URL encode the keys and values of the tags.

Object tagging uses a key-value pair to identify objects. For more information about object tagging, see Configure object tagging.

Add tags to an object when you upload it

  • Add tags to an object when you upload it by calling put_object.

    The following code provides an example on how to add tags to an object when you upload it by calling put_object:

    # -*- coding: utf-8 -*-
    
    import oss2
    from oss2.headers import OSS_OBJECT_TAGGING
    
    # Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
    auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
    # The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
    bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
    
    object_name = '<yourObjectName>'
    
    # Configure the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If tags contain any characters, you must URL encode the keys and values of the tags.
    k4 = "k4+‑="
    v4 = "+‑=._:/"
    tagging += "&” + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Configure the tags in the HTTP headers.
    headers = dict()
    headers[OSS_OBJECT_TAGGING] = tagging
    
    # Specify the headers when you call the put_object operation so that the tags are added to the object to be uploaded.
    result = bucket.put_object(object_name, 'content', headers=headers)
    print('http response status: ', result.status)
    
    # View the tags added to the object.
    result = bucket.get_object_tagging('yourObjectName')
    for key in result.tag_set.tagging_rule:
        print('tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
  • Add tags to an object when you upload it by calling multipart_upload.

    The following code provides an example on how to add tags to an object when you upload it by calling multipart_upload:

    # -*- coding: utf-8 -*-
    import os
    import oss2
    from oss2 import SizedFileAdapter, determine_part_size
    from oss2.models import PartInfo
    from oss2.headers import OSS_OBJECT_TAGGING
    
    # Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
    auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
    # The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
    bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
    
    object_name = '<yourObjectName>'
    filename = '<yourLocalFile>'
    
    total_size = os.path.getsize(filename)
    # Use the determine_part_size method to determine the size of each part.
    part_size = determine_part_size(total_size, preferred_size=100 * 1024)
    
    # Configure the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If tags contain any characters, you must URL encode the keys and values of the tags.
    k4 = "k4+‑="
    v4 = "+‑=._:/"
    tagging += "&” + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Configure the tags in the HTTP headers.
    headers = dict()
    headers[OSS_OBJECT_TAGGING] = tagging
    
    # Initialize a multipart upload task.
    # Specify the headers when you call the init_multipart_upload operation so that the tags are added to the object to be uploaded.
    upload_id = bucket.init_multipart_upload(object_name, headers=headers).upload_id
    parts = []
    
    # Upload the parts one by one.
    with open(filename, 'rb') as fileobj:
        part_number = 1
        offset = 0
        while offset < total_size:
            num_to_upload = min(part_size, total_size - offset)
            # The SizedFileAdapter(fileobj, size) method generates a new object, and resets the append position.
            result = bucket.upload_part(object_name, upload_id, part_number,
                                        SizedFileAdapter(fileobj, num_to_upload))
            parts.append(PartInfo(part_number, result.etag))
    
            offset += num_to_upload
            part_number += 1
    
    # Complete the multipart upload task.
    result = bucket.complete_multipart_upload(object_name, upload_id, parts)
    print('http response status: ', result.status)
    
    # View the tags added to the object.
    result = bucket.get_object_tagging(object_name)
    for key in result.tag_set.tagging_rule:
        print('tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
    
    # Verify the result of the multipart upload task.
    with open(filename, 'rb') as fileobj:
        assert bucket.get_object(object_name).read() == fileobj.read()
  • Add tags to an object when you upload it by calling append_object.

    The following code provides an example on how to add tags to an object when you upload it by calling append_object:

    # -*- coding: utf-8 -*-
    
    import oss2
    from oss2.headers import OSS_OBJECT_TAGGING
    
    # Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
    auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
    # The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
    bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
    
    object_name = '<yourObjectName>'
    
    # Configure the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If tags contain any characters, you must URL encode the keys and values of the tags.
    k4 = "k4+‑="
    v4 = "+‑=._:/"
    tagging += "&” + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Configure the tags in the HTTP headers.
    headers = dict()
    headers[OSS_OBJECT_TAGGING] = tagging
    
    # Append the object. Specify the headers when you call the append_object operation so that the tags are added to the object.
    # Only the tags configured when the object is appended for the first time are added to the object.
    result = bucket.append_object(object_name, 0, '<yourContent>', headers=headers)
    
    # View the tags added to the object.
    result = bucket.get_object_tagging('yourObjectName')
    for key in result.tag_set.tagging_rule:
        print('tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
  • Add tags to an object when you upload it by calling resumable_upload.

    The following code provides an example on how to add tags to an object when you upload it by calling resumable_upload:

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.headers import OSS_OBJECT_TAGGING
    
    # Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
    auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
    # The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
    bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
    
    object_name = '<yourObjectName>'
    local_file = '<yourLocalFileName>'
    
    # Configure the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If tags contain any characters, you must URL encode the keys and values of the tags. k4 = "k4+‑="
    v4 = "+‑=._:/"
    tagging += "&” + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Configure the tags in the HTTP headers.
    headers = dict()
    headers[OSS_OBJECT_TAGGING] = tagging
    
    # When the object length is greater than or equal to the value of the multipart_threshold optional parameter, multipart upload is used. The default value of multipart_threshold is 10 MB. If you do not use the store parameter to specify a directory, a directory named .py-oss-upload is created in the HOME directory to store the checkpoint information.
    # Specify the headers when you call the resumable_upload operation so that the tags are added to the object to be uploaded.
    oss2.resumable_upload(bucket, object_name, local_file, headers=headers)
    
    result = bucket.get_object_tagging(object_name)
    for key in result.tag_set.tagging_rule:
        print('object tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))

Add tags to an uploaded object or modify the tags added to an object

The following code provides an example on how to add tags to an uploaded object or modify the tags added to an object:
# -*- coding: utf-8 -*-

import oss2
from oss2.models import Tagging, TaggingRule

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')

# Create a tagging rule.
rule = TaggingRule()
rule.add('key1', 'value1')
rule.add('key2', 'value2')

# Create a tag.
tagging = Tagging(rule)

# Add the tag to the object.
result = bucket.put_object_tagging('<yourObjectName>', tagging)
# View the HTTP status code.
print('http response status:', result.status)

Add tags to an object when you copy it

You can specify one of the following tagging rules when you upload an object: Valid values:
  • Copy: The tag of the source object is copied to the destination object. This is the default value.
  • Replace: The tag of the destination object is set to the tag specified in the request instead of the tag of the source object.

The following examples describe how to add tags to objects smaller than 1 GB in simple copy mode and larger than 1 GB in multipart copy mode.

  • The following code provides an example on how to add tags to an object smaller than 1 GB when you upload it by calling CopyObject:

    # -*- coding: utf-8 -*-
    
    import oss2
    from oss2.headers import OSS_OBJECT_TAGGING, OSS_OBJECT_TAGGING_COPY_DIRECTIVE
    
    # Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
    auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
    # The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
    bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
    
    # Specify the source object.
    src_object_name = '<yourtSrcObjectName>'
    # Specify dest_object_name1.
    dest_object_name1 = '<yourtDestObjectName1>'
    # Specify dest_object_name2.
    dest_object_name2 = '<yourtDestObjectName2>'
    
    # Configure the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If tags contain any characters, you must URL encode the keys and values of the tags.
    k4 = "k4+‑="
    v4 = "+‑=._:/"
    tagging += "&” + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Specify OSS_OBJECT_TAGGING_COPY_DIRECTIVE to COPY or keep the default value in the HTTP headers, so that the tags added to the source object is also added to dest_object_name1.
    headers=dict()
    headers[OSS_OBJECT_TAGGING_COPY_DIRECTIVE] = 'COPY'
    bucket.copy_object(bucket.bucket_name, src_object_name, dest_object_name1, headers=headers)
    
    # Specify OSS_OBJECT_TAGGING_COPY_DIRECTIVE to REPLACE in the HTTP headers, so that the tags specified in OSS_OBJECT_TAGGING are added to dest_object_name2.
    headers[OSS_OBJECT_TAGGING_COPY_DIRECTIVE] = 'REPLACE'
    headers[OSS_OBJECT_TAGGING] = tagging
    bucket.copy_object(bucket.bucket_name, src_object_name, dest_object_name2, headers=headers)
    
    # View the tags added to the src_object_name object.
    result = bucket.get_object_tagging(src_object_name)
    for key in result.tag_set.tagging_rule:
        print('src tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
    
    # View the tags added to dest_object_name1. The tags are the same as those of the source object.
    result = bucket.get_object_tagging(dest_object_name1)
    for key in result.tag_set.tagging_rule:
        print('dest1 object tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
    
    # View the tags added to dest_object_name2. The added tags are specified in OSS_OBJECT_TAGGING.
    result = bucket.get_object_tagging(dest_object_name2)
    for key in result.tag_set.tagging_rule:
        print('dest2 object tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
  • The following code provides an example on how to add tags to an object larger than 1 GB when you upload it by calling multipart_upload:
    # -*- coding: utf-8 -*-
    import os
    import oss2
    from oss2 import determine_part_size
    from oss2.models import PartInfo
    from oss2.headers import OSS_OBJECT_TAGGING
    
    # Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
    auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
    # The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
    bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
    
    # Specify the source object.
    src_object_name = '<yourSrcObject>'
    # Specify the destination object.
    dest_object_name = '<yourDestObject>'
    
    # Obtain the size of the source object.
    head_info = bucket.head_object(src_object_name)
    total_size = head_info.content_length
    print('src object size:', total_size)
    
    # Use the determine_part_size method to determine the size of each part.
    part_size = determine_part_size(total_size, preferred_size=100 * 1024)
    print('part_size:', part_size)
    
    # Configure the tagging string.
    tagging = "k1=v1&k2=v2&k3=v3"
    
    # If tags contain any characters, you must URL encode the keys and values of the tags.
    k4 = "k4+‑="
    v4 = "+‑=._:/"
    tagging += "&” + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)
    
    # Configure the tags in the HTTP headers.
    headers = dict()
    headers[OSS_OBJECT_TAGGING] = tagging
    
    # Initialize a multipart upload task.
    # Specify the headers when you call the init_multipart_upload operation so that the tags are added to the destination object.
    upload_id = bucket.init_multipart_upload(dest_object_name, headers=headers).upload_id
    parts = []
    
    # Upload the parts one by one.
    part_number = 1
    offset = 0
    while offset < total_size:
        num_to_upload = min(part_size, total_size - offset)
        end = offset + num_to_upload - 1;
        result = bucket.upload_part_copy(bucket.bucket_name, src_object_name, (offset, end), dest_object_name, upload_id, part_number)
        # Save the part information.
        parts.append(PartInfo(part_number, result.etag))
    
        offset += num_to_upload
        part_number += 1
    
    # Complete the multipart upload task.
    result = bucket.complete_multipart_upload(dest_object_name, upload_id, parts)
    
    # Obtain the object metadata.
    head_info = bucket.head_object(dest_object_name)
    
    # View the size of the destination object.
    dest_object_size = head_info.content_length
    print('dest object size:', dest_object_size)
    
    # Compare the size of the destination object with that of the source object.
    assert dest_object_size == total_size
    
    # View the tags added to the source object.
    result = bucket.get_object_tagging(src_object_name)
    for key in result.tag_set.tagging_rule:
        print('src tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
    
    # View the tags added to the destination object.
    result = bucket.get_object_tagging(dest_object_name)
    for key in result.tag_set.tagging_rule:
        print('dest tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))
    					

Add tags to a symbolic link object

The following code provides an example on how to add tags to a symbolic link object:

# -*- coding: utf-8 -*-

import oss2
from oss2.headers import OSS_OBJECT_TAGGING

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')

object_name = '<yourObjectName>'
symlink_name = '<yourSymlinkName>'

# Configure the tagging string.
tagging = "k1=v1&k2=v2&k3=v3"

# If tags contain any characters, you must URL encode the keys and values of the tags.
k4 = "k4+‑="
v4 = "+‑=._:/"
tagging += "&” + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)

# Configure the tags in the HTTP headers.
headers = dict()
headers[OSS_OBJECT_TAGGING] = tagging

# Add a symbolic link to the object.
# Specify the headers when you call the put_symlink operation so that the tags are added to a symbolic link object.
result = bucket.put_symlink(object_name, symlink_name, headers=headers)
print('http response status: ', result.status)

# View the tags added to the symbolic link object.
result = bucket.get_object_tagging(symlink_name)
for key in result.tag_set.tagging_rule:
    print('tagging key: {}, value: {}'.format(key, result.tag_set.tagging_rule[key]))