All Products
Search
Document Center

Object Storage Service:Manage bucket tags

Last Updated:Jan 29, 2024

Object Storage Service (OSS) allows you to classify and manage buckets by using bucket tags. You can use the bucket tagging feature to configure tags for buckets that are used for different purposes and configure access control lists (ACLs) for buckets that have specific tags.

Usage notes

The bucket tagging feature allows you to use a key-value pair to identify buckets. You can configure tags for buckets that are used for different purposes and manage the buckets by tags.

  • Only the bucket owner and users who are granted the oss:PutBucketTagging permission can configure tags for buckets. If other users attempt to configure tags for buckets, the 403 Forbidden message that contains the AccessDenied error code is returned.

  • You can configure up to 20 tags (key-value pairs) for each bucket.

  • The key and value of a tag must be encoded in UTF-8.

  • The key can be up to 64 characters in length. It is case-sensitive and cannot be empty. The key cannot start with http://, https://, or Aliyun. These prefixes are not case-sensitive.

  • The value of a tag can be up to 128 characters in length and can be empty.

Scenarios

If you have a large number of buckets, you can classify the buckets based on tags and configure RAM policies to authorize specific users to manage the buckets that have specific tags. For example, you can configure the following policy to authorize User A (UID: 193248792425xxxx) to list all buckets that have the key1:value1 tag:

{
    "Version": "1",
    "Statement": [
        {
            "Action": [
                "oss:ListBuckets"
            ],
            "Resource": [
                "acs:oss:*:193248792425xxxx:*"
            ],
            "Effect": "Allow",
            "Condition": {
                "StringEquals": {
                    "oss:BucketTag/key1": "value1"
                }
            }
        }
    ]
}

You can also authorize User A to perform other operations on buckets by specifying the action element, such as writing data to buckets that have specific tags and querying information about these buckets. For more information about the action element that is supported by RAM policies, see Overview.

Procedure

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 Bucket Settings > Bucket Tagging.

  4. On the Bucket Tagging page, click Create Tag.

  5. Click + Tag to enter the key and value of a tag, or select an existing tag.

    To add multiple tags to the bucket, click + Tag.

  6. Click Save.

Use OSS SDKs

The following code provides examples on how to configure tags for a bucket by using OSS SDKs for common programming languages. For more information about how to configure tags for a bucket 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.SetBucketTaggingRequest;

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";

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

        try {
            // Configure tags for the bucket. 
            SetBucketTaggingRequest request = new SetBucketTaggingRequest(bucketName);
            // Specify the key and value of the tag. For example, set the key to owner and value to John. 
            request.setTag("owner", "John");
            request.setTag("location", "hangzhou");
            ossClient.setBucketTagging(request);
        } 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;
use OSS\Model\TaggingConfig;
use OSS\Model\Tag;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that you specified the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables. 
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";

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

try {
    // Configure tags for the bucket. 
    $config = new TaggingConfig();
    $config->addTag(new Tag("key1", "value1"));
    $config->addTag(new Tag("key2", "value2"));
    $ossClient->putBucketTags($bucket, $config);
} 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 you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET
});

// Configure tags for the bucket. 
async function putBucketTags(bucketName, tag) {
  try {
    const result = await client.putBucketTags(bucketName, tag);
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

const tag = { a: '1', b: '2' };
putBucketTags('bucketName', tag)
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import Tagging, TaggingRule

# Obtain access credentials from the environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
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. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# Create tagging rules for the bucket. 
rule = TaggingRule()
rule.add('key1', 'value1')
rule.add('key2', 'value2')

# Create tags for the bucket. 
tagging = Tagging(rule)
# Configure tags for the bucket. 
result = bucket.put_bucket_tagging(tagging)
# Display the returned HTTP status code. 
print('http status:', result.status)
using Aliyun.OSS;
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. Example: examplebucket. 
var bucketName = "examplebucket";

// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    // Configure tags for the bucket. 
    var setRequest = new SetBucketTaggingRequest(bucketName);

    var tag1 = new Tag
    {
        Key = "project",
        Value = "projectone"
    };

    var tag2 = new Tag
    {
        Key = "user",
        Value = "jsmith"
    };

    setRequest.AddTag(tag1);
    setRequest.AddTag(tag2);    
    client.SetBucketTagging(setRequest);
    Console.WriteLine("Set bucket:{0} Tagging succeeded ", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
package main

import (
	"fmt"
	"os"

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

func main() {
	// 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, 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)
	}

	// Initialize tagging configurations. 
	tag1 := oss.Tag{
		Key:   "key1",
		Value: "value1",
	}
	tag2 := oss.Tag{
		Key:   "key2",
		Value: "value2",
	}
	tagging := oss.Tagging{
		Tags: []oss.Tag{tag1, tag2},
	}
	// Specify the name of the bucket. Example: examplebucket. 
	// Configure tags for the bucket. 
	err = client.SetBucketTagging("examplebucket", tagging)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account 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 name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* 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);

    /* Configure tags for the bucket. */
    SetBucketTaggingRequest request(BucketName);
    Tag tag1("yourTagkey1","yourTagValue1");
    Tag tag2("yourTagkey2", "yourTagValue2");
    TagSet tagset;
    tagset.push_back(tag1);
    tagset.push_back(tag2);
    Tagging taging;
    taging.setTags(tagset);
    request.setTagging(taging);
    auto outcome = client.SetBucketTagging(request);

    if (outcome.isSuccess()) {      
            std::cout << " SetBucketTagging success " << std::endl;
    }
    else {
        /* Handle exceptions. */
        std::cout << "SetBucketTagging 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

For more information about how to configure bucket tags by using ossutil, see Add tags to a bucket or modify the tags of a bucket.

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