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:

// The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 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.
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";

// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// Create a request by using SetBucketLifecycleRequest.
SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);

// Specify the rule IDs and the object prefixes and tags to match the rules.
String ruleId0 = "rule0";
String matchPrefix0 = "A0/";
Map<String, String> matchTags0 = new HashMap<String, String>();
matchTags0.put("key0", "value0");


String ruleId1 = "rule1";
String matchPrefix1 = "A1/";
Map<String, String> matchTags1 = new HashMap<String, String>();
matchTags1.put("key1", "value1");

String ruleId2 = "rule2";
String matchPrefix2 = "A2/";

String ruleId3 = "rule3";
String matchPrefix3 = "A3/";

String ruleId4 = "rule4";
String matchPrefix4 = "A4/";

String ruleId5 = "rule5";
String matchPrefix5 = "A5/";

String ruleId6 = "rule6";
String matchPrefix6 = "A6/";

// Specify that objects expire three days after they are last modified.
LifecycleRule rule = new LifecycleRule(ruleId0, matchPrefix0, LifecycleRule.RuleStatus.Enabled, 3);
rule.setTags(matchTags0);
request.AddLifecycleRule(rule);

// Specify that the objects last modified before the specified date expire.
rule = new LifecycleRule(ruleId1, matchPrefix1, LifecycleRule.RuleStatus.Enabled);
rule.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
rule.setTags(matchTags1);
request.AddLifecycleRule(rule);

// Specify that parts expire three days after they are last modified.
rule = new LifecycleRule(ruleId2, matchPrefix2, LifecycleRule.RuleStatus.Enabled);
LifecycleRule.AbortMultipartUpload abortMultipartUpload = new LifecycleRule.AbortMultipartUpload();
abortMultipartUpload.setExpirationDays(3);
rule.setAbortMultipartUpload(abortMultipartUpload);
request.AddLifecycleRule(rule);

// Specify that the parts last modified before the specified date expire.
rule = new LifecycleRule(ruleId3, matchPrefix3, LifecycleRule.RuleStatus.Enabled);
abortMultipartUpload = new LifecycleRule.AbortMultipartUpload();
abortMultipartUpload.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
rule.setAbortMultipartUpload(abortMultipartUpload);
request.AddLifecycleRule(rule);

// Specify that the storage class of objects is converted to IA 10 days after they are last modified, and to Archive 30 days after they are last modified.
rule = new LifecycleRule(ruleId4, matchPrefix4, LifecycleRule.RuleStatus.Enabled);
List<StorageTransition> storageTransitions = new ArrayList<StorageTransition>();
StorageTransition storageTransition = new StorageTransition();
storageTransition.setStorageClass(StorageClass.IA);
storageTransition.setExpirationDays(10);
storageTransitions.add(storageTransition);
storageTransition = new StorageTransition();
storageTransition.setStorageClass(StorageClass.Archive);
storageTransition.setExpirationDays(30);
storageTransitions.add(storageTransition);
rule.setStorageTransition(storageTransitions);
request.AddLifecycleRule(rule);

// Specify that the storage class of objects that are last modified before October 12, 2022 is converted to Archive.
rule = new LifecycleRule(ruleId5, matchPrefix5, LifecycleRule.RuleStatus.Enabled);
storageTransitions = new ArrayList<StorageTransition>();
storageTransition = new StorageTransition();
storageTransition.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
storageTransition.setStorageClass(StorageClass.Archive);
storageTransitions.add(storageTransition);
rule.setStorageTransition(storageTransitions);
request.AddLifecycleRule(rule);

// Create rule6 for versioned buckets.
rule = new LifecycleRule(ruleId6, matchPrefix6, LifecycleRule.RuleStatus.Enabled);
// Specify that the storage class of objects is converted to Archive 365 days after they are last modified.
storageTransitions = new ArrayList<StorageTransition>();
storageTransition = new StorageTransition();
storageTransition.setStorageClass(StorageClass.Archive);
storageTransition.setExpirationDays(365);
storageTransitions.add(storageTransition);
rule.setStorageTransition(storageTransitions);
// Specify that delete markers are automatically removed when they expire.
rule.setExpiredDeleteMarker(true);
// Specify that the storage class of objects is converted to IA 10 days after they become previous versions.
NoncurrentVersionStorageTransition noncurrentVersionStorageTransition =
        new NoncurrentVersionStorageTransition().withNoncurrentDays(10).withStrorageClass(StorageClass.IA);
