You can use the bucket inventory feature to export the information about specified objects in a bucket, such as the number, sizes, storage classes, and encryption status of the objects. To list a large number of objects, we recommend that you use the bucket inventory feature instead of the GetBucket (ListObjects) operation.

Overview

After an inventory is configured for a bucket, Object Storage Service (OSS) generates inventory lists at the specified time interval. The following structure shows the directories in which generated inventory lists are stored.
dest_bucket
 └──destination-prefix/
     └──src_bucket/
         └──inventory_id/
             ├──YYYY-MM-DDTHH-MMZ/
             │   ├──manifest.json
             │   └──manifest.checksum
             └──data/
                 └──745a29e3-bfaa-490d-9109-47086afcc8f2.csv.gz
Directory Description
destination-prefix/ This directory is generated based on the prefix specified for inventory lists. If no prefix is specified for inventory lists, this directory is omitted.
src_bucket/ This directory is generated based on the name of the source bucket for which inventory lists are generated.
inventory_id/ The directory is generated based on the name of the inventory.
YYY-MM-DDTHH-MMZ/ This directory indicates the start time when the bucket is scanned. The name of this directory is a timestamp in GMT. Example: 2020-05-17T16-00Z. The manifest.json and manifest.checksum objects are stored in this directory.
data/ Inventory lists that include the metadata of exported objects in the source bucket are stored in this directory. Inventory lists are CSV files that are compressed by using Gzip.
Notice When large inventory lists are exported, they are split into multiple CSV files. The names of these CSV files are generated in the following format in sequence: uuid.csv.gz, uuid-1.csv.gz, and uuid-2.csv.gz. You can obtain the list of these CSV files from the manifest.json object. Then, you can decompress the files based on the preceding sequence to read the inventory lists.
After an inventory is configured for a bucket, the following objects are generated based on the inventory:
  • Manifest objects
    Manifest objects include manifest.json and manifest.checksum.
    • manifest.json: stores the metadata of inventory lists and related information.
      {
          "creationTimestamp": "1642994594",
          "destinationBucket": "destbucket",
          "fileFormat": "CSV",
          "fileSchema": "Bucket, Key, VersionId, IsLatest, IsDeleteMarker, Size, StorageClass, LastModifiedDate, ETag, IsMultipartUploaded, EncryptionStatus",
          "files": [{
                  "MD5checksum": "F77449179760C3B13F1E76110F07****",
                  "key": "destbucket/inventory0124/data/a1574226-b5e5-40ee-91df-356845777c04.csv.gz",
                  "size": 2046}],
          "sourceBucket": "srcbucket",
          "version": "2019-09-01"}

      The following table describes the fields included in the manifest.json object.

      Field Description
      creationTimestamp The start time when the source bucket is scanned. The value of this field is a UNIX timestamp.
      destinationBucket The bucket in which you want to store the generated inventory lists.
      fileFormat The format of the inventory lists.
      fileSchema The fields included in each inventory list.
      files The name, size, and MD5 hash of each inventory list.
      sourceBucket The source bucket for which the inventory lists are generated.
      version The version of the inventory list.
    • manifest.checksum: stores the MD5 hash of the manifest.json object. Example: 8420A430CBD6B659A1C0DFC1C11A****.
  • Inventory lists
    Inventory lists contain the exported object information and are stored in the data/ directory. The following figure shows an example of an inventory list.Inventory lists
    The following table describes the fields in the preceding figure from left to right.
    Field Description
    Bucket The name of the bucket for which the inventory is created.
    Key The name of the object in the bucket.

    The object name is URL-encoded. You must decode the object name before you can view the name.

    VersionId The version ID of the object.

    This field exists only when versioning is enabled for the bucket and the inventory specifies that all versions of data are exported.

    IsLatest Specifies whether the version is the latest version. If the version is the latest version, the value of this field is True. Otherwise, the value is False.

    This field exists only when versioning is enabled for the bucket and the inventory specifies that all versions of data are exported.

    IsDeleteMarker Specifies whether the version is a delete marker. If the version is a delete marker, the value of this field is True. Otherwise, the value is False.

    This field exists only when versioning is enabled for the bucket and the inventory specifies that all versions of data are exported.

    Size The size of the object.
    StorageClass The storage class of the object.
    LastModifiedDate The time when the object is last modified.
    ETag The ETag of the object.

    An ETag is generated when an object is created. The ETag is used to identify the content of the object.

    • If an object is created by calling PutObject, the ETag of the object is the MD5 hash of the object content.
    • If an object is created by using other methods, the ETag of the object is not the MD5 hash of the object content but a unique value calculated for the object.
    IsMultipartUploaded Specifies whether to upload the object by using multipart upload. If the object is created by using multipart upload, the value of this field is True. Otherwise, the value is False.
    EncryptionStatus Specifies whether to encrypt the object. If the object is encrypted, the value of this field is True. Otherwise, the value is False.

