All Products
Search
Document Center

Object Storage Service:Add tags to an object

Last Updated:Feb 27, 2024

Object Storage Service (OSS) allows you to configure object tags to classify objects. You can configure lifecycle rules and access control lists (ACLs) for objects based on tags.

Tagging rules

Object tagging uses key-value pairs to tag objects. You can add tags to objects when and after you upload objects.

  • An object can have up to 10 tags. The tags added to an object must have unique tag 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.

  • Changing tags of an object does not update the Last‑Modified parameter of the object.

  • 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 and configure lifecycle rules to automatically delete objects with these tags on a regular basis for storage cost optimization. For example, you can configure the following 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:

    <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 the following RAM policy to authorize a RAM user to access objects that have the key2:value2 tag:

    {
      "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, find and click the desired bucket.

  3. In the left-side navigation tree, choose Object Management > Objects.

  4. Add tags.

    1. Select the object to which you want to add tags.

      • Versioning not enabled for the bucket

        Find the object to which you want to add tags, and choose more > Tag.

      • Versioning enabled for the bucket

        Find the object version for which you want to configure tags, and choose more > Tag.

    2. In the Tag panel, follow the on-screen instructions to configure Key and Value.

  5. Click OK.

Use OSS SDKs

The following sample 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.common.auth.*;
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 your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";

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

        try {
            Map<String, String> tags = new HashMap<String, String>();
            // Specify the key and value of the object tag. For example, set the key to owner and 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 the object. 
            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;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// 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. 
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket. 
$bucket = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. 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({
  // Specify 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',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'yourbucketname'
});

// Specify the full path of the object. Do not include the bucket name in the full path. 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 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
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# 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 name of the bucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Specify the full path of the object. Do not include the bucket name in the full path. 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 encode the keys and values of the tags by using URL encoding. 
k4 = "k4+-="
v4 = "+-=._:/"
tagging += "&" + oss2.urlquote(k4) + "=" + oss2.urlquote(v4)

# Add the tagging configurations to 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;

// 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. 
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. 
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 headers. 
    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() {
	// Obtain access credentials from environment variables. Before you run the code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// Create an OSSClient instance. 
	// 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 your actual endpoint. 
	client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
	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. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
	objectName := "exampledir/exampleobject.txt"

	// Obtain the bucket information. 
	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 information about the account that is used to access OSS. */
    
    /* 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. */
    std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "test cpp sdk";
    PutObjectRequest request(BucketName, ObjectName, content);

    /* Specify the tags. */
    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;
        return -1;
    }

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

Use ossutil

You can add tags to objects by using ossutil. For more information, see Add or modify object tags.

Use the OSS API

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.