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

  • Configure a lifecycle rule and match by prefix and tag

    The following code provides an example on how to configure a lifecycle rule and match by prefix and tag for a bucket named examplebucket:

    OSS ossClient = null;
    try {
        // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
        String endpoint = "yourEndpoint";
        // 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 Resource Access Management (RAM) user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket for which you want to configure a lifecycle rule. Example: examplebucket. 
        String bucketName = "examplebucket";
    
        // Create an OSSClient instance. 
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
        // Create a request by using SetBucketLifecycleRequest. 
        SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);
    
        // Specify the ID for the lifecycle rule. 
        String ruleId0 = "rule0";
        // Specify the prefix that you want the lifecycle rule to match. 
        String matchPrefix0 = "A0/";
        // Specify the tag that you want the lifecycle rule to match. 
        Map<String, String> matchTags0 = new HashMap<String, String>();
        // Specify the key and value of the object tag. Example: the key is owner, and the value is John. 
        matchTags0.put("owner", "John");
    
    
        String ruleId1 = "rule1";
        String matchPrefix1 = "A1/";
        Map<String, String> matchTags1 = new HashMap<String, String>();
        matchTags1.put("type", "document");
    
        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/";
    
        // Set the expiration time to three days after the last modified time. 
        LifecycleRule rule = new LifecycleRule(ruleId0, matchPrefix0, LifecycleRule.RuleStatus.Enabled, 3);
        rule.setTags(matchTags0);
        request.AddLifecycleRule(rule);
    
        // Specify that objects that are created before the expiration 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);
    
        // Set the expiration time to three days for parts of an object. 
        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 parts that are created before the expiration 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<LifecycleRule.StorageTransition> storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
        LifecycleRule.StorageTransition storageTransition = new LifecycleRule.StorageTransition();
        storageTransition.setStorageClass(StorageClass.IA);
        storageTransition.setExpirationDays(10);
        storageTransitions.add(storageTransition);
        storageTransition = new LifecycleRule.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<LifecycleRule.StorageTransition>();
        storageTransition = new LifecycleRule.StorageTransition();
    
        storageTransition.setCreatedBeforeDate(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
    
        storageTransition.setStorageClass(StorageClass.Archive);
        storageTransitions.add(storageTransition);
        rule.setStorageTransition(storageTransitions);
        request.AddLifecycleRule(rule);
    
        // Specify that rule6 is configured 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 the objects are last modified. 
        storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
        storageTransition = new LifecycleRule.StorageTransition();
        storageTransition.setStorageClass(StorageClass.Archive);
        storageTransition.setExpirationDays(365);
        storageTransitions.add(storageTransition);
        rule.setStorageTransition(storageTransitions);
        // Configure the lifecycle rule to automatically delete expired delete markers. 
        rule.setExpiredDeleteMarker(true);
        // Configure the lifecycle rule to convert the previous versions of objects to the IA storage class 10 days after the objects are last modified. 
        LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition =
                new LifecycleRule.NoncurrentVersionStorageTransition().withNoncurrentDays(10).withStrorageClass(StorageClass.IA);
        // Specify that the storage class of the previous versions of objects is converted to Archive 20 days after the objects are last modified. 
        LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition2 =
                new LifecycleRule.NoncurrentVersionStorageTransition().withNoncurrentDays(20).withStrorageClass(StorageClass.Archive);
        // Specify that the previous versions of objects are deleted 30 days after the objects become previous versions. 
        LifecycleRule.NoncurrentVersionExpiration noncurrentVersionExpiration = new LifecycleRule.NoncurrentVersionExpiration().withNoncurrentDays(30);
        List<LifecycleRule.NoncurrentVersionStorageTransition> noncurrentVersionStorageTransitions = new ArrayList<LifecycleRule.NoncurrentVersionStorageTransition>();
        noncurrentVersionStorageTransitions.add(noncurrentVersionStorageTransition2);
        rule.setStorageTransition(storageTransitions);
        rule.setNoncurrentVersionExpiration(noncurrentVersionExpiration);
        rule.setNoncurrentVersionStorageTransitions(noncurrentVersionStorageTransitions);
        request.AddLifecycleRule(rule);
    
        // Initiate a request to configure lifecycle rules. 
        ossClient.setBucketLifecycle(request);
    
        // Query the lifecycle rules configured for the bucket. 
        List<LifecycleRule> listRules = ossClient.getBucketLifecycle(bucketName);
        for(LifecycleRule rules : listRules){
            System.out.println("ruleId="+rules.getId()+", matchPrefix="+rules.getPrefix());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if(ossClient != null){
            // Shut down the OSSClient instance. 
            ossClient.shutdown();
        }
    }
  • Configure a lifecycle rule for all objects in a bucket
    The following code provides an example on how to configure a lifecycle rule for all objects in a bucket named examplebucket:
    OSS ossClient = null;
    try {
        // Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
        String endpoint = "yourEndpoint";
        // 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. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket for which you want to configure a lifecycle rule. Example: examplebucket. 
        String bucketName = "examplebucket";
    
        // Create an OSSClient instance. 
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
        // Create a request by using SetBucketLifecycleRequest. 
        SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);
    
        // Specify the ID for the lifecycle rule. 
        String ruleId0 = "rule0";
        // If you leave the Prefix parameter empty, this lifecycle rule applies to the whole bucket. 
        String matchPrefix0 = null;
    
        // Set the expiration time to three days after the last modified time. 
        LifecycleRule rule = new LifecycleRule(ruleId0, matchPrefix0, LifecycleRule.RuleStatus.Enabled, 3);
        request.AddLifecycleRule(rule);
    
        // Initiate a request to configure lifecycle rules. 
        ossClient.setBucketLifecycle(request);
    
        // Query the lifecycle rules configured for the bucket. 
        List<LifecycleRule> listRules = ossClient.getBucketLifecycle(bucketName);
        for(LifecycleRule rules : listRules){
            System.out.println("ruleId="+rules.getId()+", matchPrefix="+rules.getPrefix()+", expirationDays="+rules.getExpirationDays());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if(ossClient != null){
            // Shut down the OSSClient instance. 
            ossClient.shutdown();
        }
    }

Query lifecycle rules

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

// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
String endpoint = "yourEndpoint";
// 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. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket of which you want to query the lifecycle rules. Example: examplebucket. 
String bucketName = "examplebucket";

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

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

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

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

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

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

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

    // View the expiration days configured in the lifecycle rule. 
    if (r.hasExpirationDays()) {
        System.out.println("rule expiration days: " + r.getExpirationDays());
    }

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

    // View the rule for 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 rule of storage class conversion. 
    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 lifecycle rule to check whether expired delete markers are automatically deleted. 
    if (r.hasExpiredDeleteMarker()) {
        System.out.println("rule expired delete marker: " + r.getExpiredDeleteMarker());
    }

    // View the rule to convert the storage class of 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 rule for the previous versions of objects. 
    if (r.hasNoncurrentVersionExpiration()) {
        System.out.println("rule noncurrent versions expiration days:" + r.getNoncurrentVersionExpiration().getNoncurrentDays());
    }
}

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

Clear lifecycle rules

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

// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com. 
String endpoint = "yourEndpoint";
// 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. 
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket of which you want to clear lifecycle rules. Example: examplebucket. 
String bucketName = "examplebucket";

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

ossClient.deleteBucketLifecycle(bucketName);

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