All Products
Search
Document Center

Object Storage Service:Manage bucket inventory using OSS SDK for Go 2.0

Last Updated:Mar 20, 2026

Use the OSS Go SDK V2 to create, query, list, and delete bucket inventory configurations.

Prerequisites

Before you begin, make sure that you have:

  • Configured access credentials as environment variables

  • Permissions to create, query, list, and delete inventories for the bucket. By default, the bucket owner has these permissions. If not, ask the bucket owner to grant them.

  • A destination bucket in the same region as the source bucket

Usage notes

  • A bucket can have up to 1,000 inventory configurations.

  • The source bucket and the destination bucket must be in the same region.

  • Each list request returns up to 100 inventory configurations. If there are more than 100, the response includes a token — pass it as a parameter in the next request to paginate through more results.

  • The code samples use the cn-hangzhou region. Replace it with your actual region. For available regions and endpoints, see OSS regions and endpoints. If you access OSS from other Alibaba Cloud products in the same region, use an internal endpoint.

Create an inventory

Use PutBucketInventoryRequest to submit the inventory configuration. The destination bucket, RAM role ARN, and schedule frequency are required fields.

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

var (
	region     string
	bucketName string
)

func init() {
	flag.StringVar(&region, "region", "", "The region where the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The bucket name.")
}

func main() {
	flag.Parse()

	var (
		accountId   = "account id of the bucket" // Alibaba Cloud account ID granted permissions by the bucket owner. Example: 109885487000****.
		inventoryId = "inventory id"             // Inventory name. Must be unique within the bucket.
	)

	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg)

	request := &oss.PutBucketInventoryRequest{
		Bucket:      oss.Ptr(bucketName),
		InventoryId: oss.Ptr(inventoryId),
		InventoryConfiguration: &oss.InventoryConfiguration{
			Id:        oss.Ptr(inventoryId),
			IsEnabled: oss.Ptr(true),
			Filter: &oss.InventoryFilter{
				Prefix:                   oss.Ptr("filterPrefix"),    // Filter objects by prefix.
				LastModifyBeginTimeStamp: oss.Ptr(int64(1637883649)), // Unix timestamp: filter start time.
				LastModifyEndTimeStamp:   oss.Ptr(int64(1638347592)), // Unix timestamp: filter end time.
				LowerSizeBound:           oss.Ptr(int64(1024)),       // Minimum object size in bytes.
				UpperSizeBound:           oss.Ptr(int64(1048576)),    // Maximum object size in bytes.
				StorageClass:             oss.Ptr("Standard,IA"),     // Filter by storage class. Separate multiple values with commas.
			},
			Destination: &oss.InventoryDestination{
				OSSBucketDestination: &oss.InventoryOSSBucketDestination{
					Format:    oss.InventoryFormatCSV,                                   // The format of the exported inventory lists.
					AccountId: oss.Ptr(accountId),                                       // Alibaba Cloud account ID. Example: 109885487000****.
					RoleArn:   oss.Ptr("acs:ram::" + accountId + ":role/AliyunOSSRole"), // RAM role ARN. Example: acs:ram::109885487000****:role/ram-test.
					Bucket:    oss.Ptr("acs:oss:::" + bucketName),                       // Destination bucket for inventory lists.
					Prefix:    oss.Ptr("export/"),                                       // Path prefix for inventory list files in the destination bucket.
				},
			},
			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.
		},
	}

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

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

Key parameters

ParameterTypeDescription
IdstringInventory name. Must be unique within the bucket.
IsEnabledboolWhether the inventory is enabled.
IncludedObjectVersionsstringObject versions to include in the inventory list. Example: All.
FrequencyenumExport frequency. Example: oss.InventoryFrequencyDaily (daily).
FormatenumInventory list format. Example: oss.InventoryFormatCSV (CSV).
AccountIdstringAlibaba Cloud account ID of the account granted permissions by the bucket owner.
RoleArnstringARN of the RAM role granted permissions. Format: acs:ram::<accountId>:role/<roleName>.
Bucket (destination)stringDestination bucket in the format acs:oss:::<bucketName>. Must be in the same region as the source bucket.
Prefix (filter)stringFilters inventory to objects whose keys start with this prefix.
LastModifyBeginTimeStampint64Unix timestamp. Filters to objects last modified after this time.
LastModifyEndTimeStampint64Unix timestamp. Filters to objects last modified before this time.
LowerSizeBoundint64Minimum object size in bytes.
UpperSizeBoundint64Maximum object size in bytes.
StorageClass (filter)stringFilters by storage class. Comma-separated values, e.g., Standard,IA.
Prefix (destination)stringPath prefix for inventory list files stored in the destination bucket.

Query an inventory

Use GetBucketInventoryRequest to retrieve the configuration of a specific inventory by name.

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

var (
	region     string
	bucketName string
)

func init() {
	flag.StringVar(&region, "region", "", "The region where the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The bucket name.")
}

func main() {
	flag.Parse()

	var inventoryId = "inventory id"

	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg)

	request := &oss.GetBucketInventoryRequest{
		Bucket:      oss.Ptr(bucketName),
		InventoryId: oss.Ptr(inventoryId),
	}

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

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

List inventories

Each request returns up to 100 inventory configurations. If a bucket has more than 100, the response includes a token — pass it as a parameter in the next request to retrieve the next page.

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

var (
	region     string
	bucketName string
)

func init() {
	flag.StringVar(&region, "region", "", "The region where the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The bucket name.")
}

func main() {
	flag.Parse()

	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg)

	request := &oss.ListBucketInventoryRequest{
		Bucket: oss.Ptr(bucketName),
	}

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

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

Delete an inventory

Use DeleteBucketInventoryRequest to delete a specific inventory configuration by name.

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

var (
	region     string
	bucketName string
)

func init() {
	flag.StringVar(&region, "region", "", "The region where the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The bucket name.")
}

func main() {
	flag.Parse()

	var inventoryId = "inventory id"

	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg)

	request := &oss.DeleteBucketInventoryRequest{
		Bucket:      oss.Ptr(bucketName),
		InventoryId: oss.Ptr(inventoryId),
	}

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

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

API reference

OperationGo methodReference
Create an inventoryclient.PutBucketInventory()PutBucketInventory
Query an inventoryclient.GetBucketInventory()GetBucketInventory
List inventoriesclient.ListBucketInventory()ListBucketInventory
Delete an inventoryclient.DeleteBucketInventory()DeleteBucketInventory