Usage notes

  • Permissions

    Resource Access Management (RAM) users must have permissions to configure inventories. If RAM users do not have the permissions in the following scenarios, you can perform the following operations to grant them permissions.

    • For a RAM user that has no permissions
      If a RAM user has no permissions and wants to use the bucket inventory feature, perform the following steps to grant them permissions:
      1. Create the following custom policy in the JSON format. For more information, see Create a custom policy.
        {
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "oss:PutBucketInventory",
                        "oss:GetBucketInventory",
                        "oss:DeleteBucketInventory",
                        "oss:ListBuckets",
                        "ram:CreateRole",
                        "ram:AttachPolicyToRole",
                        "ram:GetRole",
                        "ram:ListPoliciesForRole"
                    ],
                    "Resource": "*"
                }
            ],
            "Version": "1"
        }
      2. Attach the created custom policy to the RAM user. For more information, see Grant permissions to a RAM user.
    • For a RAM user that has the AliyunOSSFullAccess permission
      • Attach a custom policy to the RAM user

        If a RAM user has the AliyunOSSFullAccess permission, you can create the following custom policy in the JSON format and attach the created custom policy to the RAM user:

        {
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": [
                        "ram:CreateRole",
                        "ram:AttachPolicyToRole",
                        "ram:GetRole",
                        "ram:ListPoliciesForRole"
                    ],
                    "Resource": "*"
                }
            ],
            "Version": "1"
        }
      • Grant the AliyunRAMFullAccess permission

        If a RAM user has the AliyunOSSFullAccess permission and does not want to use the bucket inventory feature by attaching custom policies, you can grant the AliyunRAMFullAccess permission to the RAM user. For more information about how to grant system permissions, see Grant permissions to a RAM user.

    After you perform the preceding operations, use the OSS console to configure an inventory. After you configure the inventory, the RAM console automatically creates a RAM role named AliyunOSSRole. By default, the RAM role has permissions to read all objects from the source bucket and write objects to the destination bucket. If you want to use the bucket inventory feature by means of OSS SDKs, we recommend that you use the AliyunOSSRole RAM role created in the OSS console. This prevents other roles from being used to grant permissions.

  • Recommended configurations

    We recommend that you configure inventories based on the number of objects in the source bucket:

    • If the number of objects in the source bucket is less than 1 billion, you can configure inventories to export inventory lists on a daily basis.
    • If the number of objects in the source bucket is between 1 billion and 10 billion, you can configure inventories to export inventory lists on a weekly basis.
    • If the number of objects in the source bucket is greater than 10 billion, we recommend that you configure different inventories based on object prefixes to generate inventory lists on a weekly basis and make sure that the number of objects scanned based on each inventory does not exceed 10 billion.
  • Traffic and bandwidth

    To increase the speed at which inventory lists are exported, bucket- and user-level bandwidth may be occupied when the inventory lists are exported to the destination bucket. If the bucket for which you want to configure the inventory is frequently accessed and the available bandwidth of the bucket is limited, we recommend that you create a bucket as the destination bucket to store the inventory lists.

  • Exceptions
    • If no objects are stored in the bucket for which the inventory is configured or the specified prefix does not apply to objects in the inventory, inventory lists are not generated.
    • When you export the inventory lists, the exported lists may not contain all objects in the source bucket due to operations such as creation, deletion, or overwriting. If the time when an object is last modified is earlier than the time specified by the createTimeStamp field in the manifest.json object, inventory lists contain the information about the object. Otherwise, inventory lists may not contain the information about the object. We recommend that you check the object attributes by calling HeadObject before you export the information about an object. For more information, see HeadObject.

