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 to reduce your storage costs. This topic describes how to manage lifecycle rules for buckets.

Configure lifecycle rules

  • Configure lifecycle rules that match objects by tag and prefix

    The following sample code provides an example on how to configure a lifecycle rule that matches objects by prefix and tag for the bucket named examplebucket:

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.common.utils.DateUtil;
    import com.aliyun.oss.model.LifecycleRule;
    import com.aliyun.oss.model.SetBucketLifecycleRequest;
    import com.aliyun.oss.model.StorageClass;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. 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. Example: examplebucket. 
            String bucketName = "examplebucket";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // Create a request by using SetBucketLifecycleRequest. 
                SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);
    
                // Specify the ID of 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 tag. In the example, the key is set to owner and the value is set to 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 date to three days after the last modification time. 
                LifecycleRule rule = new LifecycleRule(ruleId0, matchPrefix0, LifecycleRule.RuleStatus.Enabled, 3);
                rule.setTags(matchTags0);
                request.AddLifecycleRule(rule);
    
                // Specify that the objects that are created before the specific 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 date of parts to three days later. 
                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 specific 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 whose last modification time is 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);
                // Specify that delete markers are automatically removed when they expire. 
                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);
                // Configure the lifecycle rule to convert the previous versions of objects to the Archive storage class 20 days after the objects are last modified. 
                LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition2 =
                        new LifecycleRule.NoncurrentVersionStorageTransition().withNoncurrentDays(20).withStrorageClass(StorageClass.Archive);
                // Specify that objects are deleted 30 days after they 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 that are configured for the bucket. 
                List<LifecycleRule> listRules = ossClient.getBucketLifecycle(bucketName);
                for(LifecycleRule rules : listRules){
                    System.out.println("ruleId="+rules.getId()+", matchPrefix="+rules.getPrefix());
                }
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    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 the bucket named examplebucket:
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.LifecycleRule;
    import com.aliyun.oss.model.SetBucketLifecycleRequest;
    import java.util.List;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. 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. Example: examplebucket. 
            String bucketName = "examplebucket";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            try {
                // Create a request by using SetBucketLifecycleRequest. 
                SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);
    
                // Specify the ID of the lifecycle rule. 
                String ruleId0 = "rule0";
                // If the prefix that is used to match objects is left empty, the lifecycle rule takes effect on all objects in the bucket. 
                String matchPrefix0 = null;
    
                // Set the expiration date to three days after the last modification 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 that are 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 (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }

Query lifecycle rules

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

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.LifecycleRule;
import java.util.List;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. 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. Example: examplebucket. 
        String bucketName = "examplebucket";

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

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

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

                // Query 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 (LifecycleRule.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 removed. 
                if (r.hasExpiredDeleteMarker()) {
                    System.out.println("rule expired delete marker: " + r.getExpiredDeleteMarker());
                }

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

                // View the expiration rule for objects of previous versions. 
                if (r.hasNoncurrentVersionExpiration()) {
                    System.out.println("rule noncurrent versions expiration days:" + r.getNoncurrentVersionExpiration().getNoncurrentDays());
                }
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Delete lifecycle rules

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

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify the actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. 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. Example: examplebucket. 
        String bucketName = "examplebucket";

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

        try {
            ossClient.deleteBucketLifecycle(bucketName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

References

  • For more information about the complete sample code for lifecycle rules, visit GitHub.
  • For more information about the API operation that you can call to configure lifecycle rules, see PutBucketLifecycle.
  • For more information about the API operation that you can call to query lifecycle rules, see GetBucketLifecycle.
  • For more information about the API operation that you can call to delete lifecycle rules, see DeleteBucketLifecycle.