Todos os produtos
Search
Central de documentação

Object Storage Service:Bucket inventory (OSS SDK for Go 1.0)

Última atualização: Jul 03, 2026

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

Observações

  • Este tópico usa 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 obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Este exemplo obtém as credenciais de acesso de variáveis de ambiente. Para saber mais sobre como configure credenciais de acesso, consulte Configurar credenciais de acesso.

  • Este tópico demonstra como crie uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).

  • Verifique se você tem permissões para crie, visualize, listar e exclua inventários de um bucket. Por padrão, o proprietário do bucket tem permissão para execute essas operações. Caso não tenha as permissões necessárias, solicite-as ao proprietário do bucket.

  • Você pode configure até 1.000 inventários por bucket.

  • O bucket de source, para o qual você deseja configure um inventário, deve estar na mesma região do bucket de destino onde a lista de inventário será armazenada.

Crie um inventário para um bucket

O código a seguir mostra como crie 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)
	}
}

Consultar os inventários de um bucket

O código a seguir mostra como consultar um inventário configurado em 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))
}

Listar vários inventários simultaneamente

Nota

É 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 de um bucket

O código a seguir mostra como exclua um inventário configurado em 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 sobre gerenciamento de inventários de bucket, visite o GitHub.

  • Para obter mais informações sobre a operação de API para criação de inventários de bucket, consulte PutBucketInventory.

  • Para obter mais informações sobre a operação de API para consulta de inventários configurados em um bucket, consulte GetBucketInventory.

  • Para obter mais informações sobre a operação de API para listagem de inventários configurados em um bucket, consulte ListBucketInventory.

  • Para obter mais informações sobre a operação de API para exclusão de inventários configurados em um bucket, consulte DeleteBucketInventory.