Limits

  • You can configure up to 1,000 inventories for a bucket by using OSS SDKs or ossutil. You can configure a maximum of 10 inventories in the OSS console.
  • The bucket for which you want to configure the inventory and the bucket in which you want to store the generated inventory lists do not have to be the same bucket, but they must belong to the same Alibaba Cloud account and reside within the same region.

Billing

  • You are charged for the bucket inventory feature. However, you are only charged storage fees for inventory lists and API operation calling fees during public preview.
  • OSS generates inventory lists based on the inventory until you delete the inventory. Fees are incurred for the storage of the inventory lists. To prevent unnecessary costs, delete inventory lists that are no longer needed.

Use the OSS console

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the bucket that you want to manage.
  3. In the left-side navigation pane, choose Basic Settings > Bucket Inventory. In the Bucket Inventory section, click Configure.
  4. Click Create Inventory. In the Create Inventory panel, configure the parameters in the following table.
    Parameter Description
    Status Set the status of the inventory. You can select Enabled or Disabled.
    Rule Name Set the name of the inventory. The name can contain only lowercase letters, digits, and hyphens (-) and cannot start or end with a hyphen (-).
    Destination Bucket Select the bucket in which generated inventory lists are stored.

    The source bucket for which an inventory is configured and the destination bucket in which the inventory lists are stored do not have to be the same bucket, but they must belong to the same account and reside within the same region.

    Inventory List Path Configure the directory in which generated inventory lists are stored.
    • If you want to store the inventory lists in the root directory of the destination bucket, leave the parameter empty.
    • Otherwise, specify the parameter as a full path of a directory, excluding the destination bucket name.

      For example, when you want to store the inventory lists in the exampledir1 path of the destination bucket named examplebucket, set the parameter to exampledir1. When you want to store the inventory lists in the exampledir2 subdirectory of the exampledir1 directory, set the parameter to exampledir1/exampledir2.

    Frequency Configure the frequency at which inventory lists are generated. You can select Weekly or Daily.
    We recommend that you configure inventories based on the number of objects in the source bucket:
    • If the number of objects in the source bucket is smaller than 1 billion, we recommend that you configure inventories to export inventory lists on a daily basis.
    • If the number of objects in the source bucket is between 1 billion and 10 billion, we recommend that you configure inventories to export inventory lists on a weekly basis.
    • If the number of objects in the source bucket is greater than 10 billion, we recommend that you configure different inventories based on object prefixes to generate inventory lists on a weekly basis and make sure the number of objects scanned based on each inventory does not exceed 10 billion.
    Encryption Method Specify whether to encrypt inventory lists.
    • None: Inventory lists are not encrypted.
    • AES-256: Inventory lists are encrypted by using AES-256.
    • KMS: Inventory lists are encrypted by using a customer master key (CMK) managed by Key Management Service (KMS).

      To use a CMK to encrypt inventory lists, you must create a CMK in KMS in the same region as the destination bucket. For more information about how to configure CMKs, see Create a CMK.

      Note You are charged for calling API operations when you use CMKs to encrypt or decrypt data.
    Object Versions Select the object version to which the inventory is applied.

    If versioning is enabled for the bucket, you can select Current Version or All Versions to generate inventory lists for the current version or all versions of objects in the bucket. For more information, see Overview.

    By default, inventory lists are generated for all objects in the bucket if versioning is not enabled for the bucket.

    Object Prefix Set the prefix based on which to scan objects.
    • To scan all objects in the bucket, do not specify this parameter.
    • To scan all objects in a directory of the bucket, set this parameter to the full path that does not include the bucket name.

      To scan all objects in the exampledir1 root directory of the examplebucket bucket, set this parameter to exampledir1/. To scan all objects in the exampledir2 subdirectory of the exampledir1 root directory, set this parameter to exampledir1/exampledir2/.

    Note If no objects in the bucket match the specified prefix, no inventory lists are generated.
    Optional Fields Select the object information that you want to export to inventory lists. You can select the following fields: Object Size, Storage Class, Last Update Time, ETag, Multipart Upload, and Encryption Status.
  5. Read and select I understand the terms and agree to authorize Alibaba Cloud OSS to access the resources in my buckets. Then, click OK.
    It may take a while to generate an inventory list for a large number of objects. If you want to be notified when the inventory list is generated for the objects, we recommend that you configure an event notification for the destination bucket in which the inventory list is stored and set the event to PutObject. When an inventory list is generated, a notification is sent to you. For more information about how to configure event notifications, see Configure event notification rules.

