Object Storage Service (OSS) allows you to configure object tags to classify objects. Tags allow you to configure lifecycle rules and access control lists (ACLs) for objects that have the same tag.

Rules and conventions

Object tagging uses key-value pairs to identify objects. You can add tags to objects when and after you upload objects.
  • You can add up to 10 tags to an object. The tags added to an object must have unique keys.
  • A tag key can be up to 128 characters in length. A tag value can be up to 256 characters in length.
  • Tag keys and tag values are case-sensitive.
  • The key and the value of a tag can contain letters, digits, spaces, and the following special characters:

    + - = . _ : /

    If the tags of the HTTP header contain characters, you must perform URL encoding on the keys and values of the tags.

Usage notes

  • Only the owner of a bucket and RAM users that have the oss:PutObjectTagging permission can read and write the tags of objects in the bucket.
  • You can add tags to an object when you perform simple upload, multipart upload, append upload, and object copy operations. You can also add tags to an uploaded object.
  • After you add tags to an object, you are charged for object tagging based on the number of added tags on an hourly basis. For more information, see Object tagging fees.
  • The Last-Modified value of an object is not updated when object tags are changed.
  • For cross-region replication (CRR), object tags are replicated from the source object to the destination object.

Scenarios

  • Configure lifecycle rules based on object tags
    You can add specific tags to periodically generated objects that do not need to be stored for a long period of time. This way, you can configure lifecycle rules to automatically delete the objects with specific tags on a regular basis. For example, you can configure a lifecycle rule to delete objects that have the dir1 prefix in their names and the key1:value1 tag 30 days after the objects are last updated. The following example shows how to configure a lifecycle rule:
    <LifecycleConfiguration>
     <Rule>
      <ID>rule1</ID>
      <Prefix>dir1</Prefix>
      <Tag><Key>key1</Key><Value>value1</Value></Tag>
      <Status>Enabled</Status>
      <Expiration>
        <Days>30</Days>
      </Expiration>
     </Rule>
    </LifecycleConfiguration>
  • Authorize a RAM user to access objects that have specific tags

    For example, you can configure a RAM policy to authorize a RAM user to access objects that have the key2:value2 tag. The following example shows how to configure the RAM policy:

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "oss:GetObject",
          "Resource": "*",
          "Condition": {
            "StringEquals": {
              "oss:ExistingObjectTag/key2": [
                "value2"
              ]
            }
          }
        }
      ]
    }

    You can also authorize the RAM user to perform more actions, such as writing data to objects that have specific tags or viewing the information about the objects. For more information about the actions that are supported by RAM policies, see Overview.

Use the OSS console

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
  3. In the left-side navigation pane, choose Files > Objects.
  4. Add tags to objects.
    1. Select objects to which you want to add tags.
      • Add tags to objects in unversioned buckets

        Find the object to which you want to add tags, and choose more > Tagging in the Actions column.

      • Add tags to objects in versioned buckets

        Find the object of the specified version for which you want to configure tags, and choose more > Tagging in the Actions column.

    2. In the Tagging panel, set Key and Value based on the rules of object tagging.
  5. Click OK.

Use OSS SDKs

The following code provides examples on how to add tags to objects in simple upload by using OSS SDKs for common programming languages. For more information about how to add tags to objects in simple upload, multipart upload, append upload, and object copy operations by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object, not including the bucket name. Example: exampledir/exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            Map<String, String> tags = new HashMap<String, String>();
            // Specify the key and the value of the object tag. For example, set the key to owner and the value to John. 
            tags.put("owner", "John");
            tags.put("type", "document");

            // Configure the tags in the HTTP header. 
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setObjectTagging(tags);

            // Upload the object and add tags to it. 
            String content = "<yourtContent>";
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()), metadata);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket. 
$bucket = "examplebucket";
// Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
$object = "exampledir/exampleobject.txt";
// Specify the string to upload. 
$content = "hello world";

$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);

// Add tags to the object. 
$options = array(
      OssClient::OSS_HEADERS => array(
              'x-oss-tagging' => 'key1=value1&key2=value2&key3=value3',
));
  
try {
      // Upload the object by using simple upload. 
      $ossClient->putObject($bucket, $object, $content, $options);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}

print(__FUNCTION__ . ": OK" . "\n");  
const OSS = require('ali-oss')

const client = new OSS({
  // Set yourRegion to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourRegion',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the name of the bucket. Example: examplebucket. 
  bucket: 'examplebucket',
});

// Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
const objectName = 'exampledir/exampleobject.txt'
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. 
// By default, if you specify only the name of the local file such as examplefile.txt without specifying the local path, the local file is uploaded from the path of the project to which the sample program belongs. 
const localFilepath = 'D:\\localpath\\examplefile.txt'

// Configure request headers. 
const headers = {
  // Specify the key and value of the object tag. For example, set the key to owner and the value to John. 
  'x-oss-tagging': 'owner=John&type=document', 
}

client.put(objectName, localFilepath, {
  headers
})
# -*- coding: utf-8 -*-

import oss2
from oss2.headers import OSS_OBJECT_TAGGING

# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
# Specify the bucket name. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'yourEndpoint', 'examplebucket')
# Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
object_name = 'exampledir/exampleobject.txt'

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

# If tags contain characters, you must perform URL encoding on 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 when the object is uploaded. 
result = bucket.put_object(object_name, 'content', headers=headers)
print('http response status: ', result.status)

# Display 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]))
using System.Text;
using Aliyun.OSS;
using System.Text;
using Aliyun.OSS.Util;

// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the bucket name. 
var bucketName = "examplebucket";
// Specify the full path of the object. The full path of the object cannot contain the bucket name. 
var objectName = "exampleobject.txt";
var objectContent = "More than just cloud.";

String UrlEncodeKey(String key)
{
const string CharsetName = "utf-8";
const char separator = '/';
var segments = key.Split(separator);

var encodedKey = new StringBuilder();
encodedKey.Append(HttpUtils.EncodeUri(segments[0], CharsetName));
for (var i = 1; i < segments.Length; i++)
    encodedKey.Append(separator).Append(HttpUtils.EncodeUri(segments[i], CharsetName));

    if (key.EndsWith(separator.ToString()))
    {
        // String#split ignores trailing empty strings, e.g., "a/b/" will be split as a 2-entries array,
        // so we have to append all the trailing slash to the uri.
        foreach (var ch in key)
        {
            if (ch == separator)
                encodedKey.Append(separator);
            else
                break;
        }
    }

return encodedKey.ToString();
}
// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
    MemoryStream requestContent = new MemoryStream(binaryData);

    var meta = new ObjectMetadata();
    // Configure the tags in the HTTP header. 
    string str = UrlEncodeKey("key1") + "=" + UrlEncodeKey("value1") + "&" + UrlEncodeKey("key2") + "=" + UrlEncodeKey("value2");
    meta.AddHeader("x-oss-tagging", str);
    var putRequest = new PutObjectRequest(bucketName, objectName, requestContent);
    putRequest.Metadata = meta;

    // Upload the object and add tags to the object. 
    client.PutObject(putRequest);
    Console.WriteLine("Put object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}
package main

import (
    "fmt"
    "os"
    "strings"

    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // Create an OSSClient instance. 
    // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket"
    // Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
    objectName := "exampledir/exampleobject.txt"

    // Obtain the bucket. 
    bucket, err := client.Bucket(bucketName)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Specify the key and the value of the object tag. For example, set the key to owner and the value to John. 
    tag1 := oss.Tag{
        Key:   "owner",
        Value: "John",
    }
    tag2 := oss.Tag{
        Key:   "type",
        Value: "document",
    }
    tagging := oss.Tagging{
        Tags: []oss.Tag{tag1, tag2},
    }

    // Add tags to the object. 
    err = bucket.PutObject(objectName, strings.NewReader("Hello OSS"), oss.SetTagging(tagging))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    fmt.Println(bucket.GetObjectTagging(objectName))
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access Object Storage Service (OSS). */
    /* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize resources such as networks. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "test cpp sdk";
    PutObjectRequest request(BucketName, ObjectName, content);

    /* Specify the tags that you want to add to the object. */
    Tagging tagging;
    tagging.addTag(Tag("key1", "value1"));
    tagging.addTag(Tag("key2", "value2"));
    request.setTagging(tagging.toQueryParameters());

    /* Upload the object. */
    auto outcome = client.PutObject(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "PutObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        ShutdownSdk();
        return -1;
    }

    /* Release resources such as networks. */
    ShutdownSdk();
    return 0;
}

Use ossutil

For more information about how to configure object tags by using ossutil, see Add or modify object tags.

Use RESTful APIs

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutObjectTagging.