This topic describes how to manage lifecycle rules.

You can configure lifecycle rules for OSS buckets to reduce storage costs. The lifecycle rule allows OSS to automatically delete expired objects or parts of an object. It also converts the storage class of expired objects to IA or Archive. A lifecycle rule includes the following fields:
  • Rule ID. It identifies a rule. Ensure that each rule ID in a bucket is unique.
  • Policy. You can configure a policy by using the following configuration methods. Only one method can be configured for a bucket.
    • Configure by Prefix: You can create multiple rules by using this method. Ensure that each prefix is unique.
    • Configure for the entire bucket: You can configure only one rule by using this method.
  • Expiration. You can configure the time when an object expires in the following methods:
    • Configure by number of days: specifies a number of days. Objects expire the specified days after they are last modified.
    • Configure by date: specifies a date. Objects expire if they are last modified before the specified date.
  • Whether this rule takes effect.

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

For more information about lifecycle rules, see Manage object lifecycle.

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 https://ram.console.aliyun.com.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint based on your requirements.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')

# Set the expiration time to three days after the last modification date.
rule1 = LifecycleRule('rule1', 'tests/',
                      status=LifecycleRule.ENABLED,
                      expiration=LifecycleExpiration(days=3))

# Set the expiration date to delete objects that are created before the specified date.
rule2 = LifecycleRule('rule2', 'tests2/',
                      status=LifecycleRule.ENABLED,
expiration=LifecycleExpiration(created_before_date=datetime.date(2018, 12, 12)))

# Set the expiration time to three days for parts of an object.
rule3 = LifecycleRule('rule3', 'tests3/',
                      status=LifecycleRule.ENABLED,
            abort_multipart_upload=AbortMultipartUpload(days=3))

# Set the expiration date to delete parts that are created before the specified date.
rule4 = LifecycleRule('rule4', 'tests4/',
                      status=LifecycleRule.ENABLED,
                      abort_multipart_upload = AbortMultipartUpload(created_before_date=datetime.date(2018, 12, 12)))

# Configure the lifecycle rule. This rule converts the storage class of an object to IA after 20 days from the last modification date. The rule also coverts the storage class to Archive after 30 days from the last modification date.
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)])

# Set tags as the matching condition.
tagging_rule = TaggingRule()
tagging_rule.add('key1', 'value1')
tagging_rule.add('key2', 'value2')
tagging = Tagging(tagging_rule)

# Configure the rule to convert the storage class of an object to Archive 365 days after the object is last modified. 
# rule6 specifies a matching tag unlike the preceding rules. Only objects that have the two tags key1=value1 and key2=value2 match this rule.
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)

# rule7 is configured for versioning-enabled buckets.
# Configure the rule to convert the storage class of an object to Archive 365 days after the object is last modified.
# Configure the lifecycle rule to delete expired delete markers automatically.
# Configure the lifecycle rule to convert a historical version of the object to the IA storage class 12 days after the object is last modified.
# Configure the lifecycle rule to convert a historical version of the object to the Archive storage class 20 days after the object is last modified.
# Configure the lifecycle rule to delete a historical version of the object 30 days after it become a historical version.
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 lifecycle rules:

# -*- 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 https://ram.console.aliyun.com.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint based on your requirements.
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:
            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)

Clear lifecycle rules

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

# -*- 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 https://ram.console.aliyun.com.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint based on your requirements.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')

# Clear the lifecycle rules configured for the bucket.
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')