Use OSS SDKs

The following code provides examples on how to configure an inventory for a bucket by using OSS SDKs for common programming languages. For more information about how to configure an inventory for a bucket by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.ArrayList;
import java.util.List;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the name of the bucket in which you want to store the generated inventory lists. 
        String destBucketName ="yourDestinationBucketName";
        // Specify the account ID granted by the bucket owner. 
        String accountId ="yourDestinationBucketAccountId";
        // Specify the RAM role for which you want to configure inventories. The RAM role must have permissions to read the source bucket for which you want to configure the inventory and permissions to write data to the destination bucket in which you want to store the generated inventory lists. 
        String roleArn ="yourDestinationBucketRoleArn";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // Create an inventory. 
            InventoryConfiguration inventoryConfiguration = new InventoryConfiguration();

            // Specify the name of the inventory. 
            String inventoryId = "testid";
            inventoryConfiguration.setInventoryId(inventoryId);

            // Specify the object attributes to include in the inventory lists. 
            List<String> fields = new ArrayList<String>();
            fields.add(InventoryOptionalFields.Size);
            fields.add(InventoryOptionalFields.LastModifiedDate);
            fields.add(InventoryOptionalFields.IsMultipartUploaded);
            fields.add(InventoryOptionalFields.StorageClass);
            fields.add(InventoryOptionalFields.ETag);
            fields.add(InventoryOptionalFields.EncryptionStatus);
            inventoryConfiguration.setOptionalFields(fields);

            // Specify whether to generate the inventory list on a daily basis or weekly basis. The following code provides an example on how to generate inventory list on a weekly basis. Weekly indicates that the inventory lists are generated once a week and Daily indicates that the inventory lists are generated once a day. 
            inventoryConfiguration.setSchedule(new InventorySchedule().withFrequency(InventoryFrequency.Weekly));

            // Specify that the inventory lists include only the current version of objects. If you set the InventoryIncludedObjectVersions parameter to All, all versions of objects are included in the inventory lists. This configuration takes effect only when you enable versioning for the bucket. 
            inventoryConfiguration.setIncludedObjectVersions(InventoryIncludedObjectVersions.Current);

            // Specify whether the inventory is enabled. Valid values: true and false. Set the value to true to enable the inventory. Set the value to false to disable the inventory. 
            inventoryConfiguration.setEnabled(true);

            // Specify the rule used to filter the objects to include in the inventory lists. The following code provides an example on how to filter the objects by a prefix. 
            InventoryFilter inventoryFilter = new InventoryFilter().withPrefix("obj-prefix");
            inventoryConfiguration.setInventoryFilter(inventoryFilter);

            // Configure the destination bucket that you want to store the generated inventory lists. 
            InventoryOSSBucketDestination ossInvDest = new InventoryOSSBucketDestination();
            // Specify the prefix of the path in which you want to store the generated inventory lists. 
            ossInvDest.setPrefix("destination-prefix");
            // Specify the format of the inventory lists. 
            ossInvDest.setFormat(InventoryFormat.CSV);
            // Specify the ID of the Alibaba Cloud account to which the destination bucket belongs. 
            ossInvDest.setAccountId(accountId);
            // Specify the role ARN of the destination bucket. 
            ossInvDest.setRoleArn(roleArn);
            // Specify the name of the destination bucket. 
            ossInvDest.setBucket(destBucketName);

            // The following code provides an example on how to encrypt the inventory lists by using customer master keys (CMKs) hosted in KMS. 
            // InventoryEncryption inventoryEncryption = new InventoryEncryption();
            // InventoryServerSideEncryptionKMS serverSideKmsEncryption = new InventoryServerSideEncryptionKMS().withKeyId("test-kms-id");
            // inventoryEncryption.setServerSideKmsEncryption(serverSideKmsEncryption);
            // ossInvDest.setEncryption(inventoryEncryption);

            // The following code provides an example on how to encrypt the inventory list on the OSS server. 
            // InventoryEncryption inventoryEncryption = new InventoryEncryption();
            // inventoryEncryption.setServerSideOssEncryption(new InventoryServerSideEncryptionOSS());
            // ossInvDest.setEncryption(inventoryEncryption);

            // Specify the destination for the inventory results. 
            InventoryDestination destination = new InventoryDestination();
            destination.setOssBucketDestination(ossInvDest);
            inventoryConfiguration.setDestination(destination);

            // Upload the inventory. 
            ossClient.setBucketInventoryConfiguration(bucketName, inventoryConfiguration);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
