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.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint For more information about the regions and endpoints supported by OSS, see Regions and endpoints.
  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or STS, see Create an OSSClient instance.
  • The oss:PutBucketLifecycle permission is required to configure a lifecycle rule. The oss:GetBucketLifecycle permission is required to query a lifecycle rule. The oss:DeleteBucketLifecycle permission is required to delete a lifecycle rule. For more information, see Attach a custom policy to a RAM user.

Configure lifecycle rules

The following code provides an example on how to configure a lifecycle rule based on the last modified time for a bucket named examplebucket. The lifecycle rule matches objects by prefix and tag. The storage class of the matched objects is converted, or the matched objects are deleted based on the lifecycle rule.

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
    /* 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. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    SetBucketLifecycleRequest request(BucketName);
    std::string date("2022-10-12T00:00:00.000Z");

    /* Configure tagging. */
    Tagging tagging;
    tagging.addTag(Tag("key1", "value1"));
    tagging.addTag(Tag("key2", "value2"));

    /* Specify a lifecycle rule. */
    auto rule1 = LifecycleRule();
    rule1.setID("rule1");
    rule1.setPrefix("test1/");
    rule1.setStatus(RuleStatus::Enabled);
    rule1.setExpiration(3);
    rule1.setTags(tagging.Tags());

    /* Specify the expiration date. */
    auto rule2 = LifecycleRule();
    rule2.setID("rule2");
    rule2.setPrefix("test2/");
    rule2.setStatus(RuleStatus::Disabled);
    rule2.setExpiration(date);

    /* Specify that rule3 is configured for the bucket if the versioning state of the bucket is enabled. */
    auto rule3 = LifecycleRule();
    rule3.setID("rule3");
    rule3.setPrefix("test3/");
    rule3.setStatus(RuleStatus::Disabled);

    /* Specify that the storage class of objects is converted to Archive 365 days after they are last modified. */  
    auto transition = LifeCycleTransition();  
    transition.Expiration().setDays(365);
    transition.setStorageClass(StorageClass::Archive);
    rule3.addTransition(transition);

    /* Specify that expired delete markers are automatically deleted. */
    rule3.setExpiredObjectDeleteMarker(true);

    /* Specify that the storage class of objects is converted to Infrequent Access (IA) 10 days after their versions are updated. */
    auto transition1 = LifeCycleTransition();  
    transition1.Expiration().setDays(10);
    transition1.setStorageClass(StorageClass::IA);

    /* Specify that the storage class of objects is converted to Archive 20 days after their versions are updated. */
    auto transition2 = LifeCycleTransition();  
    transition2.Expiration().setDays(20);
    transition2.setStorageClass(StorageClass::Archive);

    /* Specify that objects are deleted 30 days after their versions are updated. */
    auto expiration  = LifeCycleExpiration(30);
    rule3.setNoncurrentVersionExpiration(expiration);

    LifeCycleTransitionList noncurrentVersionStorageTransitions{transition1, transition2};
    rule3.setNoncurrentVersionTransitionList(noncurrentVersionStorageTransitions);

    /* Configure the lifecycle rules. */
    LifecycleRuleList list{rule1, rule2, rule3};
    request.setLifecycleRules(list);
    auto outcome = client.SetBucketLifecycle(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetBucketLifecycle fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Query lifecycle rules

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

#include <alibabacloud/oss/OssClient.h>
#include "../src/utils/Utils.h"
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
    /* 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. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    /* View the lifecycle rules. */
    auto outcome = client.GetBucketLifecycle(BucketName);

    if (outcome.isSuccess()) {
        std::cout << "GetBucketLifecycle success," << std::endl;
        for (auto const rule : outcome.result().LifecycleRules()) {
            std::cout << "rule:" << rule.ID() << "," << rule.Prefix() << "," << rule.Status() << ","
            "hasExpiration:" << rule.hasExpiration() << "," <<
            "hasTransitionList:" << rule.hasTransitionList() << "," << std::endl;

            auto taglist = rule.Tags();
            for (const auto& tag : taglist)
            {
                std::cout <<"GetBucketLifecycle tag success, Key:" 
                << tag.Key() << "; Value:" << tag.Value() << std::endl;
            }

            /* View relevant lifecycle rules to check whether expired delete markers are automatically removed. */
            if (rule.ExpiredObjectDeleteMarker()) {
                std::cout << "rule expired delete marker: " << rule.ExpiredObjectDeleteMarker() << std::endl;
            }

            /* Query the configurations used to convert the storage class of the previous versions of objects. */
            if (rule.hasNoncurrentVersionTransitionList()) {
                for (auto const lifeCycleTransition : rule.NoncurrentVersionTransitionList()) {
                    std::cout << "rule noncurrent versions trans days:" << lifeCycleTransition.Expiration() <<
                    " trans storage class: " << ToStorageClassName(lifeCycleTransition.StorageClass()) << std::endl;    
                }
            }

            /* Query the expiration configurations of the previous versions of objects. */
            if (rule.hasNoncurrentVersionExpiration()) {
                std::cout << "rule noncurrent versions expiration days:" << rule.NoncurrentVersionExpiration().Days() << std::endl;
            }

        }
    }
    else {
        /* Handle exceptions. */
        std::cout << "GetBucketLifecycle fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Delete lifecycle rules

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

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
    /* 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. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources, such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret,  conf);

    /* Delete the lifecycle rules. */
    DeleteBucketLifecycleRequest request(BucketName);
    auto outcome = client.DeleteBucketLifecycle(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "DeleteBucketLifecycle fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

References

  • For the complete sample code that is used to configure lifecycle rules for a bucket, 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.