Updated on 2026-07-31 GMT+08:00

Configuring a Bucket Inventory Rule (SDK for Python)

Function

This API is used to configure a bucket inventory rule. With this API, object information in a bucket (source) is regularly listed and saved as CSV files. These files are then stored in a specified bucket (destination). In this manner, you can easily manage objects in a bucket. A source bucket can also be the destination bucket. A bucket inventory file contains the following object-related information: object versions, sizes, storage classes, tags, encryption statuses, and last modification time.

You can encrypt bucket inventory files using SSE-KMS.

Restrictions

  • To configure a bucket inventory rule, you must be the bucket owner or have the required permission (obs:bucket:PutBucketInventoryConfiguration granted using IAM or PutBucketInventoryConfiguration granted using a bucket policy). For details, see Introduction to OBS Access Control, IAM Custom Policies, and Creating a Custom Bucket Policy.
  • The mapping between OBS regions and endpoints must comply with what is listed in Regions and Endpoints.
  • Bucket versions
    • Inventories can be generated only for OBS 3.0 buckets, but the bucket that stores the inventory files can be any OBS version.
  • Number of bucket inventory rules
    • A bucket can have a maximum of 10 inventory rules.
  • Source and destination buckets
    • The source bucket (for which a bucket inventory rule is configured) and the destination bucket (where the generated inventory files are stored) must belong to the same account.
    • The source bucket and the destination bucket must be in the same region.
    • Default encryption cannot be enabled for the destination bucket configured for storing inventory files.
  • Functions
    • Inventory files can only be saved in CSV format.
    • Inventories can apply to all objects in a bucket or to a set of objects with the same name prefix.
    • The filter criteria of multiple inventory rules within the same bucket must not overlap.
      • If there is already an inventory rule for all objects in the bucket, any other inventory rule with an object name prefix specified cannot be created. To create a rule for only a set of objects, delete the inventory rule that applies to all objects first.
      • If there is already an inventory rule for a set of objects, a rule for all objects in the bucket cannot be created. To create a rule for all objects, delete all inventory rules that use a prefix filter.
      • Assume there is an inventory rule that uses the ab prefix as a filter. Any new inventory rule whose prefix overlaps with ab, such as a or abc, cannot be created. To create a rule with prefix a or abc, delete the overlapping rule first.
    • Only SSE-KMS can be used to encrypt bucket inventories.
  • Permissions
    • Inventory files are uploaded to the destination bucket by an OBS system user. Therefore, you need to grant the system user the permission to write objects to the destination bucket.
  • Others
    • The bucket inventory function is offered for free, but inventory files are billed for the storage they use.

Method

ObsClient.putBucketInventory(bucketName, inventoryId, inventoryConfiguration, extensionHeaders)

Request Parameters

Parameter

Type

Mandatory (Yes/No)

Description

bucketName

str

Yes

Explanation:

