All Products
Search
Document Center

Object Storage Service:Manage bucket tags

Last Updated:Mar 20, 2026

Bucket tags are key-value pairs you attach to OSS buckets to group them by project, environment, or team. Once tagged, you can reference those tags in Resource Access Management (RAM) policies to enforce fine-grained access control—restricting which users can read or write data in which buckets.

Common uses:

  • Access control: Write RAM policies that allow or deny access based on bucket tags, preventing cross-project data access.

  • Resource grouping: Identify bucket ownership at a glance without opening each bucket.

Prerequisites

Before you begin, ensure that you have:

  • The oss:PutBucketTagging permission, or bucket owner access

Users without this permission receive 403 Forbidden with the AccessDenied error code.

Limitations

ConstraintDetail
Maximum tags per bucket20
EncodingUTF-8
Tag key lengthUp to 64 characters; case-sensitive; cannot be empty
Restricted key prefixesCannot start with http://, https://, or Aliyun (case-insensitive)
Tag value lengthUp to 128 characters; can be empty
Buckets without a region attributeNot supported

Add tags to a bucket

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 target 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 and enter the tag key and value, or select an existing tag. To add multiple tags, click + Tag for each additional tag.

  6. Click Save.

Use OSS SDKs

All examples below load credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables. Replace examplebucket and the region with your actual values.

<details> <summary>Python</summary>

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="Put bucket tags")
parser.add_argument('--region', help='The region where the bucket is located.', required=True)
parser.add_argument('--bucket', help='The bucket name.', required=True)
parser.add_argument('--endpoint', help='Custom endpoint (optional).')

def main():
    args = parser.parse_args()

    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.put_bucket_tags(
        oss.PutBucketTagsRequest(
            bucket=args.bucket,
            tagging=oss.Tagging(
                tag_set=oss.TagSet(
                    tags=[
                        oss.Tag(key='test_key', value='test_value'),
                        oss.Tag(key='test_key2', value='test_value2'),
                    ],
                ),
            ),
        )
    )

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


if __name__ == "__main__":
    main()

</details>

<details> <summary>Java</summary>

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.SetBucketTaggingRequest;

public class Demo {

