Lifecycle rules let you automatically transition objects to lower-cost storage classes or delete them when they are no longer needed. Rules are evaluated based on each object's last modified time, so you can reduce storage costs without manual intervention.
Prerequisites
Before you begin, make sure that you have:
An OSS bucket with objects to manage
The appropriate RAM permissions:
oss:PutBucketLifecycle— to set lifecycle rulesoss:GetBucketLifecycle— to query lifecycle rulesoss:DeleteBucketLifecycle— to delete lifecycle rules
(Optional) Familiarity with lifecycle rules based on the last modified time
Usage notes
The examples in this topic use the public endpoint for the China (Hangzhou) region. To call OSS from another Alibaba Cloud service in the same region, use the internal endpoint instead. For details, see Regions and endpoints.
The examples create an
OSSClientinstance using an OSS endpoint. To create anOSSClientusing a custom domain name or Security Token Service (STS), see Create an OSSClient instance.For more information about Resource Access Management (RAM) permissions, see Attach a custom policy to a RAM user.
Operations
All three examples follow the same client initialization pattern: set your endpoint and region, load credentials from environment variables, and call the target operation.
| Operation | Method | Required permission |
|---|---|---|
| Set lifecycle rules | SetBucketLifecycle | oss:PutBucketLifecycle |
| View lifecycle rules | GetBucketLifecycle | oss:GetBucketLifecycle |
| Clear lifecycle rules | DeleteBucketLifecycle | oss:DeleteBucketLifecycle |
Set lifecycle rules
The following example sets three lifecycle rules on examplebucket:
rule1 — expires objects under the
test1/prefix after 3 days; filters by tagskey1=value1andkey2=value2rule2 — expires objects under the
test2/prefix on a fixed date (2022-10-12T00:00:00.000Z)rule3 — for a versioning-enabled bucket: transitions current objects to Archive after 365 days, transitions noncurrent versions to Infrequent Access after 10 days and to Archive after 20 days, deletes noncurrent versions after 30 days, and auto-removes expired delete markers
To modify one or more rules after they are set, see How do I modify one or more lifecycle rules?
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
// Set yourEndpoint to the endpoint of the region where the bucket is located.
// Example: https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou).
std::string Endpoint = "yourEndpoint";
// Set yourRegion to the region ID of the bucket. Example: cn-hangzhou.
std::string Region = "yourRegion";
std::string BucketName = "examplebucket";
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
// Load credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
SetBucketLifecycleRequest request(BucketName);
std::string date("2022-10-12T00:00:00.000Z");
// rule1: expire objects under test1/ after 3 days, filtered by tags.
Tagging tagging;
tagging.addTag(Tag("key1", "value1"));
tagging.addTag(Tag("key2", "value2"));
auto rule1 = LifecycleRule();
rule1.setID("rule1");
rule1.setPrefix("test1/");
rule1.setStatus(RuleStatus::Enabled);
rule1.setExpiration(3);
rule1.setTags(tagging.Tags());
// rule2: expire objects under test2/ on a fixed date.
auto rule2 = LifecycleRule();
rule2.setID("rule2");
rule2.setPrefix("test2/");
rule2.setStatus(RuleStatus::Disabled);
rule2.setExpiration(date);
// rule3: versioning-enabled bucket.
auto rule3 = LifecycleRule();
rule3.setID("rule3");
rule3.setPrefix("test3/");
rule3.setStatus(RuleStatus::Disabled);
// Transition current objects to Archive 365 days after last modification.
auto transition = LifeCycleTransition();
transition.Expiration().setDays(365);
transition.setStorageClass(StorageClass::Archive);
rule3.addTransition(transition);
// Auto-remove expired delete markers.
rule3.setExpiredObjectDeleteMarker(true);
// Transition noncurrent versions to Infrequent Access after 10 days.
auto transition1 = LifeCycleTransition();
transition1.Expiration().setDays(10);
transition1.setStorageClass(StorageClass::IA);
// Transition noncurrent versions to Archive after 20 days.
auto transition2 = LifeCycleTransition();
transition2.Expiration().setDays(20);
transition2.setStorageClass(StorageClass::Archive);
// Delete noncurrent versions 30 days after they become noncurrent.
auto expiration = LifeCycleExpiration(30);
rule3.setNoncurrentVersionExpiration(expiration);
LifeCycleTransitionList noncurrentVersionStorageTransitions{transition1, transition2};
rule3.setNoncurrentVersionTransitionList(noncurrentVersionStorageTransitions);
LifecycleRuleList list{rule1, rule2, rule3};
request.setLifecycleRules(list);
auto outcome = client.SetBucketLifecycle(request);
if (!outcome.isSuccess()) {
std::cout << "SetBucketLifecycle fail"
<< ",code:" << outcome.error().Code()
<< ",message:" << outcome.error().Message()
<< ",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
ShutdownSdk();
return 0;
}Key parameters
| Parameter | Type | Description |
|---|---|---|
BucketName | std::string | Name of the bucket to configure |
LifecycleRule | class | Represents one lifecycle rule; configured via setID, setPrefix, setStatus, setExpiration, and setTags |
RuleStatus | enum | Enabled — rule is active; Disabled — rule is inactive |
LifeCycleTransition | class | Storage class transition action; set the target class via setStorageClass and the trigger days via Expiration().setDays() |
StorageClass | enum | Standard, IA (Infrequent Access), Archive, ColdArchive |
LifeCycleExpiration | class | Object or noncurrent-version expiration; accepts a day count or an ISO 8601 date string |
setExpiredObjectDeleteMarker(true) | method | Automatically removes delete markers after all versions of an object have expired |
setNoncurrentVersionTransitionList | method | List of storage class transitions applied to noncurrent versions |
setNoncurrentVersionExpiration | method | Deletes noncurrent versions after the specified number of days |
For class and field definitions, see include/alibabacloud/oss/model/SetBucketLifecycleRequest.h in the OSS C++ SDK source.View lifecycle rules
The following example retrieves all lifecycle rules configured on examplebucket and prints each rule's ID, prefix, status, expiration settings, tags, and noncurrent-version actions.
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
std::string ToStorageClassName(const StorageClass& storageClass) {
switch (storageClass) {
case StorageClass::Standard: return "Standard";
case StorageClass::IA: return "IA";
case StorageClass::Archive: return "Archive";
case StorageClass::ColdArchive: return "ColdArchive";
default: return "Unknown";
}
}
int main(void)
{
std::string Endpoint = "yourEndpoint";
std::string Region = "yourRegion";
std::string BucketName = "examplebucket";
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
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;
// Print tags.
for (const auto& tag : rule.Tags()) {
std::cout << "tag Key:" << tag.Key() << "; Value:" << tag.Value() << std::endl;
}
// Print expired delete marker setting.
if (rule.ExpiredObjectDeleteMarker()) {
std::cout << "expired delete marker: " << rule.ExpiredObjectDeleteMarker() << std::endl;
}
// Print noncurrent-version transition rules.
if (rule.hasNoncurrentVersionTransitionList()) {
for (auto const t : rule.NoncurrentVersionTransitionList()) {
std::cout << "noncurrent version transition days:"
<< std::to_string(t.Expiration().Days())
<< " storage class: " << ToStorageClassName(t.StorageClass()) << std::endl;
}
}
// Print noncurrent-version expiration rule.
if (rule.hasNoncurrentVersionExpiration()) {
std::cout << "noncurrent version expiration days:"
<< rule.NoncurrentVersionExpiration().Days() << std::endl;
}
}
} else {
std::cout << "GetBucketLifecycle fail"
<< ",code:" << outcome.error().Code()
<< ",message:" << outcome.error().Message()
<< ",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
ShutdownSdk();
return 0;
}Key return fields
| Field | Method | Description |
|---|---|---|
| Rule ID | rule.ID() | Unique identifier for the rule |
| Prefix | rule.Prefix() | Object key prefix the rule applies to |
| Status | rule.Status() | Enabled or Disabled |
| Expiration | rule.hasExpiration() | Whether the rule has an expiration action |
| Transition list | rule.hasTransitionList() | Whether the rule has storage class transition actions |
| Tags | rule.Tags() | Object tags used as a filter |
| Noncurrent version transitions | rule.NoncurrentVersionTransitionList() | Storage class transitions for noncurrent versions |
| Noncurrent version expiration | rule.NoncurrentVersionExpiration().Days() | Days until noncurrent versions are deleted |
Clear lifecycle rules
The following example clears all lifecycle rules from examplebucket. To delete specific rules instead of all rules, see How do I delete one or more lifecycle rules?
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
std::string Endpoint = "yourEndpoint";
std::string Region = "yourRegion";
std::string BucketName = "examplebucket";
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
DeleteBucketLifecycleRequest request(BucketName);
auto outcome = client.DeleteBucketLifecycle(request);
if (!outcome.isSuccess()) {
std::cout << "DeleteBucketLifecycle fail"
<< ",code:" << outcome.error().Code()
<< ",message:" << outcome.error().Message()
<< ",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
ShutdownSdk();
return 0;
}What's next
For the complete sample code, see the GitHub sample.
For the API reference, see: