Gerenciar tags de objeto - Amazon Simple Storage Service

Gerenciar tags de objeto

Esta seção explica como você pode gerenciar tags de objeto usando os AWS SDKs for Java e .NET ou o console do Amazon S3.

A marcação de objetos é uma forma de categorizar o armazenamento. Cada tag é um par de valores chave que segue as regras a seguir:

  • Você pode associar até 10 tags a um objeto. As tags associadas a um objeto devem ter chaves de tag exclusivas.

  • Um chave de tag pode ter até 128 caracteres Unicode e os valores de tag podem ter até 256 caracteres Unicode. As tags de objeto do Amazon S3 são representadas internamente em UTF-16. Observe que, em UTF-16, os caracteres utilizam posições de um ou de dois caracteres.

  • As chaves e os valores diferenciam letras maiúsculas de minúsculas.

Para obter mais informações sobre tags de objeto, consulte Categorizando seu armazenamento usando tags. Para obter mais informações sobre restrições de tags, consulte Restrições de tags definidas pelo usuário no Manual do usuário do AWS Billing and Cost Management.

Para adicionar tags a um objeto
  1. Faça login no AWS Management Console e abra o console do Amazon S3 em https://console.aws.amazon.com/s3/.

  2. Na lista Buckets (Buckets), escolha o nome do bucket que contém os objetos aos quais você deseja adicionar às tags.

    Você também pode, opcionalmente, navegar até uma pasta.

  3. Na lista Objects (Objetos), marque a caixa de seleção ao lado dos nomes dos objetos aos quais você deseja adicionar tags.

  4. No menu Actions (Ações), escolha Edit (Editar).

  5. Revise os objetos listados e escolha Add tags (Adicionar tags).

  6. Cada tag de objeto é um par de chave-valor. Insira uma Key (Chave) e um Value (Valor). Para adicionar outra tag, escolha Add Tag (Adicionar tag).

    Você pode digitar até 10 tags para um objeto.

  7. Selecione Save changes.

    O Amazon S3 adiciona as tags aos objetos especificados.

Para obter mais informações, consulte também Exibir propriedades do objeto no console do Amazon S3 e Fazer upload de objetos neste guia.

Java

O exemplo a seguir mostra como usar o AWS SDK for Java para definir tags para um objeto novo e recuperar ou substituir tags para um objeto existente. Para obter mais informações sobre marcação de objetos, consulte Categorizando seu armazenamento usando tags. Consulte instruções sobre como criar e testar uma amostra funcional em Getting Started no Guia do desenvolvedor do AWS SDK for Java.

import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.*; import java.io.File; import java.util.ArrayList; import java.util.List; public class ManagingObjectTags { public static void main(String[] args) { Regions clientRegion = Regions.DEFAULT_REGION; String bucketName = "*** Bucket name ***"; String keyName = "*** Object key ***"; String filePath = "*** File path ***"; try { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new ProfileCredentialsProvider()) .withRegion(clientRegion) .build(); // Create an object, add two new tags, and upload the object to Amazon S3. PutObjectRequest putRequest = new PutObjectRequest(bucketName, keyName, new File(filePath)); List<Tag> tags = new ArrayList<Tag>(); tags.add(new Tag("Tag 1", "This is tag 1")); tags.add(new Tag("Tag 2", "This is tag 2")); putRequest.setTagging(new ObjectTagging(tags)); PutObjectResult putResult = s3Client.putObject(putRequest); // Retrieve the object's tags. GetObjectTaggingRequest getTaggingRequest = new GetObjectTaggingRequest(bucketName, keyName); GetObjectTaggingResult getTagsResult = s3Client.getObjectTagging(getTaggingRequest); // Replace the object's tags with two new tags. List<Tag> newTags = new ArrayList<Tag>(); newTags.add(new Tag("Tag 3", "This is tag 3")); newTags.add(new Tag("Tag 4", "This is tag 4")); s3Client.setObjectTagging(new SetObjectTaggingRequest(bucketName, keyName, new ObjectTagging(newTags))); } catch (AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } }
.NET

O exemplo a seguir mostra como usar o AWS SDK for .NET para definir as tags para um objeto novo e recuperar ou substituir as tags para um objeto existente. Para obter mais informações sobre marcação de objetos, consulte Categorizando seu armazenamento usando tags.

Para obter informações sobre como configurar e executar exemplos de código, consulte Conceitos básicos do AWS SDK for .NET no Guia do desenvolvedor do AWS SDK for .NET.

using Amazon; using Amazon.S3; using Amazon.S3.Model; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { public class ObjectTagsTest { private const string bucketName = "*** bucket name ***"; private const string keyName = "*** key name for the new object ***"; private const string filePath = @"*** file path ***"; // Specify your bucket region (an example region is shown). private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2; private static IAmazonS3 client; public static void Main() { client = new AmazonS3Client(bucketRegion); PutObjectWithTagsTestAsync().Wait(); } static async Task PutObjectWithTagsTestAsync() { try { // 1. Put an object with tags. var putRequest = new PutObjectRequest { BucketName = bucketName, Key = keyName, FilePath = filePath, TagSet = new List<Tag>{ new Tag { Key = "Keyx1", Value = "Value1"}, new Tag { Key = "Keyx2", Value = "Value2" } } }; PutObjectResponse response = await client.PutObjectAsync(putRequest); // 2. Retrieve the object's tags. GetObjectTaggingRequest getTagsRequest = new GetObjectTaggingRequest { BucketName = bucketName, Key = keyName }; GetObjectTaggingResponse objectTags = await client.GetObjectTaggingAsync(getTagsRequest); for (int i = 0; i < objectTags.Tagging.Count; i++) Console.WriteLine("Key: {0}, Value: {1}", objectTags.Tagging[i].Key, objectTags.Tagging[i].Value); // 3. Replace the tagset. Tagging newTagSet = new Tagging(); newTagSet.TagSet = new List<Tag>{ new Tag { Key = "Key3", Value = "Value3"}, new Tag { Key = "Key4", Value = "Value4" } }; PutObjectTaggingRequest putObjTagsRequest = new PutObjectTaggingRequest() { BucketName = bucketName, Key = keyName, Tagging = newTagSet }; PutObjectTaggingResponse response2 = await client.PutObjectTaggingAsync(putObjTagsRequest); // 4. Retrieve the object's tags. GetObjectTaggingRequest getTagsRequest2 = new GetObjectTaggingRequest(); getTagsRequest2.BucketName = bucketName; getTagsRequest2.Key = keyName; GetObjectTaggingResponse objectTags2 = await client.GetObjectTaggingAsync(getTagsRequest2); for (int i = 0; i < objectTags2.Tagging.Count; i++) Console.WriteLine("Key: {0}, Value: {1}", objectTags2.Tagging[i].Key, objectTags2.Tagging[i].Value); } catch (AmazonS3Exception e) { Console.WriteLine( "Error encountered ***. Message:'{0}' when writing an object" , e.Message); } catch (Exception e) { Console.WriteLine( "Encountered an error. Message:'{0}' when writing an object" , e.Message); } } } }