All Products
Search
Document Center

Object Storage Service:Lifecycle management (Python SDK V2)

Last Updated:Mar 20, 2026

Lifecycle rules let OSS automatically transition objects to lower-cost storage classes or delete them based on age or access patterns — no manual intervention required.

OSS supports two rule types:

  • Rules based on last modified time: Transition or delete objects that haven't been modified for a specified number of days. Use these rules to clean up stale data or archive infrequently updated files.

  • Rules based on last access time: OSS monitors access patterns and automatically moves cold data to a cheaper storage class. This implements Automatic Storage Tiering and reduces storage costs over time.

Prerequisites

Before you begin, ensure that you have:

The sample code in this topic uses the China (Hangzhou) region (cn-hangzhou) with a public endpoint. To access OSS from another Alibaba Cloud service in the same region, use an internal endpoint instead. For supported regions and endpoints, see OSS regions and endpoints.

Set lifecycle rules

All three examples below call client.put_bucket_lifecycle() to apply a LifecycleConfiguration to a bucket. Each example demonstrates a different filtering and transition scenario.

To update one or more existing rules, see How do I modify lifecycle rules?

Transition objects to IA storage based on last modified time

This example sets two rules on a bucket:

  • rule1: Transitions objects with the prefix foo/ and tag k1:v1 to Infrequent Access (IA) storage 30 days after last modification.

  • rule2: For objects with the prefix dir/ in a versioning-enabled bucket — automatically removes expired delete markers, transitions noncurrent versions to IA after 10 days, and permanently deletes noncurrent versions after 30 days.

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="put bucket lifecycle sample")
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')

def main():
    args = parser.parse_args()

    # Load credentials from environment variables
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.put_bucket_lifecycle(oss.PutBucketLifecycleRequest(
        bucket=args.bucket,
        lifecycle_configuration=oss.LifecycleConfiguration(
            rules=[
                oss.LifecycleRule(
                    id='rule1',
                    status='Enabled',
                    prefix='foo/',
                    transitions=[oss.LifecycleRuleTransition(
                        days=30,
                        storage_class=oss.StorageClassType.IA,
                        is_access_time=False,  # Policy based on last modified time
                    )],
                    tags=[oss.Tag(
                        key='k1',
                        value='v1',
                    )],
                ),
                oss.LifecycleRule(
                    id='rule2',
                    status='Enabled',
                    prefix='dir/',
                    expiration=oss.LifecycleRuleExpiration(
                        days=10,
                        expired_object_delete_marker=True,  # Remove delete markers when no other versions exist
                    ),
                    noncurrent_version_expiration=oss.NoncurrentVersionExpiration(
                        noncurrent_days=30,
                    ),
                    noncurrent_version_transition=oss.NoncurrentVersionTransition(
                        noncurrent_days=10,
                        storage_class=oss.StorageClassType.IA,
                        is_access_time=False,  # Policy based on last modified time
                    ),
                ),
            ]
        ),
    ))

    print(f'status code: {result.status_code}, request id: {result.request_id}')


if __name__ == "__main__":
    main()

Filter objects by size and exclude specific prefixes or tags

This example transitions objects with the prefix logs/ to Infrequent Access (IA) storage 30 days after last modification, but only if the object size is between 500 bytes and 1,000 bytes. Objects that also match the prefix logs/log with the tag key1:value1 are excluded.

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="put bucket lifecycle sample")
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')

def main():
    args = parser.parse_args()

    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.put_bucket_lifecycle(oss.PutBucketLifecycleRequest(
        bucket=args.bucket,
        lifecycle_configuration=oss.LifecycleConfiguration(
            rules=[
                oss.LifecycleRule(
                    id='rule1',
                    status='Enabled',
                    prefix='logs/',
                    transitions=[oss.LifecycleRuleTransition(
                        days=30,
                        storage_class=oss.StorageClassType.IA,
                        is_access_time=False,  # Policy based on last modified time
                    )],
                    filter=oss.LifecycleRuleFilter(
                        object_size_greater_than=500,   # Minimum object size in bytes
                        object_size_less_than=1000,     # Maximum object size in bytes
                        filter_not=[oss.LifecycleRuleNot(
                            prefix='logs/log',          # Exclude this prefix
                            tag={
                                'key': 'key1',
                                'value': 'value1',
                            },
                        )],
                    ),
                ),
            ]
        ),
    ))

    print(f'status code: {result.status_code}, request id: {result.request_id}')


if __name__ == "__main__":
    main()

Move cold data based on access patterns

This example sets two rules that transition objects based on last access time rather than last modified time. Both rules use is_access_time=True and return_to_std_when_visit=False.

  • rule1: Transitions objects with the prefix data/ to Infrequent Access (IA) after 200 days of inactivity.

  • rule2: Transitions objects with the prefix log/ to IA after 120 days of inactivity, then to Archive after 250 days.

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="put bucket lifecycle sample")
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')

def main():
    args = parser.parse_args()

    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.put_bucket_lifecycle(oss.PutBucketLifecycleRequest(
        bucket=args.bucket,
        lifecycle_configuration=oss.LifecycleConfiguration(
            rules=[
                oss.LifecycleRule(
                    id='rule1',
                    status='Enabled',
                    prefix='data/',
                    transitions=[oss.LifecycleRuleTransition(
                        days=200,
                        storage_class=oss.StorageClassType.IA,
                        is_access_time=True,               # Policy based on last access time
                        return_to_std_when_visit=False,    # Stay in IA when accessed again
                    )],
                ),
                oss.LifecycleRule(
                    id='rule2',
                    status='Enabled',
                    prefix='log/',
                    transitions=[
                        oss.LifecycleRuleTransition(
                            days=120,
                            storage_class=oss.StorageClassType.IA,
                            is_access_time=True,
                            return_to_std_when_visit=False,
                        ),
                        oss.LifecycleRuleTransition(
                            days=250,
                            storage_class=oss.StorageClassType.ARCHIVE,
                            is_access_time=True,
                            return_to_std_when_visit=False,
                        ),
                    ],
                ),
            ]
        ),
    ))

    print(f'status code: {result.status_code}, request id: {result.request_id}')


if __name__ == "__main__":
    main()

View lifecycle rules

Use client.get_bucket_lifecycle() to retrieve all lifecycle rules configured for a bucket. The result contains a lifecycle_configuration.rules list with the full rule definitions.

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="get bucket lifecycle sample")
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')

def main():
    args = parser.parse_args()

    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.get_bucket_lifecycle(
        oss.GetBucketLifecycleRequest(
            bucket=args.bucket,
        )
    )

    print(f'status code: {result.status_code}, request id: {result.request_id}')

    if result.lifecycle_configuration.rules:
        for r in result.lifecycle_configuration.rules:
            print(f'rule: {r}')


if __name__ == "__main__":
    main()

Delete all lifecycle rules

client.delete_bucket_lifecycle() removes all lifecycle rules from a bucket. To delete individual rules instead, see How do I delete specific lifecycle rules?

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="delete bucket lifecycle sample")
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')

def main():
    args = parser.parse_args()

    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    result = client.delete_bucket_lifecycle(
        oss.DeleteBucketLifecycleRequest(
            bucket=args.bucket,
        )
    )

    print(f'status code: {result.status_code}, request id: {result.request_id}')


if __name__ == "__main__":
    main()

References