Use tags para marcar buckets com diferentes finalidades e gerenciá-los por categoria.
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Neste exemplo, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).
Definir tags de bucket
O código a seguir mostra como definir tags para um bucket chamado examplebucket.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of your bucket. For example, for the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
// Set yourRegion to the region where your bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Initialize tags.
tag1 := oss.Tag{
Key: "key1",
Value: "value1",
}
tag2 := oss.Tag{
Key: "key2",
Value: "value2",
}
tagging := oss.Tagging{
Tags: []oss.Tag{tag1, tag2},
}
// Specify the bucket name, for example, examplebucket.
// Set bucket tags.
err = client.SetBucketTagging("examplebucket", tagging)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
Visualizar tags de bucket
O código a seguir mostra como visualizar as tags de um bucket chamado examplebucket.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of your bucket. For example, for the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
// Set yourRegion to the region where your bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the bucket name.
// Get bucket tag information.
ret, err := client.GetBucketTagging("examplebucket")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Print the number of tags.
fmt.Println("Tag length: ", len(ret.Tags))
}
Listar buckets com tags específicas
O código a seguir mostra como listar buckets que possuem tags específicas.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of your bucket. For example, for the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
// Set yourRegion to the region where your bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Find buckets by TagKey.
ret, err := client.ListBuckets(oss.TagKey("yourTaggingKey"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Print bucket information.
for _, bucket := range ret.Buckets {
fmt.Println("bucket:", bucket)
}
// Find buckets by both TagKey and TagValue.
// The TagValue parameter must be used with the TagKey parameter. You can leave TagValue unspecified. If TagValue is not specified, the results are not filtered by tag value.
res, err := client.ListBuckets(oss.TagKey("yourTaggingKey"), oss.TagValue("yourTaggingValue"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Print bucket information.
for _, b := range res.Buckets {
fmt.Println("bucket:", b)
}
}
Excluir tags de bucket
Excluir uma única tag de bucket
O código a seguir mostra como excluir a tag com a chave key1 de um bucket chamado examplebucket.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of your bucket. For example, for the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
// Set yourRegion to the region where your bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the bucket name.
// Delete the bucket tag whose key is key1.
err = client.DeleteBucketTagging("examplebucket", oss.AddParam("tagging", "key1"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
Excluir várias tags de bucket
O código a seguir mostra como excluir as tags com as chaves key1 e key2 de um bucket chamado examplebucket.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Get access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Set yourEndpoint to the endpoint of your bucket. For example, if your bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint accordingly.
// Set yourRegion to the region where your bucket is located. For example, if your bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region accordingly.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the bucket name.
// Delete the bucket tags whose keys are key1 and key2.
err = client.DeleteBucketTagging("examplebucket", oss.AddParam("tagging", "key1,key2"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
Excluir todas as tags de um bucket
O código a seguir exemplifica como excluir todas as tags do bucket examplebucket.
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Replace yourEndpoint with the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, specify the actual endpoint.
// Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the bucket name, such as examplebucket.
// Delete the bucket tags.
err = client.DeleteBucketTagging("examplebucket")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
Referências
Para mais informações sobre a operação de API para definir tags de bucket, consulte PutBucketTags.
Para obter detalhes sobre a operação de API para recuperar tags de bucket, consulte GetBucketTags.
Para informações sobre a operação de API para excluir tags de bucket, consulte DeleteBucketTags.