Tous les produits
Search
Centre de documentation

Object Storage Service:Gérer l'inventaire des compartiments avec le SDK OSS pour Go 2.0

Dernière mise à jour :Aug 08, 2026

Cette rubrique explique comment créer un inventaire pour un compartiment, ainsi que comment consulter, lister et supprimer les inventaires configurés.

Notes

  • L'exemple de code de cette rubrique utilise l'ID de région cn-hangzhou (Chine (Hangzhou)). Par défaut, l'accès aux ressources d'un compartiment s'effectue via le point de terminaison public. Pour accéder aux ressources 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 pris en charge par Object Storage Service (OSS), consultez Régions et points de terminaison OSS.

  • Les identifiants d'accès proviennent des variables d'environnement. Pour savoir comment les configurer, consultez Configurer les identifiants d'accès.

  • Assurez-vous de disposer des autorisations nécessaires pour créer, consulter, lister et supprimer les inventaires d'un compartiment. Par défaut, le propriétaire du compartiment détient ces autorisations. Si ce n'est pas le cas, contactez-le pour qu'il vous les accorde.

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

  • Le compartiment source doit se trouver dans la même région que le compartiment de destination où seront stockées les listes d'inventaire.

Exemples de code

Créer un inventaire pour un compartiment

Le code suivant crée un inventaire pour un compartiment.

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 compartiment

Le code suivant consulte les configurations d'inventaire d'un compartiment.

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

Lister les inventaires configurés pour un compartiment

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 ci-dessous liste les inventaires configurés pour un compartiment.

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 compartiment

Le code suivant supprime un inventaire configuré pour un compartiment.

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 de création d'un inventaire pour un compartiment, consultez PutBucketInventory.

  • Pour plus d'informations sur l'opération API de consultation des configurations d'inventaire d'un compartiment, consultez GetBucketInventory.

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

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