CloudBox object tags

Updated at:

OSS on CloudBox lets you use tags to classify objects in an OSS on CloudBox bucket. Based on these tags, you can set lifecycle rules and access permissions for the 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, you must URL-encode both the tag keys and values. 

Usage notes

  • Only the bucket owner and users who have the oss-cloudbox:PutObjectTagging permission can read and write object tags.

  • 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.

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

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 that have specific tags

    You can configure a RAM policy to grant a RAM user permissions to access objects that have the tags status:ok and key1:value1 in an OSS on CloudBox bucket named examplebucket. The ID of the CloudBox is cb-f8z7yvzgwfkl9q0h****.

    {
        "Version": "1",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "oss-cloudbox:GetObject"
                ],
                "Resource": [
                    "acs:oss-cloudbox:*:174649585760****:cloudbox/cb-f8z7yvzgwfkl9q0h****/bucket/examplebucket/*"
                ],
                "Condition": {
                    "StringEquals": {
                        "oss-cloudbox:ExistingObjectTag/status":"ok",
                        "oss-cloudbox:ExistingObjectTag/key1":"value1"
                    }
                }
            }
        ]
    }
    

Procedure

Use an Alibaba Cloud SDK

You can add tags during a simple upload by using the OSS SDK for Java, Python, or Go (Java SDK 3.15.0 or later, Python SDK V2 1.1.1 or later, or Go SDK V2 v1.2.1 or later). For OSS on CloudBox, the Python and Go SDKs are called in the same way as they are in public cloud OSS. For information about how to create a client, see SDK support. The following code examples use the Java, Python, and Go SDKs.

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;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;

public class Demo {
    public static void main(String[] args) throws Exception {
        // Specify the data endpoint of the OSS on CloudBox bucket.
        String endpoint = "https://cb-f8z7yvzgwfkl9q0h****.cn-hangzhou.oss-cloudbox.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the OSS on CloudBox bucket, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the region where the OSS on CloudBox bucket is located.
        String region = "cn-hangzhou";
        // Specify the CloudBox ID.
        String cloudBoxId = "cb-f8z7yvzgwfkl9q0h****";
        // Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
        String objectName = "exampledir/exampleobject.txt";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer in use, call the shutdown method to release the resources.
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        conf.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(new DefaultCredentialProvider(credentialsProvider.getCredentials()))
                .clientConfiguration(conf)
                .region(region)
                .cloudBoxId(cloudBoxId)
                .build();

        try {
            Map<String, String> tags = new HashMap<String, String>();
            // Specify the tag key, such as owner, and the tag value, such as John.
            tags.put("owner", "John");
            tags.put("type", "document");

            // Set the tag information in the HTTP header.
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setObjectTagging(tags);

            // Set the content of the object to upload.
            String content = "yourContent";
            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();
            }
        }
    }
}
import alibabacloud_oss_v2 as oss

# Obtain access credentials from environment variables. Before you run this code example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

# Use the default configuration of the SDK.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Specify the region in which the CloudBox is located, such as cn-hangzhou.
cfg.region = "cn-hangzhou"
# Specify the CloudBox ID. After you set the CloudBox ID, the SDK automatically switches the signing product to oss-cloudbox.
cfg.cloud_box_id = "cb-f8z7yvzgwfkl9q0h****"
# Specify the data domain in the CloudboxId.Region.oss-cloudbox.aliyuncs.com format.
cfg.endpoint = "cb-f8z7yvzgwfkl9q0h****.cn-hangzhou.oss-cloudbox.aliyuncs.com"

# Create an OSS client.
client = oss.Client(cfg)

# Specify the content of the object to upload.
content = "yourContent"

# Add tags during the simple upload by using the tagging parameter. Separate multiple tags with an ampersand (&).
result = client.put_object(oss.PutObjectRequest(
    bucket="examplebucket",
    key="exampledir/exampleobject.txt",
    body=content.encode(),
    tagging="owner=John&type=document",
))

print(f'status code: {result.status_code},'
      f' request id: {result.request_id},'
      f' etag: {result.etag},')
package main

import (
	"context"
	"log"
	"strings"

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

func main() {
	// Obtain access credentials from environment variables. Before you run this code example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
	// Use the default configuration of the SDK, and specify the region, CloudBox ID, and data domain.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		// Specify the region in which the CloudBox is located, such as cn-hangzhou.
		WithRegion("cn-hangzhou").
		// Specify the data domain in the CloudboxId.Region.oss-cloudbox.aliyuncs.com format.
		WithEndpoint("cb-f8z7yvzgwfkl9q0h****.cn-hangzhou.oss-cloudbox.aliyuncs.com").
		// Specify the CloudBox ID. After you set the CloudBox ID, the SDK automatically switches the signing product to oss-cloudbox.
		WithCloudBoxId("cb-f8z7yvzgwfkl9q0h****")

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

	// Add tags during the simple upload by using the Tagging field. Separate multiple tags with an ampersand (&).
	request := &oss.PutObjectRequest{
		Bucket:  oss.Ptr("examplebucket"),
		Key:     oss.Ptr("exampledir/exampleobject.txt"),
		Body:    strings.NewReader("yourContent"),
		Tagging: oss.Ptr("owner=John&type=document"),
	}

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

	log.Printf("put object result, status code:%d, request id:%s, etag:%v\n",
		result.StatusCode, result.RequestID, oss.ToString(result.ETag))
}

Use ossutil

For more information about how to use ossutil to add object tags, see put-object-tagging.

Use the REST API

If you have advanced customization requirements, you can make REST API requests directly. This requires you to manually write code to calculate the signature. For more information, see PutObjectTagging.