// Specify that the storage class of objects is converted to Archive 20 days after they become previous versions.
NoncurrentVersionStorageTransition noncurrentVersionStorageTransition2 =
        new NoncurrentVersionStorageTransition().withNoncurrentDays(20).withStrorageClass(StorageClass.Archive);
// Specify that objects are deleted when they expire 30 days after they become previous versions.
NoncurrentVersionExpiration noncurrentVersionExpiration = new NoncurrentVersionExpiration().withNoncurrentDays(30);
List<NoncurrentVersionStorageTransition> noncurrentVersionStorageTransitions = new ArrayList<NoncurrentVersionStorageTransition>();
noncurrentVersionStorageTransitions.add(noncurrentVersionStorageTransition2);
rule.setStorageTransition(storageTransitions);
rule.setNoncurrentVersionExpiration(noncurrentVersionExpiration);
rule.setNoncurrentVersionStorageTransitions(noncurrentVersionStorageTransitions);
request.AddLifecycleRule(rule);

// Initiate the request to configure lifecycle rules.
ossClient.setBucketLifecycle(request);

// Shut down the OSSClient instance.
ossClient.shutdown();

View lifecycle rules

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

// The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 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.
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";

// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// Query the lifecycle rules.
List<LifecycleRule> rules = ossClient.getBucketLifecycle(bucketName);

// View the lifecycle rules.
for (LifecycleRule r : rules) {
    System.out.println("================");

    // View the rule IDs.
    System.out.println("rule id: " + r.getId());

    // View the status of the rules.
    System.out.println("rule status: " + r.getStatus());

    // View the prefixes configured in the lifecycle rules.
    System.out.println("rule prefix: " + r.getPrefix());

    // View the tags configured in the lifecycle rules.
    if (r.hasTags()) {
        System.out.println("rule tagging: "+ r.getTags().toString());
    }

    // View the validity period configurations.
    if (r.hasExpirationDays()) {
        System.out.println("rule expiration days: " + r.getExpirationDays());
    }

    // View the expiration date configurations.
    if (r.hasCreatedBeforeDate()) {
        System.out.println("rule expiration create before days: " + r.getCreatedBeforeDate());
    }

    // View the configurations used to delete expired parts.
    if(r.hasAbortMultipartUpload()) {
        if(r.getAbortMultipartUpload().hasExpirationDays()) {
            System.out.println("rule abort uppart days: " + r.getAbortMultipartUpload().getExpirationDays());
        }

        if (r.getAbortMultipartUpload().hasCreatedBeforeDate()) {
            System.out.println("rule abort uppart create before date: " + r.getAbortMultipartUpload().getCreatedBeforeDate());
        }
    }

    // View the configurations used to convert storage classes.
    if (r.getStorageTransition().size() > 0) {
        for (StorageTransition transition : r.getStorageTransition()) {
            if (transition.hasExpirationDays()) {
                System.out.println("rule storage trans days: " + transition.getExpirationDays() +
                        " trans storage class: " + transition.getStorageClass());
            }

            if (transition.hasCreatedBeforeDate()) {
                System.out.println("rule storage trans before create date: " + transition.getCreatedBeforeDate());
            }
        }
    }

    // View the configurations used to remove delete markers.
    if (r.hasExpiredDeleteMarker()) {
        System.out.println("rule expired delete marker: " + r.getExpiredDeleteMarker());
    }

    // View the configurations used to convert the previous versions of objects.
    if (r.hasNoncurrentVersionStorageTransitions()) {
        for (NoncurrentVersionStorageTransition transition : r.getNoncurrentVersionStorageTransitions()) {
            System.out.println("rule noncurrent versions trans days:" + transition.getNoncurrentDays() +
                    " trans storage class: " + transition.getStorageClass());
        }
    }

    // View the expiration configurations for the previous versions of the objects.
    if (r.hasNoncurrentVersionExpiration()) {
        System.out.println("rule noncurrent versions expiration days:" + r.getNoncurrentVersionExpiration().getNoncurrentDays());
    }
}

// Shut down the OSSClient instance.
ossClient.shutdown();

Delete lifecycle rules

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

// The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 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.
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";

// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

ossClient.deleteBucketLifecycle(bucketName);

// Shut down the OSSClient instance.
ossClient.shutdown();