All Products
Search
Document Center

Object Storage Service:Bucket inventory (Python SDK V2)

Last Updated:Aug 01, 2025

This topic describes how to create an inventory for a bucket and how to query, list, and delete the inventories of a bucket using Object Storage Service (OSS) SDK for Python.

Notes

  • The sample code in this topic uses the region ID cn-hangzhou of the China (Hangzhou) region as an example. By default, a public endpoint is used. If you want to access OSS from other Alibaba Cloud products in the same region, use an internal endpoint. For more information about the mappings between OSS regions and endpoints, see Regions and endpoints.

  • Make sure that you have the permissions to create, query, list, and delete bucket inventories. By default, the bucket owner has the permissions to perform the preceding operations. If you do not have the permissions to perform the preceding operations, contact the bucket owner to grant you the permissions.

  • You can configure up to 1,000 inventories for a bucket.

  • The source bucket for which you want to configure an inventory must be located in the same region as the destination bucket in which you want to store inventory lists.

Examples

Add checklist configuration

The following sample code provides an example on how to create an inventory for a bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to create an inventory for a bucket.
parser = argparse.ArgumentParser(description="put bucket inventory sample")

# Specify the command line parameters, including the required region, bucket name, endpoint, user ID, Alibaba Cloud Resource Name (ARN) of the RAM role, and inventory name.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--user_id', help='User account ID.', required=True)
parser.add_argument('--arn', help='The Alibaba Cloud Resource Name (ARN) of the role that has the permissions to read all objects from the source bucket and write objects to the destination bucket. Format: `acs:ram::uid:role/rolename`.', required=True)
parser.add_argument('--inventory_id', help='The name of the inventory.', required=True)

def main():
    # Parse the command line parameters to obtain the values specified by the user.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters specified by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to create an inventory for a bucket.
    result = client.put_bucket_inventory(oss.PutBucketInventoryRequest(
            bucket=args.bucket, # The name of the bucket.
            inventory_id=args.inventory_id, # The ID of the inventory.
            inventory_configuration=oss.InventoryConfiguration(
                included_object_versions='All', # Specify that inventory lists include all versions of objects.
                optional_fields=oss.OptionalFields(
                    fields=[ # The optional fields, such as the size and last modified time of objects.
                        oss.InventoryOptionalFieldType.SIZE,
                        oss.InventoryOptionalFieldType.LAST_MODIFIED_DATE,
                    ],
                ),
                id=args.inventory_id, # The ID of the inventory.
                is_enabled=True, # Specify whether to enable the inventory feature for the bucket. In this example, the inventory feature is enabled.
                destination=oss.InventoryDestination(
                    oss_bucket_destination=oss.InventoryOSSBucketDestination(
                        format=oss. InventoryFormatType.CSV, # Specify that the output format of the inventory lists is CSV.
                        account_id=args.user_id, # The account ID of the user.
                        role_arn=args.arn, # The ARN of the RAM role, which has the permissions to read the objects in the source bucket and write objects to the destination bucket.
                        bucket=f'acs:oss:::{args.bucket}', # The name of the destination bucket.
                        prefix='aaa', # Specify the prefix contained in the names of the objects that you want to include in inventory lists.
                    ),
                ),
                schedule=oss.InventorySchedule(
                    frequency=oss. InventoryFrequencyType.DAILY, # Specify whether to generate inventory lists on a daily or weekly basis. In this example, inventory lists are generated on a daily basis.
                ),
                filter=oss.InventoryFilter(
                    lower_size_bound=1024, # Specify the minimum size of the object that you want to include in inventory lists. Unit: bytes.
                    upper_size_bound=1048576, # Specify the maximum size of the object that you want to include in inventory lists. Unit: bytes.
                    storage_class='ColdArchive', # # Specify the storage classes of objects that you want to include in inventory lists.
                    prefix='aaa', # Specify the prefix that is used to filter inventories.
                    last_modify_begin_time_stamp=1637883649, # Specify the beginning of the time range during which the object was last modified.
                    last_modify_end_time_stamp=1638347592, # Specify the end of the time range during which the object was last modified.
                ),
            ),
    ))

    # Display the HTTP status code of the operation and request ID to check the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
    )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.

Query an inventory of a bucket

The following sample code provides an example on how to query an inventory of a bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to query the inventory of a bucket.
parser = argparse.ArgumentParser(description="get bucket inventory sample")

# Specify the command line parameters, including the required region, bucket name, endpoint, and inventory ID.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--inventory_id', help='The name of the inventory.', required=True)

