OSS allows you to configure lifecycle rules to delete expired objects and parts or convert the storage class of expired objects to IA or Archive. This way, storage costs are minimized. This topic describes how to manage lifecycle rules.

Background information

Each lifecycle rule contains the following information:

  • Policy: specifies the mode to match objects and parts.
    • Match by prefix: matches objects and parts by prefix. You can create multiple rules to configure different prefixes. Each prefix must be unique.
    • Match by tag: matches objects by tag key and tag value. You can configure multiple tags for a single rule. OSS runs lifecycle rules for all objects that have these tags. Tags cannot be configured for parts to match lifecycle rules.
      Note For more information, see 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 the bucket. If you select this method, only a single rule can be created.
  • Object lifecycle policy: specifies the validity period or expiration date and the operation to perform on these objects when they expire.
    • Validity period: specifies the number of days for unversioned and current objects and the operation to perform on these objects. Objects that meet the specified conditions are retained for the specified period of time after the objects are last modified. The specified operation is performed on these objects when they expire.
    • Expiration date: specifies a date for unversioned and current objects and the operation to perform on these objects. 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 number of days for the previous versions of objects and the operation to perform on these objects. Objects that meet the specified conditions are retained for the specified period of time after the objects become previous versions. The specified operation is performed on these objects when they expire.
    Note You can specify that the storage class of objects is converted to IA or Archive, or delete the objects when they expire. For more information, see Configuration elements.
  • Part lifecycle policy: specifies the validity period or expiration date and the operation to perform on these parts when they expire.
    • Validity period: specifies the number of days for which to retain parts after they are last modified and the delete operation to perform on these parts when they expire.
    • Expiration date: specifies a date based on which to delete parts. Parts that are last modified before this date expire.

You can also configure lifecycle rules for parts that are uploaded to a bucket using uploadPart. The last modification time uses the time the multipart upload task is initiated.

For more information, see Manage object lifecycles.

Configure lifecycle rules

The following code provides an example on how to configure lifecycle rules:

# -*- 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 log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')

# 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(2018, 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(2018, 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(2018, 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 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 when they expire 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)

View lifecycle rules

The following code provides an example on how to view the lifecycle rules configured for a bucket:

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

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')

# View 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 delete the lifecycle rules configured for a bucket:

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

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')

# Delete lifecycle rules.
bucket.delete_bucket_lifecycle()

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