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
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management > Objects.
Add tags.
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
> Tag.
Versioning enabled for the bucket
Find the object version for which you want to configure tags, and choose
> Tag.
In the Tag panel, follow the on-screen instructions to configure Key and Value.
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.
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();
}
}
}
}
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
})
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(®ion, "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)
}
<?php
// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for command line parameters.
$optsdesc = [
"region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
"key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object.
];
// Convert the parameter descriptions to a long options list required by getopt.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information about the parameters.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If the required parameters are not configured, exit the program.
}
}
// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of object.
// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Specify the content that you want to upload.
$data = 'Hello OSS';
// Create a PutObjectRequest object to upload the object.
$request = new Oss\Models\PutObjectRequest(
bucket: $bucket,
key: $key,
tagging: "key1=value1&key2=value2"); // Specify the tag information.
$request-> body=Oss\Utils::streamFor($data); // Specify that the data in the HTTP request body is a binary stream.
// Perform the simple upload operation.
$result = $client->putObject($request);
// Display the upload result.
printf(
'status code: %s' . PHP_EOL . // The HTTP status code.
'request id: %s' . PHP_EOL . // The request ID.
'etag: %s' . PHP_EOL, // The ETag of the object.
$result->statusCode,
$result->requestId,
$result->etag
);
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line parameter parser and define the parameters.
parser = argparse.ArgumentParser(description="put object tagging sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--tag_key', help='The name of the tag key.', required=True)
parser.add_argument('--tag_value', help='The name of the tag value.', required=True)
def main():
# Parse the command-line parameters.
args = parser.parse_args()
# Load access credentials from environment variables.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configuration of the SDK.
cfg = oss.config.load_default()
# Specify the credential provider.
cfg.credentials_provider = credentials_provider
# Specify the region.
cfg.region = args.region
# Specify the endpoint if one is provided.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client.
client = oss.Client(cfg)
# Specify a tag.
# Add more oss.Tag objects in the following format if you need to configure multiple tags.
# tags = [oss.Tag(key=args.tag_key, value=args.tag_value), oss.Tag(key=args.tag_key2, value=args.tag_value2)]
tags = [oss.Tag(
key=args.tag_key,
value=args.tag_value,
)]
# Configure the tags for the object.
result = client.put_object_tagging(oss.PutObjectTaggingRequest(
bucket=args.bucket,
key=args.key,
tagging=oss.Tagging(
tag_set=oss.TagSet(
tags=tags,
),
),
))
# Print the response.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' version id: {result.version_id},'
)
if __name__ == "__main__":
main()
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.