Todos os produtos
Search
Central de documentação

Object Storage Service:Gerencie inventário de bucket com o OSS SDK for Go 2.0

Última atualização: Jul 03, 2026

Este tópico descreve como crie um inventário para um bucket, além de visualize, listar e exclua os inventários configurados em um bucket.

Observações

  • O código de exemplo deste tópico utiliza o ID da região cn-hangzhou, correspondente à região China (Hangzhou). Por padrão, o acesso aos recursos do bucket ocorre pelo endpoint público. Caso precise acessar esses recursos por meio de outros serviços da Alibaba Cloud na mesma região do bucket, utilize um endpoint interno. Para mais detalhes sobre as regiões e endpoints compatíveis com o Object Storage Service (OSS), consulte Regiões e endpoints do OSS.

  • Neste tópico, as credenciais de acesso são obtidas a partir de variáveis de ambiente. Para saber mais sobre como configure credenciais de acesso, veja Configurar credenciais de acesso.

  • Certifique-se de ter permissões para crie, visualize, listar e exclua inventários de um bucket. O proprietário do bucket possui essas permissões por padrão. Se você não tiver as permissões necessárias, solicite ao proprietário do bucket que as conceda.

  • É possível configure até 1.000 inventários por bucket.

  • O bucket de source, onde o inventário será configurado, deve estar na mesma região do bucket de destino destinado ao armazenamento das listas de inventário.

Código de exemplo

Crie um inventário para um bucket

O código abaixo exemplifica como crie um inventário para um bucket.

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"
)

// Define global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	var (
		accountId   = "account id of the bucket" // Specify the ID of the Alibaba Cloud account to which the bucket owner grants permissions to perform the operation. Example: 109885487000****.
		inventoryId = "inventory id"             // The name of the inventory. The name must be globally unique in the bucket.
	)

	// 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")
	}

	// 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 configure an inventory for the bucket.
	putRequest := &oss.PutBucketInventoryRequest{
		Bucket:      oss.Ptr(bucketName),  // The name of the bucket.
		InventoryId: oss.Ptr(inventoryId), // The name of the inventory specified by the user.
		InventoryConfiguration: &oss.InventoryConfiguration{
			Id:        oss.Ptr(inventoryId), // The name of the inventory specified by the user.
			IsEnabled: oss.Ptr(true),        // Enable the inventory.
			Filter: &oss.InventoryFilter{
				Prefix:                   oss.Ptr("filterPrefix"),    // Specify the rule that is used to filter the objects included in inventories.
				LastModifyBeginTimeStamp: oss.Ptr(int64(1637883649)), // The timestamp that specifies the start time of the last modification.
				LastModifyEndTimeStamp:   oss.Ptr(int64(1638347592)), // The timestamp that specifies the end time of the last modification.
				LowerSizeBound:           oss.Ptr(int64(1024)),       // The lower size limit of files (unit: bytes).
				UpperSizeBound:           oss.Ptr(int64(1048576)),    // The upper size limit of files (unit: bytes).
				StorageClass:             oss.Ptr("Standard,IA"),     // The storage class.
			},
			Destination: &oss.InventoryDestination{
				OSSBucketDestination: &oss.InventoryOSSBucketDestination{
					Format:    oss.InventoryFormatCSV,                                   // The format of the exported inventory lists.
					AccountId: oss.Ptr(accountId),                                       // Specify the ID of the account that is granted permissions by the bucket owner to perform the operation. Example: 109885487000****.
					RoleArn:   oss.Ptr("acs:ram::" + accountId + ":role/AliyunOSSRole"), // 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.
					Bucket:    oss.Ptr("acs:oss:::" + bucketName),                       // Specify the name of the bucket in which you want to store the generated inventory lists.
					Prefix:    oss.Ptr("export/"),                                       // Specify the prefix of the path in which you want to store the generated inventory lists.
				},
			},
			Schedule: &oss.InventorySchedule{
				Frequency: oss.InventoryFrequencyDaily, // The frequency at which the inventory list is exported (daily).
			},
			IncludedObjectVersions: oss.Ptr("All"), // Specify whether to include all versions of objects or only the current versions of objects in the inventory list.
		},
	}

	// Execute the request.
	putResult, err := client.PutBucketInventory(context.TODO(), putRequest)
	if err != nil {
		log.Fatalf("failed to put bucket inventory %v", err)
	}

	// Display the result.
	log.Printf("put bucket inventory result:%#v\n", putResult)
}

Visualize as configurações de inventário de um bucket

O exemplo a seguir demonstra como visualize as configurações de inventário de um bucket.

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"
)

// Define global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Specify the name of the inventory.
	var inventoryId = "inventory id"

	// 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")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSSClient instance.
	client := oss.NewClient(cfg)

	// Create a request to query the inventory configurations.
	request := &oss.GetBucketInventoryRequest{
		Bucket:      oss.Ptr(bucketName),
		InventoryId: oss.Ptr(inventoryId),
	}

	// Make the query request and process the result.
	result, err := client.GetBucketInventory(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket inventory %v", err)
	}

	// Display the result.
	log.Printf("get bucket inventory result:%#v\n", result)
}

Listar os inventários configurados em um bucket

Nota

Uma única requisição permite visualize até 100 inventários. Para obter mais de 100 inventários, envie múltiplas requisições e utilize o token retornado em cada uma como parâmetro na requisição seguinte.

Veja abaixo um exemplo de como listar os inventários configurados em um bucket.

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"
)

// Define global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// 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 list the inventories configured for the bucket.
	request := &oss.ListBucketInventoryRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Execute the request and process the result.
	result, err := client.ListBucketInventory(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to list bucket inventory %v", err)
	}

	// Display the result.
	log.Printf("list bucket inventory result:%#v\n", result)
}

Exclua um inventário configurado em um bucket

Este trecho de código ilustra o processo de exclusão de um inventário configurado em um bucket.

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"
)

// Define global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Specify the name of the inventory.
	var inventoryId = "inventory id"

	// 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")
	}

	// 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 delete the inventory configured for the bucket.
	request := &oss.DeleteBucketInventoryRequest{
		Bucket:      oss.Ptr(bucketName),
		InventoryId: oss.Ptr(inventoryId),
	}

	// Execute the request and process the result.
	result, err := client.DeleteBucketInventory(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket inventory %v", err)
	}

	// Display the result.
	log.Printf("delete bucket inventory result:%#v\n", result)
}

Referências

  • Para detalhes sobre a operação de API usada na criação de inventários de bucket, consulte PutBucketInventory.

  • Saiba mais sobre a operação de API para visualize das configurações de inventário de um bucket em GetBucketInventory.

  • A documentação da operação de API para listagem de inventários configurados está disponível em ListBucketInventory.

  • Informações completas sobre a operação de API destinada à exclusão de inventários podem ser encontradas em DeleteBucketInventory.