Promo Center

50% off for new user

Direct Mail-46% off

Learn More

Tag objects

Updated at: 2025-02-21 08:40

Object Storage Service (OSS) is a tool that lets you tag objects for classification. Use tags to configure lifecycle rules and access control lists (ACLs) for objects.

Tagging rules

Objects are tagged with key-value pairs. You can add tags either when uploading new objects or to existing objects stored within your bucket. 

  • Up to 10 tags with unique keys can be added to an object.

  • The maximum length for keys is 128 characters, and for values, 256 characters. Both are case-sensitive.

  • The valid character set for tags includes uppercase and lowercase letters, numbers, spaces, and the following symbols:

    + - = . _ : /

    When configuring tags via HTTP headers, especially if the tags contain special or non-alphanumeric characters, you must URL-encode both the tag keys and values. 

Notes

  • Only the owner of a bucket and RAM users who are granted 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 copy operations. You can also add tags to uploaded objects.

  • You will be charged based on the number of added tags on an hourly basis. For more information, see Object tagging fees.

  • Editing the tags of an object does not affect its Last‑Modified timestamp.

  • Tags are replicated from the source to the destination object in cross-region replication (CRR).

Scenarios

  • Configure lifecycle rules based on tags

    For efficient management of your storage resources and cost optimization, you can apply specific tags to objects that are generated periodically and do not require long-term retention, then configure lifecycle rules to automatically delete these tagged objects at predefined intervals.

    For example, you can configure the following lifecycle rule to delete objects prefixed with dir1 and tagged with key1:value1 30 days after these 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 with specific tags

    You can configure the following RAM policy to authorize a RAM user to access objects with the key2:value2 tag:

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

    You can also grant the user additional permissions, such as the permissions to write data to objects with specific tags or to view related information. For more information about the actions supported by RAM policies, see RAM policies.

Methods

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 you want to add tags to.

      • Versioning not enabled for the bucket

        Find the object you want to add tags to, 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

Below are code examples for configuring tags during simple upload processes using OSS SDKs for common programming languages.

For comprehensive guidance on configuring tags during other operations such as simple upload, multipart upload, append upload, and copy operations using OSS SDKs for other programming languages, see Overview.

Java
PHP
Node.js
Python
C#
C++
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";
        // 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 cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            Map<String, String> tags = new HashMap<String, String>();
            // Specify the key and value of the object tags. 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 the 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\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;

// 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.  
$provider = new 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. 
$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";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

// 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,
  authorizationV4: true,
  // 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;
using Aliyun.OSS.Common;

// 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();
}
// 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 cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
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);
}
#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 = "yourEndpoint";
    /* 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 cn-hangzhou. */
    std::string Region = "yourRegion";
    /* 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;
    conf.signatureVersion = SignatureVersionType::V4;
    /* 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);
    client.SetRegion(Region);
    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;
}
package main

import (
	"context"
	"flag"
	"log"
	"strings"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which the bucket is located.
	bucketName string // Name of the bucket.
	objectName string // Name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the name of the object is specified.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Specify the content that you want to upload.
	content := "hi oss"

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to upload the object.
	request := &oss.PutObjectRequest{
		Bucket:  oss.Ptr(bucketName),                // Name of the bucket.
		Key:     oss.Ptr(objectName),                // Name of the object.
		Body:    strings.NewReader(content),         // Content to upload.
		Tagging: oss.Ptr("tag1=value1&tag2=value2"), // Specify the tags of the object.
	}

	// Execute the request.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the results.
	log.Printf("put object result:%#v\n", result)
}

Use ossutil

You can use ossutil to add or edit tags. For information about its installation, see Install ossutil.

Run the following command to add tags to or edit the tags of objects in examplebucket.

ossutil api put-object-tagging --bucket examplebucket --key exampleobject --tagging "{\"TagSet\":{\"Tag\":[{\"Key\":\"key1\",\"Value\":\"value1\"},{\"Key\":\"key2\",\"Value\":\"value2\"}]}}"

For more information about this command, see put-object-tagging.

Related API operation

The methods described above are fundamentally implemented based on the RESTful API, which you can directly call if your program requires more customization. To directly call an API, you must include the signature calculation in your code. For more information, see PutObjectTagging.

  • On this page (1)
  • Tagging rules
  • Notes
  • Scenarios
  • Methods
  • Use the OSS console
  • Use OSS SDKs
  • Use ossutil
  • Related API operation
Feedback
phone Contact Us

Chat now with Alibaba Cloud Customer Service to assist you in finding the right products and services to meet your needs.

alicare alicarealicarealicare