const OSS = require('ali-oss');

const client = new OSS({
  bucket: '<Your BucketName>',
  // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
  region: '<oss-cn-hangzhou>',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  accessKeyId: '<Your AccessKeyId>',
  accessKeySecret: '<Your AccessKeySecret>'
});

const inventory = {
  // Specify the ID of the inventory. 
  id: 'default', 
  // Specify whether to enable the inventory for the bucket. Valid values: true and false. 
  isEnabled: false, 
  // (Optional) Specify the rule that is used to filter the objects included in inventory lists. The following code provides an example on how to filter the objects by prefix. 
  prefix: 'ttt',
  OSSBucketDestination: {
     // Specify the format of inventory lists. 
    format: 'CSV',
   // Specify the ID of the Alibaba Cloud account to which the destination bucket belongs. 
    accountId: '<Your AccountId>', 
   // Specify the name of the RAM role that is used to access the destination bucket. 
    rolename: 'AliyunOSSRole',
    // Specify the name of the destination bucket. 
    bucket: '<Your BucketName>',
    // (Optional) Specify the prefix of the path in which you want to store the generated inventory lists. 
    prefix: '<Your Prefix>',
    // The following code provides an example on how to encrypt the inventory lists by using OSS-managed keys (SSE-OSS). 
    //encryption: {'SSE-OSS': ''},
    // The following code provides an example on how to encrypt the inventory lists by using CMKs managed by KMS (SSE-KMS). 
           /*
            encryption: {
      'SSE-KMS': {
        keyId: 'test-kms-id';
      };, 
    */
  },
  // Specify whether to generate inventory lists on a daily or weekly basis. A value of Weekly indicates that inventory lists are generated on a weekly basis. A value of Daily indicates that inventory lists are generated on a daily basis. 
  frequency: 'Daily', 
  // Specify that all versions of the objects are included in inventory lists. If the value of includedObjectVersions is set to Current, only the current versions of the objects are included in inventory lists. 
  includedObjectVersions: 'All', 
  optionalFields: {
    // (Optional) Specify object attributes that are included in inventory lists. 
    field: ["Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus"]
  },
}

async function putInventory(){
  // Specify the name of the bucket for which you want to create an inventory. 
  const bucket = '<Your BucketName>'; 
        try {
    await client.putBucketInventory(bucket, inventory);
    console.log('An inventory is created.')
  } catch(err) {
    console.log('Failed to create an inventory: ', err);
  }
}

putInventory()
# -*- coding: utf-8 -*-

