Tous les produits
Search
Centre de documentation

Object Storage Service:Gérer l'inventaire des buckets à l'aide du SDK OSS pour Go 2.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 un bucket.

Notes

  • L'exemple de code présenté dans cette rubrique utilise l'ID de région cn-hangzhou de la région Chine (Hangzhou). Par défaut, le point de terminaison public est utilisé pour accéder aux ressources d'un bucket. Si vous souhaitez accéder aux ressources du bucket via 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 pris en charge par Object Storage Service (OSS), consultez Régions et points de terminaison OSS.

  • Dans cette rubrique, les identifiants d'accès sont récupérés à partir des variables d'environnement. Pour savoir comment configurer les identifiants d'accès, consultez la section Configurer les identifiants d'accès.

  • 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 des autorisations requises pour effectuer ces opérations. Si vous ne possédez pas les autorisations adéquates, contactez le propriétaire du bucket afin qu'il vous les accorde.

  • Vous pouvez configurer jusqu'à 1 000 inventaires pour un 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ù seront stockées les listes d'inventaire.

Exemple de code

Créer un inventaire pour un bucket

Le code suivant illustre la création d'un inventaire pour un 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)
}

Consulter les configurations d'inventaire d'un bucket

Le code suivant montre comment consulter les configurations d'inventaire d'un 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)
}

Répertorier les inventaires configurés pour un bucket

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 pour la suivante.

L'exemple ci-dessous illustre le listing des inventaires configurés pour un 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)
}

Supprimer un inventaire configuré pour un bucket

Voici un exemple de suppression d'un inventaire configuré pour un 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)
}

Références

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

  • Pour en savoir plus sur l'opération API utilisée pour consulter les configurations d'inventaire d'un bucket, reportez-vous à GetBucketInventory.

  • Consultez ListBucketInventory pour obtenir des détails sur l'opération API permettant de répertorier les inventaires configurés pour un bucket.

  • Des informations complémentaires sur l'opération API servant à supprimer les inventaires configurés pour un bucket sont disponibles dans DeleteBucketInventory.