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 Initialization.
  • 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

Configure a lifecycle rule based on the last modified time to convert the storage class of objects or delete objects

The following code provides an example on how to configure a lifecycle rule based on the last modified time for a bucket named examplebucket to convert the storage class of objects in the bucket or delete the objects:

package main

import (
    "fmt"
    "os"

    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // Create an OSSClient instance. 
    // 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. Specify your actual endpoint. 
    // 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. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create a lifecycle rule and set ID to rule1. Specify that the objects whose names contain the foo prefix in the bucket expire three days after the objects are last modified. 
    rule1 := oss.BuildLifecycleRuleByDays("rule1", "foo/", true, 3)

    // If an object in a bucket for which versioning is enabled is a delete marker and has no other versions, the delete marker is deleted. 
    deleteMark := true
    expiration := oss.LifecycleExpiration{
        ExpiredObjectDeleteMarker: &deleteMark,
    }

    // Specify that the previous versions of the objects are deleted 30 days after the objects are last modified. 
    versionExpiration := oss.LifecycleVersionExpiration{
        NoncurrentDays: 30,
    }

    // Specify that the storage class of the previous versions of the objects is converted to IA 10 days after the objects are last modified. 
    versionTransition := oss.LifecycleVersionTransition{
        NoncurrentDays: 10,
        StorageClass:   "IA",
    }

    // Create a lifecycle rule and set ID to rule2. 
    rule2 := oss.LifecycleRule{
        ID:                   "rule2",
        Prefix:               "yourObjectPrefix",
        Status:               "Enabled",
        Expiration:           &expiration,
        NonVersionExpiration: &versionExpiration,
        NonVersionTransition: &versionTransition,
    }

    // Create a lifecycle rule and set ID to rule3. This rule applies to objects that have the tag whose key is tag1 and whose value is value1. These objects expire three days after the objects are last modified. 
    rule3 := oss.LifecycleRule{
        ID:     "rule3",
        Prefix: "",
        Status: "Enabled",
        Tags: []oss.Tag{
            oss.Tag{
                Key:   "tag1",
                Value: "value1",
            },
        },
        Expiration: &oss.LifecycleExpiration{Days: 3},
    }

    // Configure the lifecycle rules. 
    rules := []oss.LifecycleRule{rule1, rule2, rule3}
    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket"
    err = client.SetBucketLifecycle(bucketName, rules)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
}

Configure a lifecycle rule based on the last modified time to convert the storage class of objects, except for the objects whose names contain specific prefixes or that have specific tags

The following code provides an example on how to configure a lifecycle rule based on the last modified time. The lifecycle rule is used to convert the storage class of objects that meet the following conditions in the examplebucket bucket to IA 30 days after the objects are last modified: The names of the objects do not contain the log prefix and the objects do not have the tag whose key is tag1 and whose value is value1. The Not element in the filter node is used to specify the log prefix, the key1 key, and the value1 value.

package main

import (
    "fmt"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "github.com/aliyun/aliyun-oss-go-sdk/sample"
)

func main() {
    // Create an OSSClient instance. 
    // 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. Specify your actual endpoint. 
    // 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. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket"
    tag := oss.Tag{
        Key: "key1",
        Value: "value1",
    }
    filter := oss.LifecycleFilter{
        Not: oss.LifecycleFilterNot{
            Prefix: "log",
            Tag: &tag,
        },
    }
    rule1 := oss.LifecycleRule{
        ID:     "mtime transition1",
        Prefix: "logs",
        Status: "Enabled",
        Transitions: []oss.LifecycleTransition{
            {
                Days:         30,
                StorageClass: oss.StorageIA,
            },
        },
        Filter:&filter,
    }
    var rules = []oss.LifecycleRule{rule1}
    err = client.SetBucketLifecycle(bucketName, rules)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    fmt.Printf("%s\n", "set lifecycle successed")
}

Configure a lifecycle rule based on the last modified time to convert the storage class of objects

The following code provides an example on how to configure a lifecycle rule based on the last modified time to convert the storage class of objects in the examplebucket bucket:

package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // Create an OSSClient instance. 
    // 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. Specify your actual endpoint. 
    // 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. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket"

    isTrue := true
    isFalse := false
    // Create a lifecycle rule and set ID to rule1. Specify that the objects whose names contain the logs prefix and whose size is less than or equal to 64 KB are converted to IA 30 days after the objects are last accessed. In addition, specify that the objects are still stored as IA objects when the objects are accessed again. 
    rule1 := oss.LifecycleRule{
        ID:         "rule1",
        Prefix:     "logs",
        Status:     "Enabled",
        Transitions: []oss.LifecycleTransition{
            {
                Days: 30,
                StorageClass: oss.StorageIA,
                IsAccessTime: &isTrue,
                ReturnToStdWhenVisit: &isFalse,
                AllowSmallFile:       &isTrue,
            },
        },
    }
    // Create a lifecycle rule and set ID to rule2. Specify that the previous versions of the objects whose names contain the dir prefix and whose size is larger than 64 KB are converted to IA 10 days after the objects are last accessed. In addition, specify that the storage class of the objects is converted to Standard when the objects are accessed again. 
    rule2 := oss.LifecycleRule{
        ID:         "rule2",
        Prefix:     "dir",
        Status:     "Enabled",
        NonVersionTransitions:[]oss.LifecycleVersionTransition {
            {
                NoncurrentDays: 10,
                StorageClass: oss.StorageIA,
                IsAccessTime: &isTrue,
                ReturnToStdWhenVisit: &isTrue,
                AllowSmallFile:       &isFalse,
            },
        },
    }
    // Configure the lifecycle rules. 
    var rules = []oss.LifecycleRule{rule1,rule2}
    err = client.SetBucketLifecycle(bucketName, rules)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    fmt.Printf("%s\n", "set bucket life cycle success")
}

Query lifecycle rules

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

package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // Create an OSSClient instance. 
    // 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. Specify your actual endpoint. 
    // 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. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket"
    // Query the lifecycle rules of the bucket. 
    lcRes, err := client.GetBucketLifecycle(bucketName)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    for _, rule := range lcRes.Rules {
        fmt.Println("Lifecycle Rule Id:",rule.ID)
        fmt.Println("Lifecycle Rule Prefix:",rule.Prefix)
        fmt.Println("Lifecycle Rule Status:",rule.Status)
        if rule.Expiration != nil {
            fmt.Println("Lifecycle Rule Expiration Days:",rule.Expiration.Days)
            fmt.Println("Lifecycle Rule Expiration Date:",rule.Expiration.Date)
            fmt.Println("Lifecycle Rule Expiration Created Before Date:",rule.Expiration.CreatedBeforeDate)

            if rule.Expiration.ExpiredObjectDeleteMarker != nil {
                fmt.Println("Lifecycle Rule Expiration Expired Object DeleteMarker:", *rule.Expiration.ExpiredObjectDeleteMarker)
            }
        }

        for _, tag := range rule.Tags {
            fmt.Println("Lifecycle Rule Tag Key:",tag.Key)
            fmt.Println("Lifecycle Rule Tag Value:",tag.Value)
        }

        for _, transition := range rule.Transitions {
            fmt.Println("Lifecycle Rule Transition Days:",transition.Days)
            fmt.Println("Lifecycle Rule Transition Created Before Date:",transition.CreatedBeforeDate)
            fmt.Println("Lifecycle Rule Transition Storage Class:",transition.StorageClass)
            if transition.IsAccessTime != nil {
                fmt.Println("Lifecycle Rule Transition Is Access Time:",*transition.IsAccessTime)
            }
            if transition.ReturnToStdWhenVisit != nil {
                fmt.Println("Lifecycle Rule Transition Return To Std When Visit:",*transition.ReturnToStdWhenVisit)
            }

            if transition.AllowSmallFile != nil {
                fmt.Println("Lifecycle Rule Non Version Allow Small File:", *transition.AllowSmallFile)
            }

        }
        if rule.AbortMultipartUpload != nil {
            fmt.Println("Lifecycle Rule Abort Multipart Upload Days:",rule.AbortMultipartUpload.Days)
            fmt.Println("Lifecycle Rule Abort Multipart Upload Created Before Date:",rule.AbortMultipartUpload.CreatedBeforeDate)
        }

        for _, nonVersionTransition := range rule.NonVersionTransitions {
            fmt.Println("Lifecycle Rule Non Version Transitions Non current Days:",nonVersionTransition.NoncurrentDays)
            fmt.Println("Lifecycle Rule Transition Storage Class:",nonVersionTransition.StorageClass)
            if nonVersionTransition.IsAccessTime != nil {
                fmt.Println("Lifecycle Rule Transition Is Access Time:",*nonVersionTransition.IsAccessTime)
            }

            if nonVersionTransition.ReturnToStdWhenVisit != nil {
                fmt.Println("Lifecycle Rule Transition Return To Std When Visit:",*nonVersionTransition.ReturnToStdWhenVisit)
            }

            if nonVersionTransition.AllowSmallFile != nil {
                fmt.Println("Lifecycle Rule Non Version Allow Small File:", *nonVersionTransition.AllowSmallFile)
            }

            if rule.Filter != nil {
                fmt.Println("Lifecycle Rule Filter Not Prefix:", rule.Filter.Not.Prefix)
                if rule.Filter.Not.Tag != nil {
                    fmt.Println("Lifecycle Rule Filter Not Tag Key:", rule.Filter.Not.Tag.Key)
                    fmt.Println("Lifecycle Rule Filter Not Tag Value:", rule.Filter.Not.Tag.Value)
                }
            }

        }
    }
}    

Delete lifecycle rules

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

package main

import (
    "fmt"
    "os"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
    // Create an OSSClient instance. 
    // 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. Specify your actual endpoint. 
    // 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. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket"

    // Delete the lifecycle rules. 
    err = client.DeleteBucketLifecycle(bucketName)
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
 }            

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.