Manage lifecycle rules

Last Updated: Sep 30, 2017

You can set lifecycle rules for your buckets to manage objects in the buckets. Currently, you can define rules to delete specific objects. Each rule is composed of the following parts:

  • Rule ID: ID that identifies a rule. The rule IDs cannot be repeated.
  • Object name prefix: The rule only applies to the objects whose names contain the specified prefix. No overlapped content is allowed in prefixes. For example, prefixes such as ‘/home’ and ‘/home/user’ are invalid because the former is the prefix of the latter.
  • Operation: The operation that you want to perform on the matched objects.
  • Expiration days: It specifies after how many days since the last modification will the object be deleted.
  • Take effect or not

For more documentation, see Developer Guide and API Reference.

Note: Because user data may be deleted according to the lifecycle rules, you must carefully read related documentation, and apply the lifecycle rules to production buckets only after the rules have been verified in testing buckets.

Set lifecycle rules

The following code sets two lifecycle rules:

  • Rule 1: The rule ID is rule1, the prefix is tests/, the status is Enabled, and the vadility period is 356 days.
  • Rule 2: The rule ID is rule2, the prefix is logging-, the status is Disabled and the vadility period is 1 day.
  1. # -*- coding: utf-8 -*-
  2. import oss2
  3. from oss2.models import LifecycleExpiration, LifecycleRule, BucketLifecycle
  4. auth = oss2.Auth ('Your AccessKeyID', 'Your AccessKeySecret')
  5. bucket = oss2.Bucket (auth, 'Your endpoint', 'your bucket name')
  6. rule1 = LifecycleRule('rule1', 'tests/',
  7. status=LifecycleRule.ENABLED,
  8. expiration=LifecycleExpiration(days=356))
  9. rule2 = LifecycleRule('rule2', 'logging-',
  10. status=LifecycleRule.DISABLED,
  11. expiration=LifecycleExpiration(days=1))
  12. bucket.put_bucket_lifecycle(BucketLifecycle([rule1, rule2]))

Get lifecycle rules

  1. lifecycle = bucket.get_bucket_lifecycle()
  2. for rule in lifecycle.rules:
  3. print('id={0}, prefix={1}, status={2}, days={3}, date={4}'
  4. .format(rule.id, rule.prefix, rule.status, rule.expiration.days, rule.expiration.date))

Delete lifecycle rules

You can delete all lifecycle rules of a bucket to disable the lifecycle feature:

  1. bucket.delete_bucket_lifecycle()
  2. # An exception is thrown when you try to get the lifecycle rules again
  3. try:
  4. lifecycle = bucket.get_bucket_lifecycle()
  5. except oss2.exceptions.NoSuchLifecycle:
  6. print('lifecycle is not configured')
Thank you! We've received your feedback.