def main():
    # Parse the command line parameters to obtain the values specified by the user.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters specified by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to query the inventory of the bucket.
    result = client.get_bucket_inventory(oss.GetBucketInventoryRequest(
            bucket=args.bucket, # The name of the bucket.
            inventory_id=args.inventory_id, # The ID of the inventory.
    ))

    # Display the HTTP status code of the operation and request ID to check the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' included object versions: {result.inventory_configuration.included_object_versions},'
          f' id: {result.inventory_configuration.id},'
          f' is enabled: {result.inventory_configuration.is_enabled},'
          f' account id: {result.inventory_configuration.destination.oss_bucket_destination.account_id},'
          f' role arn: {result.inventory_configuration.destination.oss_bucket_destination.role_arn},'
          f' bucket: {result.inventory_configuration.destination.oss_bucket_destination.bucket},'
          f' prefix: {result.inventory_configuration.destination.oss_bucket_destination.prefix},'
          # The following two command lines describe information about the encryption configurations. You can delete them if you do not need them.
          # f' key id: {result.inventory_configuration.destination.oss_bucket_destination.encryption.sse_kms.key_id},'
          # f' sse oss: {result.inventory_configuration.destination.oss_bucket_destination.encryption.sse_oss},'
          f' lower size bound: {result.inventory_configuration.filter.lower_size_bound},'
          f' upper size bound: {result.inventory_configuration.filter.upper_size_bound},'
          f' storage class: {result.inventory_configuration.filter.storage_class},'
          f' prefix: {result.inventory_configuration.filter.prefix},'
          f' last modify begin time stamp: {result.inventory_configuration.filter.last_modify_begin_time_stamp},'
          f' last modify end time stamp: {result.inventory_configuration.filter.last_modify_end_time_stamp},'
    )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.

List the inventories of a bucket

Note

You can query up to 100 inventories by sending a request. If you want to query more than 100 inventories, send multiple requests and use the token returned for each request as a parameter for the next request.

The following sample code provides an example on how to list the inventories of a bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to list the inventories of a bucket.
parser = argparse.ArgumentParser(description="list bucket inventory sample")

# Optional. Specify the command line parameters, including the required region, bucket name, endpoint, and inventory ID.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--inventory_id', help='The name of the inventory.', required=False) # The inventory ID is optional in this scenario.

def main():
    # Parse the command line parameters to obtain the values specified by the user.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters specified by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to list the inventories of the bucket.
    result = client.list_bucket_inventory(oss.ListBucketInventoryRequest(
            bucket=args.bucket, # The name of the bucket.
    ))

    # Display the HTTP status code of the operation and request ID to check the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' list inventory configurations result: {result.list_inventory_configurations_result},'
          f' is truncated: {result.list_inventory_configurations_result.is_truncated},'
          f' next continuation token: {result.list_inventory_configurations_result.next_continuation_token},'
    )

    # If inventories exist, traverse and display the details of each inventory.
    if result.list_inventory_configurations_result.inventory_configurations:
        for r in result.list_inventory_configurations_result.inventory_configurations:
            print(f'result: '
                  f'included object versions: {r.included_object_versions}, '
                  f'optional fields: {r.optional_fields}, '
                  f'id: {r.id}, '
                  f'is enabled: {r.is_enabled}, '
                  f'destination: {r.destination}, '
                  f'schedule: {r.schedule}, '
                  f'filter: {r.filter}'
            )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.

Delete an inventory of a bucket

The following sample code provides an example on how to delete an inventory of a bucket:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser and describe the purpose of the script. The example describes how to delete an inventory of a bucket.
parser = argparse.ArgumentParser(description="delete bucket inventory sample")

# Specify the command line parameters, including the required region, bucket name, endpoint, and inventory ID.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--inventory_id', help='The name of the inventory.', required=True)

def main():
    # Parse the command line parameters to obtain the values specified by the user.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region attribute of the configuration object based on the command line parameters specified by the user.
    cfg.region = args.region

    # If a custom endpoint is provided, modify the endpoint parameter in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSSClient instance and allow the instance to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to delete an inventory of a bucket.
    result = client.delete_bucket_inventory(oss.DeleteBucketInventoryRequest(
            bucket=args.bucket, # The name of the bucket.
            inventory_id=args.inventory_id, # The ID of the inventory.
    ))

    # Display the HTTP status code of the operation and request ID to check the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
    )

# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main() # Specify the entry points in the functions of the script. The control program flow starts here.