Bucket name

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain a period (.) and a hyphen (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets with the same name in the same region, no error will be reported and the bucket properties comply with those set in the first creation request.

Default value:

None

inventoryId

str

Yes

Explanation:

ID of a bucket inventory rule

Restrictions:

The rule ID allows letters (a–z, A–Z), digits (0–9), hyphens (-), underscores (_), and periods (.).

Value range:

The value can be up to 64 characters long.

Default value:

None

inventoryConfiguration

InventoryConfiguration

Yes

Explanation:

Bucket inventory configurations. For details, see Table 1.

extensionHeaders

dict

No

Explanation:

Extension headers

Value range:

See User-defined Headers (SDK for Python).

Default value:

None

Table 1 InventoryConfiguration

Parameter

Type

Mandatory (Yes/No)

Description

inventoryId

str

Yes

Explanation:

ID of a bucket inventory rule

Restrictions:

The rule ID allows letters (a–z, A–Z), digits (0–9), hyphens (-), underscores (_), and periods (.).

Value range:

The value can be up to 64 characters long.

Default value:

None

isEnabled

bool

Yes

Explanation:

Whether the bucket inventory rule is enabled

Value range:

True: The rule is enabled, and inventory files are generated.

False: The rule is disabled, and inventory files are not generated.

Default value:

True

objectVersion

str

Yes

Explanation:

Whether versions of objects are included in an inventory

Value range:

  • If this parameter is set to All, all the versions of objects are included in the inventory, and version-related fields are added to the inventory, including: VersionId, IsLatest, and DeleteMarker.
  • If this parameter is set to Current, the inventory only lists information about the current object version and does not include any version-related fields.

Default value:

None

filter

Table 2

No

Explanation:

Inventory filter configuration. The inventory contains only objects that meet the filter criteria (filtering by object name prefix). If no filter criteria are configured, all objects are included. For details, see Table 2.

frequency

str

Yes

Explanation:

The intervals at which inventories are generated. You can set it to Daily or Weekly. An inventory is generated within one hour after it is configured for the first time, and subsequently at the specified intervals.

Value range:

Daily: Inventories are generated once a day.

Weekly: Inventories are generated once a week.

Default value:

None

destination

Table 3

Yes

Explanation:

Destination configuration of an inventory. For details, see Table 3.

optionalFields

list

No

Explanation:

Additional object metadata fields that are contained in an inventory file

Value range:

Size: the object size

LastModifiedDate: the last modification time of an object

StorageClass: the storage class of an object

ETag: the ETag value of an object

IsMultipartUploaded: whether an object is uploaded in a multipart upload

ReplicationStatus: the cross-region replication status of an object

EncryptionStatus: the encryption status of an object

Default value:

None

Table 2 InventoryFilter

Parameter

Type

Mandatory (Yes/No)

Description

prefix

str

No

Explanation:

Prefix for filtering objects. Only objects with the specified name prefix are included in the inventory.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

Table 3 InventoryDestination

Parameter

Type

Mandatory (Yes/No)

Description

bucket

str

Yes

Explanation:

Name of the bucket for storing inventories

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain a period (.) and a hyphen (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets with the same name in the same region, no error will be reported and the bucket properties comply with those set in the first creation request.

Default value:

None

prefix

str

No

Explanation:

The prefix of the inventory file name

Value range:

The value must contain 1 to 1,024 characters.

Default value:

If you do not specify this parameter, BucketInventory is used as the prefix by default.

format

str

Yes

Explanation:

Inventory file format. Only the CSV format is supported.

Value range:

CSV

Default value:

None

Responses

Type

Description

GetResult

Explanation:

SDK common results

Table 4 GetResult

Parameter

Type

Description

status

int

Explanation:

HTTP status code

Value range:

A status code is a group of digits indicating the status of a response. It ranges from 2xx (indicating successes) to 4xx or 5xx (indicating errors). For more information, see Status Code.

Default value:

None

reason

str

Explanation:

Reason description

Default value:

None

errorCode

str

Explanation:

Error code returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

errorMessage

str

Explanation:

Error message returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

requestId

str

Explanation:

Request ID returned by the OBS server

Default value:

None

indicator

str

Explanation:

Error indicator returned by the OBS server

Default value:

None

hostId

str

Explanation:

Requested server ID. If the value of status is less than 300, this parameter is left blank.

Default value:

None

resource

str

Explanation:

Error source (a bucket or an object). If the value of status is less than 300, this parameter is left blank.

Default value:

None

header

list

Explanation:

Response header list, composed of tuples. Each tuple consists of two elements, respectively corresponding to the key and value of a response header.

Default value:

None

body

object

Explanation:

Result content returned after the operation is successful. If the value of status is larger than 300, this parameter is left blank. The value varies with the API being called. For details, see the sections "Bucket-Related APIs" and "Object-Related APIs".

Default value:

None

Sample Code

This example configures an inventory rule for bucket examplebucket.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from obs import ObsClient, InventoryDestination, InventoryFilter, InventoryConfiguration
import os
import traceback

# Obtain an AK/SK pair using environment variables (recommended) or import it in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables.
# security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 

# Create an obsClient instance.
# If you use a temporary AK/SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucketName = 'examplebucket'
    # ID of a bucket inventory rule
    inventory_id = 'example-id'
    # Target configuration of the inventory
    destination = InventoryDestination(
        bucket=bucketName,
        format='CSV',
        prefix='inventory_test/'
    )
    # Bucket inventory rule
    config = InventoryConfiguration(
        inventoryId=inventory_id,
        # Whether to enable the bucket inventory rule.
        isEnabled=True,
        # Whether to include the versions of objects in an inventory.
        objectVersion='All',
        # Inventory generation frequency
        frequency='Daily',
        destination=destination,
        # Inventory filter configuration. The inventory contains only objects that meet the filter criteria (filtering by object name prefix). If no filter criteria are configured, all objects are included.
        filter=InventoryFilter(prefix='test/')
    )
    # Configure an inventory rule for the bucket.
    resp = obsClient.putBucketInventory(bucketName, inventory_id, config)

    # If status code 2xx is returned, the API call succeeds. Otherwise, the API call fails.
    if resp.status < 300:
        print('Put Bucket Inventory Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Put Bucket Inventory Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except Exception:
    print('Put Bucket Inventory Failed')
    print(traceback.format_exc())