    public static void main(String[] args) throws Exception {
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        EnvironmentVariableCredentialsProvider credentialsProvider =
            CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        String bucketName = "examplebucket";
        String region = "cn-hangzhou";

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

        try {
            SetBucketTaggingRequest request = new SetBucketTaggingRequest(bucketName);
            request.setTag("owner", "John");
            request.setTag("location", "hangzhou");
            ossClient.setBucketTagging(request);
        } catch (OSSException oe) {
            System.out.println("Error code: " + oe.getErrorCode());
            System.out.println("Request ID: " + oe.getRequestId());
        } catch (ClientException ce) {
            System.out.println("Error: " + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

</details>

<details> <summary>Go</summary>

package main

import (
	"context"
	"flag"
	"log"

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

var (
	region     string
	bucketName string
)

func init() {
	flag.StringVar(&region, "region", "", "The region where the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The bucket name.")
}

func main() {
	flag.Parse()

	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("bucket name is required")
	}
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("region is required")
	}

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg)

	request := &oss.PutBucketTagsRequest{
		Bucket: oss.Ptr(bucketName),
		Tagging: &oss.Tagging{
			&oss.TagSet{
				[]oss.Tag{
					{Key: oss.Ptr("k1"), Value: oss.Ptr("v1")},
					{Key: oss.Ptr("k2"), Value: oss.Ptr("v2")},
					{Key: oss.Ptr("k3"), Value: oss.Ptr("v3")},
				},
			},
		},
	}

	result, err := client.PutBucketTags(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket tags: %v", err)
	}
	log.Printf("put bucket tags result: %#v\n", result)
}

</details>

<details> <summary>PHP</summary>

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

$optsdesc = [
    "region" => ['help' => 'The region where the bucket is located.', 'required' => true],
    "endpoint" => ['help' => 'Custom endpoint (optional).', 'required' => false],
    "bucket" => ['help' => 'The bucket name.', 'required' => true],
];

$longopts = array_map(fn($key) => "$key:", array_keys($optsdesc));
$options = getopt("", $longopts);

foreach ($optsdesc as $key => $value) {
    if ($value['required'] && empty($options[$key])) {
        echo "Error: --$key is required. " . $value['help'];
        exit(1);
    }
}

$region = $options["region"];
$bucket = $options["bucket"];

$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);

if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

$client = new Oss\Client($cfg);

$tagging = new Oss\Models\Tagging(
    tagSet: new Oss\Models\TagSet(
        tags: [
            new Oss\Models\Tag(key: 'key1', value: 'value1'),
            new Oss\Models\Tag(key: 'key2', value: 'value2'),
        ]
    )
);

$request = new Oss\Models\PutBucketTagsRequest(bucket: $bucket, tagging: $tagging);
$result = $client->putBucketTags($request);

printf(
    'status code: %s' . PHP_EOL .
    'request id: %s' . PHP_EOL,
    $result->statusCode,
    $result->requestId
);

</details>

<details> <summary>Node.js</summary>

const OSS = require('ali-oss');

const client = new OSS({
  region: 'oss-cn-hangzhou',
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  bucket: 'examplebucket',
});

async function putBucketTags(bucketName, tags) {
  try {
    const result = await client.putBucketTags(bucketName, tags);
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

const tags = { owner: 'John', location: 'hangzhou' };
putBucketTags('examplebucket', tags);

</details>

<details> <summary>C#</summary>

using Aliyun.OSS;
using Aliyun.OSS.Common;

var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
var bucketName = "examplebucket";
const string region = "cn-hangzhou";

var conf = new ClientConfiguration();
conf.SignatureVersion = SignatureVersion.V4;

var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);

try
{
    var setRequest = new SetBucketTaggingRequest(bucketName);
    setRequest.AddTag(new Tag { Key = "project", Value = "projectone" });
    setRequest.AddTag(new Tag { Key = "user", Value = "jsmith" });
    client.SetBucketTagging(setRequest);
    Console.WriteLine("Bucket tags set successfully.");
}
catch (OssException ex)
{
    Console.WriteLine("Error code: {0}, Message: {1}, RequestID: {2}",
        ex.ErrorCode, ex.Message, ex.RequestId);
}
catch (Exception ex)
{
    Console.WriteLine("Error: {0}", ex.Message);
}

</details>

<details> <summary>C++</summary>

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    std::string Region = "cn-hangzhou";
    std::string BucketName = "examplebucket";

    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    SetBucketTaggingRequest request(BucketName);
    Tag tag1("key1", "value1");
    Tag tag2("key2", "value2");
    TagSet tagset;
    tagset.push_back(tag1);
    tagset.push_back(tag2);
    Tagging tagging;
    tagging.setTags(tagset);
    request.setTagging(tagging);

    auto outcome = client.SetBucketTagging(request);
    if (outcome.isSuccess()) {
        std::cout << "SetBucketTagging succeeded." << std::endl;
    } else {
        std::cout << "SetBucketTagging failed. Code: " << outcome.error().Code()
                  << ", Message: " << outcome.error().Message()
                  << ", RequestId: " << outcome.error().RequestId() << std::endl;
        return -1;
    }

    ShutdownSdk();
    return 0;
}

</details>

For SDK examples in other languages, see the OSS SDK overview.

Use ossutil

For instructions on adding or updating bucket tags with ossutil, see Add tags to a bucket or modify the tags of a bucket.

Use the OSS API

To call the API directly, include signature calculation in your request. For details, see PutBucketTags.

Example: enforce RAM-based access control by project

In a company where each project uses a dedicated OSS bucket, you can tag each bucket with the project name and then write RAM policies that restrict access to buckets matching specific tags. This prevents teams from accidentally reading or writing data in another project's bucket. For a step-by-step guide, see Authorize a RAM user to read and write data in buckets with specific tags.

What's next