O Object Storage Service (OSS) permite adicionar tags a objetos para classificação. Use essas tags para configurar regras de ciclo de vida e listas de controle de acesso (ACLs) nos objetos.
Regras de tag
As tags são compostas por pares chave-valor. Adicione-as durante o upload de novos objetos ou em objetos já armazenados no bucket.
Cada objeto aceita até 10 tags com chaves exclusivas.
O limite é de 128 caracteres para chaves e 256 para valores. Ambos diferenciam maiúsculas de minúsculas.
Os caracteres válidos incluem letras maiúsculas e minúsculas, números, espaços e os seguintes símbolos:
+ - = . _ : /.
Ao definir tags via cabeçalhos HTTP, aplique codificação URL tanto nas chaves quanto nos valores.
Observações
Somente o proprietário do bucket e usuários RAM com a permissão oss:PutObjectTagging podem ler e gravar tags dos objetos nesse bucket.
Adicione tags durante operações de upload simples, multipart upload, append upload e cópia. Também é possível adicioná-las posteriormente em objetos já enviados.
A cobrança ocorre por hora, conforme a quantidade de tags adicionadas. Para mais detalhes, consulte Taxas de tag de objetos.
Alterar as tags de um objeto não modifica seu carimbo de data/hora de última alteração.
Na replicação entre regiões (CRR), as tags são copiadas do objeto de origem para o destino.
Cenários
Configurar regras de ciclo de vida com base em tags
Para gerenciar recursos de armazenamento de forma eficiente e otimizar custos, aplique tags específicas a objetos gerados periodicamente que não exigem retenção prolongada. Em seguida, configure regras de ciclo de vida para excluir automaticamente esses objetos marcados em intervalos predefinidos.
Por exemplo, a regra abaixo exclui objetos com o prefixo dir1 e a tag key1:value1 trinta dias após a última atualização:
Também é possível conceder permissões adicionais, como gravar dados em objetos com determinadas tags ou visualizar informações relacionadas. Para saber quais ações as políticas RAM suportam, consulte Política RAM.
No painel de navegação à esquerda, clique em Buckets. Na página exibida, clique em nome do bucket desejado.
No painel de navegação à esquerda, escolha Object Management > Objects.
Adicione as tags.
Selecione o objeto ao qual deseja adicionar tags.
Bucket sem versionamento ativado
Localize o objeto desejado e escolha > Tag.
Bucket com versionamento ativado
Encontre a versão do objeto que receberá as tags e escolha > Tag.
No painel Tag, siga as instruções na tela para definir Key e Value.
Clique em OK.
Usar SDKs do OSS
Veja abaixo exemplos de código para configurar tags durante uploads simples usando SDKs do OSS nas linguagens mais comuns.
Para orientações completas sobre como configurar tags em outras operações — como upload simples, multipart upload, append upload e cópia — utilizando SDKs em demais linguagens, consulte Visão geral.
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;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.common.comm.SignVersion;
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.
// Call the shutdown method to release resources when the OSSClient is no longer in use.
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({
// Set region to the region where the bucket is located. For example, set region to oss-cn-hangzhou for China (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 bucket name.
bucket: 'yourbucketname'
});
// Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt.
const objectName = 'exampledir/exampleobject.txt'
// Specify the full path of the local file. For example, D:\\localpath\\examplefile.txt.
// If you specify only the local file name (for example, examplefile.txt) without a full path, the file is uploaded from the local path that corresponds to the project of the sample program.
const localFilepath = 'D:\\localpath\\examplefile.txt'
// Set request headers.
const headers = {
// Specify the key (for example, owner) and value (for example, John) of the object tag.
'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;
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is 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 set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name.
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 where the bucket is located. For example, if the bucket is 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 as needed.
var conf = new ClientConfiguration();
// Use Signature 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();
// Set the tag information in the HTTP header.
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;
// Add tags to the file during the upload.
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 the OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name. For example, examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 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. */
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);
/* Set tags. */
Tagging tagging;
tagging.addTag(Tag("key1", "value1"));
tagging.addTag(Tag("key2", "value2"));
request.setTagging(tagging.toQueryParameters());
/* Upload the file. */
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 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()
Usar o ossutil
Use o ossutil para adicionar ou editar tags. Para detalhes sobre a instalação, consulte Instalar o ossutil.
Execute o comando abaixo para adicionar ou editar tags dos objetos em examplebucket.
ossutil api put-object-tagging --bucket examplebucket --key exampleobject --tagging "{\"TagSet\":{\"Tag\":[{\"Key\":\"key1\",\"Value\":\"value1\"},{\"Key\":\"key2\",\"Value\":\"value2\"}]}}"
Os métodos descritos acima são implementados com base na API RESTful, que você pode chamar diretamente caso seu programa exija maior personalização. Para chamar a API diretamente, inclua o cálculo da assinatura no código. Para mais detalhes, consulte PutObjectTagging.