Object Storage Service (OSS) allows you to configure lifecycle rules to delete expired objects and parts or convert the storage class of expired objects to Infrequent Access (IA) or Archive. This way, storage costs are minimized. This topic describes how to manage lifecycle rules for buckets.

Background information

Each lifecycle rule contains the following information:

  • The match policy of prefixes or tags: specifies the objects and parts that match the rule.
    • Match by prefix: specifies that the rule matches objects and parts by prefix. You can create multiple rules to match objects whose names contain different prefixes. You can only configure a lifecycle rule for each prefix.
    • Match by tag: matches objects by tag key and tag value. You can specify multiple tags in a single lifecycle rule. The lifecycle rule applies to all objects that have the specified tags. Lifecycle rules cannot be configured for parts to match tags.
      Note For more information about object tags, see Configure object tagging.
    • Match by prefix and tag: matches objects by specifying a prefix and one or more tags.
    • Match by bucket: matches all objects and parts contained in a bucket. In this case, you can create only one lifecycle rule for the bucket.
  • Object lifecycle policy: specifies the validity period or the expiration date of objects and the operation to perform on the expired objects.
    • Validity period: specifies the validity period of all objects in unversioned buckets and the current versions of objects in versioned buckets and the operation to perform on these objects after they expire. Objects that match the lifecycle rule are retained for the specified validity period after the objects are last modified. The specified operation is performed on these objects after they expire.
    • Expiration date: specifies the expiration date of all objects in unversioned buckets and the current versions of objects in versioned buckets and the operation to perform on these objects after they expire. All objects that are last modified before this date expire, and the specified operation is performed on these objects.
    • Validity period for the previous versions of objects: specifies the validity period for the previous versions of objects and the operation to perform on these previous versions. Objects that match the lifecycle rule are retained for the specified validity period after the objects become previous versions. The specified operation is performed on these objects after they expire.
    Note You can specify that the storage class of expired objects is converted to IA or Archive, or delete the expired objects. For more information, see Configuration elements.
  • Part lifecycle policy: specifies the validity period or the expiration date of parts and the operation to perform after the parts expire.
    • Validity period: specifies the validity period for parts. Parts that match the lifecycle rule are retained within the validity period and are deleted after they expire.
    • Expiration date: specifies the expiration date of parts. Parts that are last modified before this date expire and are deleted.

Lifecycle rules also apply to the parts uploaded by using uploadPart. In this case, the last modified time of an object is the time the multipart upload task is initiated.

For more information about lifecycle rules, see Lifecycle rules.

Configure lifecycle rules

The following code provides an example on how to configure lifecycle rules for a bucket named examplebucket:

# -*- coding: utf-8 -*-
import oss2
import datetime
from oss2.models import (LifecycleExpiration, LifecycleRule, 
                        BucketLifecycle,AbortMultipartUpload, 
                        TaggingRule, Tagging, StorageTransition,
                        NoncurrentVersionStorageTransition,
                        NoncurrentVersionExpiration)

# 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')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
# Specify yourBucketName as the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# Specify that objects expire three days after they are last modified. 
rule1 = LifecycleRule('rule1', 'tests/',
                      status=LifecycleRule.ENABLED,
                      expiration=LifecycleExpiration(days=3))

# Specify that the objects last modified before the specified date expire. 
rule2 = LifecycleRule('rule2', 'tests2/',
                      status=LifecycleRule.ENABLED,
expiration=LifecycleExpiration(created_before_date=datetime.date(2022, 12, 12)))

# Specify that parts expire three days after they are last modified. 
rule3 = LifecycleRule('rule3', 'tests3/',
                      status=LifecycleRule.ENABLED,
            abort_multipart_upload=AbortMultipartUpload(days=3))

# Specify that the parts last modified before the specified date expire. 
rule4 = LifecycleRule('rule4', 'tests4/',
                      status=LifecycleRule.ENABLED,
                      abort_multipart_upload = AbortMultipartUpload(created_before_date=datetime.date(2022, 12, 12)))

# Specify that the storage class of objects is converted to IA 20 days after they are last modified, and to Archive 30 days after they are last modified. 
rule5 = LifecycleRule('rule5', 'tests5/',
                      status=LifecycleRule.ENABLED,
                      storage_transitions=[StorageTransition(days=20,storage_class=oss2.BUCKET_STORAGE_CLASS_IA),
                            StorageTransition(days=30,storage_class=oss2.BUCKET_STORAGE_CLASS_ARCHIVE)])

# Specify the tags to match the rules. 
tagging_rule = TaggingRule()
tagging_rule.add('key1', 'value1')
tagging_rule.add('key2', 'value2')
tagging = Tagging(tagging_rule)

