Este tópico descreve como criar um inventário para um bucket, além de consultar, listar e excluir os inventários configurados para ele.
Notas
Este tópico usa o endpoint público da região China (Hangzhou). Se você precisar 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 Regions and endpoints.
Este tópico usa credenciais de acesso obtidas de variáveis de ambiente. Para mais informações sobre como configurar credenciais de acesso, consulte Configure access credentials.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Configure a client (Go SDK V1).
Certifique-se de ter as permissões para criar, visualizar, listar e excluir inventários do bucket. Por padrão, o proprietário do bucket tem as permissões para executar essas operações. Caso não tenha as permissões necessárias, solicite as permissões ao proprietário do bucket.
É possível configurar até 1.000 inventários para um bucket.
Implante o bucket de origem, para o qual você configurará o inventário, na mesma região do bucket de destino que armazena a lista de inventário.
Crie um inventário para um bucket
O código a seguir mostra como criar um inventário para um bucket:
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.
// 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. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
IsEnabled := true
// The following code provides an example on how to encrypt the inventory lists by using customer master keys (CMKs) managed by Key Management Service (KMS).
//var invEncryption oss.InvEncryption
//var invSseOss oss.InvSseOss
//var invSseKms oss.InvSseKms
//invSseKms.KmsId = "<yourKmsId>" // Specify the ID of CMK that is managed by KMS.
//invEncryption.SseOss = &invSseOss // Use OSS-managed keys (SSE-OSS) to encrypt the inventory lists.
//invEncryption.SseKms = &invSseKms // Use CMKs managed by KMS (SSE-KMS) to encrypt inventory lists.
invConfig := oss.InventoryConfiguration{
// Specify the name of the inventory. The name must be globally unique in the current bucket.
Id: "yourInventoryId2",
// Enable the inventory.
IsEnabled: &IsEnabled,
// Specify the rule that is used to filter the objects included in inventories. The following code provides an example on how to filter the objects by prefix.
Prefix: "yourFilterPrefix",
OSSBucketDestination: oss.OSSBucketDestination{
// Specify the format of the exported inventory lists.
Format: "CSV",
// Specify the ID of the account that is granted permissions by the bucket owner to perform the operation. Example: 109885487000****.
AccountId: "yourGrantAccountId",
// Specify the name of the RAM role that is granted permissions by the bucket owner to perform the operation. Example: acs:ram::109885487000****:role/ram-test.
RoleArn: "yourRoleArn",
// Specify the name of the bucket in which you want to store the generated inventory lists.
Bucket: "acs:oss:::" + "yourDestBucketName",
// Specify the prefix of the path in which you want to store the generated inventory lists.
Prefix: "yourDestPrefix",
// The following sample code provides an example on how to encrypt inventory lists.
//Encryption: &invEncryption,
},
// Specify the frequency at which inventory lists are exported.
Frequency: "Daily",
// Specify whether to include all versions of objects or only the current versions of objects in the inventory lists.
IncludedObjectVersions: "All",
OptionalFields: oss.OptionalFields{
// Specify the fields that are included in inventory lists.
Field: []string{
"Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
},
},
}
// Specify the name of the bucket for which you want to configure the inventory.
err = client.SetBucketInventory("yourBucketName", invConfig)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
Consulte os inventários do bucket
O código a seguir mostra como consultar um inventário configurado para um bucket:
package main
import (
"encoding/xml"
"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.
// 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. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
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 name of the bucket
// Specify the name of the inventory.
result, err := client.GetBucketInventory("yourBucketName", "yourInventoryId")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Display the inventory.
bs, err := xml.MarshalIndent(result, " ", " ")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Println(string(bs))
}
Liste vários inventários por vez
É possível consultar até 100 inventários em uma única solicitação. Para consultar mais de 100 inventários, envie várias solicitações e use o token retornado em cada solicitação como parâmetro para a próxima.
O código a seguir mostra como listar os inventários configurados para um bucket:
package main
import (
"encoding/xml"
"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.
// 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. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
var sumResult oss.ListInventoryConfigurationsResult
vmarker := ""
for {
// Specify the name of the bucket
listResult, err := client.ListBucketInventory("yourBucketName", vmarker)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
sumResult.InventoryConfiguration = append(sumResult.InventoryConfiguration, listResult.InventoryConfiguration...)
if listResult.IsTruncated != nil && *listResult.IsTruncated {
vmarker = listResult.NextContinuationToken
} else {
break
}
}
// Display the inventories of the bucket.
bs, err := xml.MarshalIndent(sumResult, " ", " ")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Println(string(bs))
}
Exclua um inventário do bucket
O código a seguir mostra como excluir um inventário configurado para um bucket:
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.
// 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. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Delete the inventory.
// Specify the name of the bucket
// Specify the name of the inventory.
err = client.DeleteBucketInventory("yourBucketName", "yourInventoryId")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
Referências
Para obter o código de exemplo completo de gerenciamento de inventários do bucket, visite o GitHub.
Para obter mais informações sobre a operação de API que cria um inventário para um bucket, consulte PutBucketInventory.
Para obter mais informações sobre a operação de API que consulta um inventário configurado para um bucket, consulte GetBucketInventory.
Para obter mais informações sobre a operação de API que lista os inventários configurados para um bucket, consulte ListBucketInventory.
Para obter mais informações sobre a operação de API que exclui os inventários configurados para um bucket, consulte DeleteBucketInventory.