Tous les produits
Search
Centre de documentation

Object Storage Service:Inventaire de bucket (OSS SDK pour Go 1.0)

Dernière mise à jour :Sep 22, 2026

Cette rubrique explique comment créer un inventaire pour un bucket, ainsi que comment consulter, répertorier et supprimer les inventaires configurés pour ce bucket.

Notes

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.

  • Les identifiants d'accès sont récupérés depuis les variables d'environnement. Pour savoir comment configurer les identifiants d'accès, consultez Configurer les identifiants d'accès.

  • Cet exemple montre comment créer une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, comme l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Configurer un client (SDK Go V1).

  • Assurez-vous de disposer des autorisations nécessaires pour créer, consulter, répertorier et supprimer les inventaires d'un bucket. Par défaut, le propriétaire du bucket dispose de ces autorisations. Si ce n'est pas le cas, demandez au propriétaire du bucket de vous les accorder.

  • Vous pouvez configurer jusqu'à 1 000 inventaires par bucket.

  • Le bucket source pour lequel vous configurez un inventaire doit se trouver dans la même région que le bucket de destination où la liste d'inventaire est stockée.

Créer un inventaire pour un bucket

L'exemple de code suivant montre comment créer un inventaire pour un 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)
	}
}

Consulter les inventaires d'un bucket

L'exemple de code suivant montre comment consulter un inventaire configuré pour un 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))
}

Répertorier plusieurs inventaires simultanément

Remarque

Une seule requête permet de consulter jusqu'à 100 inventaires. Pour en consulter davantage, envoyez plusieurs requêtes en utilisant le jeton renvoyé par chaque requête comme paramètre de la suivante.

L'exemple de code suivant montre comment répertorier les inventaires configurés pour un 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))
}

Supprimer un inventaire d'un bucket

L'exemple de code suivant montre comment supprimer un inventaire configuré pour un 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)
	}
}

Références

  • Pour obtenir l'exemple de code complet relatif à la gestion des inventaires de buckets, visitez GitHub.

  • Pour plus d'informations sur l'opération API de création d'un inventaire pour un bucket, consultez PutBucketInventory.

  • Pour plus d'informations sur l'opération API de consultation d'un inventaire configuré pour un bucket, consultez GetBucketInventory.

  • Pour plus d'informations sur l'opération API de répertoriage des inventaires configurés pour un bucket, consultez ListBucketInventory.

  • Pour plus d'informations sur l'opération API de suppression des inventaires configurés pour un bucket, consultez DeleteBucketInventory.