# Specify that the storage class of objects is converted to Archive 365 days after they are last modified.  
# Compared with the preceding rules, rule6 specifies tags to match. The rule applies to objects whose tagging configurations are key1=value1 and key2=value2. 
rule6 = LifecycleRule('rule6', 'tests6/',
                      status=LifecycleRule.ENABLED,
                      storage_transitions=[StorageTransition(created_before_date=datetime.date(2022, 12, 12),storage_class=oss2.BUCKET_STORAGE_CLASS_IA)],
                      tagging = tagging)

# Create rule7 for a versioned bucket. 
# Specify that the storage class of objects is converted to Archive 365 days after they are last modified. 
# Specify that delete markers are automatically removed when they expire. 
# Specify that the storage class of objects is converted to Infrequent Access (IA) 12 days after they become previous versions. 
# Specify that the storage class of objects is converted to Archive 20 days after they become previous versions. 
# Specify that objects are deleted 30 days after they become previous versions. 
rule7 = LifecycleRule('rule7', 'tests7/',
              status=LifecycleRule.ENABLED,
              storage_transitions=[StorageTransition(days=365, storage_class=oss2.BUCKET_STORAGE_CLASS_ARCHIVE)], 
              expiration=LifecycleExpiration(expired_detete_marker=True),
              noncurrent_version_sotrage_transitions = 
                    [NoncurrentVersionStorageTransition(12, oss2.BUCKET_STORAGE_CLASS_IA),
                     NoncurrentVersionStorageTransition(20, oss2.BUCKET_STORAGE_CLASS_ARCHIVE)],
              noncurrent_version_expiration = NoncurrentVersionExpiration(30))

lifecycle = BucketLifecycle([rule1, rule2, rule3, rule4, rule5, rule6, rule7])

bucket.put_bucket_lifecycle(lifecycle)

Query lifecycle rules

The following code provides an example on how to query the lifecycle rules configured for the bucket named examplebucket:

# -*- coding: utf-8 -*-
import oss2
# 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')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
# Specify yourBucketName as the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# Query the lifecycle rules. 
lifecycle = bucket.get_bucket_lifecycle()

for rule in lifecycle.rules:
    print('==========')
    print('id:', rule.id)
    print('prefix:', rule.prefix)
    print('status', rule.status)

    if rule.tagging is not None:
        print('tagging:', rule.tagging)

    if rule.abort_multipart_upload is not None:
        if rule.abort_multipart_upload.days is not None:
            print('abort_multipart_upload days:', rule.abort_multipart_upload.days)
        else:
            print('abort_multipart_upload created_before_date:', rule.abort_multipart_upload.created_before_date)

    if rule.expiration is not None:
        if rule.expiration.days is not None:
            print('expiration days:', rule.expiration.days)
        elif rule.expiration.expired_detete_marker is not None:
            print('expiration expired_detete_marker:', rule.expiration.expired_detete_marker)
        elif rule.expiration.created_before_date is not None:
            print('expiration created_before_date:', rule.expiration.created_before_date)

    if len(rule.storage_transitions) > 0: 
        storage_info = ''
        for storage_rule in rule.storage_transitions:
            if storage_rule.days is not None:
                storage_info += 'days={0}, storage_class={1} *** '.format(
                        storage_rule.days, storage_rule.storage_class)
            else:
                storage_info += 'created_before_date={0}, storage_class={1} *** '.format(
                        storage_rule.created_before_date, storage_rule.storage_class) 
        print('storage_transitions:', storage_info)

    if len(rule.noncurrent_version_sotrage_transitions) > 0:
        noncurrent_storage_info = ''
        for storage_rule in rule.noncurrent_version_sotrage_transitions:
            noncurrent_storage_info += 'days={0}, storage_class={1} *** '.format(
                storage_rule.noncurrent_days, storage_rule.storage_class)
        print('noncurrent_version_sotrage_transitions:', noncurrent_storage_info)

    if rule.noncurrent_version_expiration is not None:
        print('noncurrent_version_expiration days:', rule.noncurrent_version_expiration.noncurrent_days)

Delete lifecycle rules

The following code provides an example on how to clear lifecycle rules of a bucket named examplebucket:

# -*- coding: utf-8 -*-
import oss2

# 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')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
# Specify yourBucketName as the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')

# Delete lifecycle rules. 
bucket.delete_bucket_lifecycle()

# An exception occurs when you query lifecycle rules again. 
try:
    lifecycle = bucket.get_bucket_lifecycle()
except oss2.exceptions.NoSuchLifecycle:
    print('lifecycle is not configured')