import oss2
from oss2.models import (InventoryConfiguration,
                        InventoryFilter, 
                        InventorySchedule, 
                        InventoryDestination, 
                        InventoryBucketDestination, 
                        InventoryServerSideEncryptionKMS,
                        InventoryServerSideEncryptionOSS,
                        INVENTORY_INCLUDED_OBJECT_VERSIONS_CURRENT,
                        INVENTORY_INCLUDED_OBJECT_VERSIONS_ALL,
                        INVENTORY_FREQUENCY_DAILY,
                        INVENTORY_FREQUENCY_WEEKLY,
                        INVENTORY_FORMAT_CSV,
                        FIELD_SIZE,
                        FIELD_LAST_MODIFIED_DATE,
                        FIELD_STORAG_CLASS,
                        FIELD_ETAG,
                        FIELD_IS_MULTIPART_UPLOADED,
                        FIELD_ENCRYPTION_STATUS)

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# Specify the account ID granted by the bucket owner to perform the PutBucketInventory operation. 
account_id = 'yourtBucketDestinationAccountId'
# Specify the RAM role for which you want to configure inventories. The RAM role must have permissions to read the source bucket for which you want to configure the inventory and permissions to write data to the destination bucket in which you want to store the generated inventory lists. 
role_arn = 'yourBucketDestinationRoleArn'
# Specify the name of the bucket in which you want to store the generated inventory lists. 
dest_bucket_name = 'yourDestinationBucketName'

# Specify the inventory name. 
inventory_id = "inventory1"

# Specify the object attributes to include in the inventory lists. 
optional_fields = [FIELD_SIZE, FIELD_LAST_MODIFIED_DATE, FIELD_STORAG_CLASS,
        FIELD_ETAG, FIELD_IS_MULTIPART_UPLOADED, FIELD_ENCRYPTION_STATUS]

# Create an configuration for the destination bucket. 
bucket_destination = InventoryBucketDestination(
        # Specify the ID of the Alibaba Cloud account that owns the destination bucket. 
        account_id=account_id, 
        # Specify the role ARN of the destination bucket. 
        role_arn=role_arn,
        # Specify the name of the destination bucket. 
        bucket=dest_bucket_name,
        # Specify the format of the inventory lists. 
        inventory_format=INVENTORY_FORMAT_CSV,
        # Specify the prefix of the path in which you want to store the generated inventory lists. 
        prefix='destination-prefix',
        # The following code provides an example on how to encrypt the inventory list object by using CMKs hosted in KMS. 
        # sse_kms_encryption=InventoryServerSideEncryptionKMS("test-kms-id"),
        # The following code provides an example on how to encrypt the inventory list object on the OSS server. 
        # sse_oss_encryption=InventoryServerSideEncryptionOSS()
        )

# Create an inventory configuration. 
inventory_configuration = InventoryConfiguration(
        # Specify the inventory ID. 
        inventory_id=inventory_id,
        # Specify whether the inventory is enabled. True indicates that the inventory list is generated, while false indicates that no inventory list is generated. 
        is_enabled=True, 
        # Specify whether to generate the inventory on a daily or weekly basis. The following code provides an example to generate an inventory on a daily basis.  
        inventory_schedule=InventorySchedule(frequency=INVENTORY_FREQUENCY_DAILY),
        # Set the inventory list to include only the current version. If you set this parameter to INVENTORY_INCLUDED_OBJECT_VERSIONS_ALL, all versions are inventoried. Versioning must be enabled for this configuration to take effect. 
        included_object_versions=INVENTORY_INCLUDED_OBJECT_VERSIONS_CURRENT,
        # Specify the prefix of object names to filter objects to include in the inventory list. 
        inventory_filter=InventoryFilter(prefix="obj-prefix"),
        # Specify the object attributes to include in the inventory list. 
        optional_fields=optional_fields,
        # Specify the destination for the inventory lists. 
        inventory_destination=InventoryDestination(bucket_destination=bucket_destination))

# Apply the inventory configuration to the bucket. 
bucket.put_bucket_inventory_configuration(inventory_configuration)
using Aliyun.OSS;
using Aliyun.OSS.Common;

// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. 
var bucketName = "examplebucket";
// Specify the account ID granted by the bucket owner to perform the PutBucketInventory operation. 
var accountId ="yourDestinationBucketAccountId";
// Specify the RAM role for which you want to configure inventories. The RAM role must have permissions to read the source bucket for which you want to configure the inventory and permissions to write data to the destination bucket in which you want to store the generated inventory lists. 
var roleArn ="yourDestinationBucketRoleArn";
// Specify the name of the bucket in which you want to store the generated inventory lists. 
var destBucketName ="yourDestinationBucketName";
// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    // Create an inventory for the bucket. 
    var config = new InventoryConfiguration();
    // Specify the inventory name. 
    config.Id = "report1";
    // Specify whether inventory is enabled for the bucket. Valid values: true and false. If you set this parameter to true, the inventory is enabled. 
    config.IsEnabled = true;
    // Specify the rule used to filter the objects to include in the inventory lists. The following code provides an example on how to filter the objects by prefix. 
    config.Filter = new InventoryFilter("filterPrefix");
    // Configure the destination bucket used to store the generated inventory lists. 
    config.Destination = new InventoryDestination();
    config.Destination.OSSBucketDestination = new InventoryOSSBucketDestination();
    // Specify the format of the inventory lists. 
    config.Destination.OSSBucketDestination.Format = InventoryFormat.CSV;
    // Specify the ID of the Alibaba Cloud account that owns the destination bucket. 
    config.Destination.OSSBucketDestination.AccountId = accountId;
    // Specify the role ARN of the destination bucket. 
    config.Destination.OSSBucketDestination.RoleArn = roleArn;
    // Specify the name of the destination bucket in which the generated inventory lists are stored. 
    config.Destination.OSSBucketDestination.Bucket = destBucketName;
    // Specify the prefix of the path in which you want to store the generated inventory lists. 
    config.Destination.OSSBucketDestination.Prefix = "prefix1";
    
    // Specify whether to generate the inventory list on a daily or weekly basis. The following code provides an example on how to generate an inventory list on a weekly basis.  
    config.Schedule = new InventorySchedule(InventoryFrequency.Daily);
    // Specify that the inventory list includes only the current version of objects. If you set the InventoryIncludedObjectVersions parameter to All, all versions of objects are included in the inventory list. This configuration takes effect only when versioning is enabled for the bucket. 
    config.IncludedObjectVersions = InventoryIncludedObjectVersions.All;
    
    // Specify the object attributes to include in the inventory lists. 
    config.OptionalFields.Add(InventoryOptionalField.Size);
    config.OptionalFields.Add(InventoryOptionalField.LastModifiedDate);
    config.OptionalFields.Add(InventoryOptionalField.StorageClass);
    config.OptionalFields.Add(InventoryOptionalField.IsMultipartUploaded);
    config.OptionalFields.Add(InventoryOptionalField.EncryptionStatus);
    config.OptionalFields.Add(InventoryOptionalField.ETag);
    var req = new SetBucketInventoryConfigurationRequest(bucketName, config)
    client.SetBucketInventoryConfiguration(req);
    Console.WriteLine("Set bucket:{0} InventoryConfiguration succeeded", bucketName);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // Create an OSSClient instance. 
    // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the endpoint based on your business requirements. 
    // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    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 CMKs hosted in KMS. 
    //var invEncryption oss.InvEncryption
    //var invSseOss oss.InvSseOss
    //var invSseKms oss.InvSseKms
    //invSseKms.KmsId = "<yourKmsId>" // Specify your CMK ID. 
    //invEncryption.SseOss = &invSseOss // Use OSS-managed keys (SSE-OSS) to encrypt the inventory lists. 
    //invEncryption.SseKms = &invSseKms // Use CMKs stored in KMS (SSE-KMS) to encrypt the inventory lists. 

    invConfig := oss.InventoryConfiguration{
        // Specify the name of the inventory. The name must be globally unique in the current bucket. 
        Id: "yourInventoryId2",
        // Enable an inventory configuration. 
        IsEnabled: &bEnabled,

        // Specify the rule used to filter the objects to include in the inventory lists. 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 list. 
            Format: "CSV",

            // Specify the ID of the account granted by the bucket owner. Example: 109885487000****. 
            AccountId: "yourGrantAccountId",

            // Specify the RAM role to which the bucket owner grants permissions. 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",

            // To encrypt inventory lists, refer to the following code. 
            //Encryption:     &invEncryption,
        },

        // Specify the frequency at which inventory lists are exported. 
        Frequency: "Daily",

        // Specify whether the information about all versions of the objects is included in the inventory list. 
        IncludedObjectVersions: "All",

        OptionalFields: oss.OptionalFields{
            // Specify the configuration fields included in the inventory lists. 
            Field: []string{
                "Size", "LastModifiedDate", "ETag", "StorageClass", "IsMultipartUploaded", "EncryptionStatus",
            },
        },
    }
    // Specify yourBucketName as 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)
    }
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access Object Storage Service (OSS). */
    /* Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources such as networks. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    InventoryConfiguration inventoryConf;
    /* Specify the inventory name, which must be globally unique in the current bucket. */
    inventoryConf.setId("inventoryId");

    /* Specify whether inventory is enabled for the bucket. Valid values: true and false. */
    inventoryConf.setIsEnabled(true);

    /* Optional. Specify the prefix of object names to filter objects to include in the inventory lists. After you specify the prefix, the information about objects whose names contain the prefix is included in the inventory list. */
    inventoryConf.setFilter(InventoryFilter("objectPrefix"));

    InventoryOSSBucketDestination dest;
    /* Specify the format of the exported inventory lists. */
    dest.setFormat(InventoryFormat::CSV);
    /* Specify the account ID that is granted by the bucket owner. */
    dest.setAccountId("10988548********");
    /* Specify the role ARN to which the bucket owner grants the operation permissions. */
    dest.setRoleArn("acs:ram::10988548********:role/inventory-test");
    /* Specify the bucket in which you want to store the generated inventory lists. */
    dest.setBucket("yourDstBucketName");
    /* Specify the prefix of the path in which you want to store the generated inventory lists. */
    dest.setPrefix("yourPrefix");
    /* Optional. Specify the method for encrypting the inventory list object. You can use SSEOSS or SSEKMS. */
    //dest.setEncryption(InventoryEncryption(InventorySSEOSS()));
    //dest.setEncryption(InventoryEncryption(InventorySSEKMS("yourKmskeyId")));
    inventoryConf.setDestination(dest);

    /* Specify the frequency at which the inventory lists are exported. You can set Daily or Weekly. */
    inventoryConf.setSchedule(InventoryFrequency::Daily);

    /* Set the object versions to include in the inventory list. Valid values: All and Current. */
    inventoryConf.setIncludedObjectVersions(InventoryIncludedObjectVersions::All);

    /* Optional. Specify the fields to include in the inventory lists based on your requirements. */
    InventoryOptionalFields field { 
        InventoryOptionalField::Size, InventoryOptionalField::LastModifiedDate, 
        InventoryOptionalField::ETag, InventoryOptionalField::StorageClass, 
        InventoryOptionalField::IsMultipartUploaded, InventoryOptionalField::EncryptionStatus
    };
    inventoryConf.setOptionalFields(field);

    /* Configure the inventory. */
    auto outcome = client.SetBucketInventoryConfiguration(
        SetBucketInventoryConfigurationRequest(BucketName, inventoryConf));

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "Set Bucket Inventory fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        ShutdownSdk();
        return -1;
    }

    /* Release resources such as networks. */
    ShutdownSdk();
    return 0;
}

Use ossutil

For more information about how to configure an inventory for a bucket by using ossutil, see inventory (configure bucket inventories).

Use the RESTful API

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutBucketInventory.

FAQ

How do I know whether inventory lists are generated?

It may take a specific period of time to generate inventory lists for a large number of objects. If you want to be notified when inventory lists are generated for objects, we recommend that you configure an event notification rule for the bucket in which inventory lists are stored and set the event type to PutObject. When inventory lists are generated, notifications are sent to you. For more information about how to configure event notifications, see Configure event notification rules.