Java
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.util.ArrayList;
import java.util.List;
public class Lifecycle {
public static void main(String[] args) throws Exception {
// The endpoint is set to China (Hangzhou) in this example. Specify the actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before running the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name, for example, examplebucket.
String bucketName = "examplebucket";
// Create an OSSClient instance.
// When the OSSClient instance is no longer needed, call the shutdown method to release resources.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
String ruleId1 = "rule1";
String ruleId2 = "rule2";
// Specify the prefix as data/.
String matchPrefix = "data/";
// Specify the prefix as log/.
String matchPrefix2 = "log/";
SetBucketLifecycleRequest request = new SetBucketLifecycleRequest(bucketName);
// In lifecycle rule 1, transition all files with the data/ prefix to the Infrequent Access storage class 200 days after their last access time. When these files are accessed again, they remain in the Infrequent Access storage class.
List<LifecycleRule.StorageTransition> storageTransitions = new ArrayList<LifecycleRule.StorageTransition>();
LifecycleRule.StorageTransition storageTransition = new LifecycleRule.StorageTransition();
storageTransition.setStorageClass(StorageClass.IA);
storageTransition.setExpirationDays(200);
storageTransition.setIsAccessTime(true);
storageTransition.setReturnToStdWhenVisit(false);
storageTransitions.add(storageTransition);
LifecycleRule rule = new LifecycleRule(ruleId1, matchPrefix, LifecycleRule.RuleStatus.Enabled);
rule.setStorageTransition(storageTransitions);
request.AddLifecycleRule(rule);
// In lifecycle rule 2, transition all files with the log/ prefix to the Infrequent Access storage class 120 days after their last access time. When these files are accessed again, they remain in the Infrequent Access storage class.
List<LifecycleRule.StorageTransition> storageTransitions2 = new ArrayList<LifecycleRule.StorageTransition>();
LifecycleRule.StorageTransition storageTransition2 = new LifecycleRule.StorageTransition();
storageTransition2.setStorageClass(StorageClass.IA);
storageTransition2.setExpirationDays(120);
storageTransition2.setIsAccessTime(true);
storageTransition2.setReturnToStdWhenVisit(false);
storageTransitions2.add(storageTransition2);
// In the same rule, transition all files with the log/ prefix to the Archive storage class 250 days after their last modification time.
LifecycleRule.StorageTransition storageTransition3 = new LifecycleRule.StorageTransition();
storageTransition3.setStorageClass(StorageClass.Archive);
storageTransition3.setExpirationDays(250);
storageTransition3.setIsAccessTime(false);
storageTransitions2.add(storageTransition3);
LifecycleRule rule2 = new LifecycleRule(ruleId2, matchPrefix2, LifecycleRule.RuleStatus.Enabled);
rule2.setStorageTransition(storageTransitions2);
request.AddLifecycleRule(rule2);
VoidResult result = ossClient.setBucketLifecycle(request);
System.out.println("Return status code:"+result.getResponse().getStatusCode()+" set lifecycle succeed");
} 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();
}
}
}
}
Python
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import LifecycleRule, BucketLifecycle, StorageTransition
# Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# In lifecycle rule 1, transition all files with the data/ prefix to the Infrequent Access storage class 200 days after their last access time. When these files are accessed again, they remain in the Infrequent Access storage class.
rule1 = LifecycleRule('rule1', 'data/', status=LifecycleRule.ENABLED)
rule1.storage_transitions = [StorageTransition(days=200,
storage_class=oss2.BUCKET_STORAGE_CLASS_IA,
is_access_time=True,
return_to_std_when_visit=False)]
# In lifecycle rule 2, transition all files with the log/ prefix to the Infrequent Access storage class 120 days after their last access time. When these files are accessed again, they remain in the Infrequent Access storage class.
# In the same rule, transition all files with the log/ prefix to the Archive storage class 250 days after their last modification time.
rule2 = LifecycleRule('rule2', 'log/', status=LifecycleRule.ENABLED)
rule2.storage_transitions = [StorageTransition(days=120,
storage_class=oss2.BUCKET_STORAGE_CLASS_IA,
is_access_time=True,
return_to_std_when_visit=False),
StorageTransition(days=250,
storage_class=oss2.BUCKET_STORAGE_CLASS_ARCHIVE,
is_access_time=False)]
lifecycle = BucketLifecycle([rule1, rule2])
# Set the lifecycle rule.
result = bucket.put_bucket_lifecycle(lifecycle)
print('Lifecycle rule set successfully. Return status:' + str(result.status))
Go
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // The region where the bucket is located.
bucketName string // The name of the bucket.
)
// The init function initializes command-line arguments.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}
func main() {
// Parse command-line arguments.
flag.Parse()
// Check if the bucket name is provided.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is provided.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Load the default configuration, and set the credentials provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to set lifecycle rules for the bucket.
request := &oss.PutBucketLifecycleRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
LifecycleConfiguration: &oss.LifecycleConfiguration{
Rules: []oss.LifecycleRule{
{
// In lifecycle rule "rule1", transition all objects with the prefix "data/"
// to the Infrequent Access (IA) storage class 200 days after they are last accessed.
// When these objects are accessed again, they remain in the IA storage class.
ID: oss.Ptr("rule1"),
Status: oss.Ptr("Enabled"),
Prefix: oss.Ptr("data/"),
Transitions: []oss.LifecycleRuleTransition{
{
Days: oss.Ptr(int32(200)),
StorageClass: oss.StorageClassIA,
IsAccessTime: oss.Ptr(true), // Set to true for a rule based on last access time.
ReturnToStdWhenVisit: oss.Ptr(false),
},
},
},
{
// In lifecycle rule "rule2", transition all objects with the prefix "log/"
// to the Infrequent Access (IA) storage class 120 days after they are last accessed.
// In the same rule, transition these objects to the Archive storage class 250 days after they are last accessed.
// When these objects are accessed again, they remain in their current storage class.
ID: oss.Ptr("rule2"),
Status: oss.Ptr("Enabled"),
Prefix: oss.Ptr("log/"),
Transitions: []oss.LifecycleRuleTransition{
{
Days: oss.Ptr(int32(120)),
StorageClass: oss.StorageClassIA,
IsAccessTime: oss.Ptr(true), // Set to true for a rule based on last access time.
ReturnToStdWhenVisit: oss.Ptr(false),
},
{
Days: oss.Ptr(int32(250)),
StorageClass: oss.StorageClassArchive,
IsAccessTime: oss.Ptr(true),
ReturnToStdWhenVisit: oss.Ptr(false),
},
},
},
},
},
}
// Set the lifecycle rules for the bucket.
result, err := client.PutBucketLifecycle(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put bucket lifecycle %v", err)
}
// Print the result of setting the lifecycle rules.
log.Printf("put bucket lifecycle result:%#v\n", result)
}