Este tema describe cómo gestionar las reglas de ciclo de vida de un bucket mediante Go SDK V2.
Contexto
En OSS, no todos los datos cargados requieren acceso frecuente. Sin embargo, algunos deben conservarse en almacenamiento en frío por motivos de cumplimiento normativo o archivado. Según sus requisitos empresariales, puede elegir entre las siguientes opciones:
Reglas de ciclo de vida basadas en la última modificación: Use estas reglas para eliminar datos que no se han modificado durante un periodo prolongado y ya no son necesarios, o bien para transferirlos a una clase de almacenamiento en frío y liberar espacio.
Reglas de ciclo de vida basadas en el último acceso: Habilite estas reglas para que OSS supervise automáticamente los patrones de acceso a los datos. OSS identifica los datos con acceso poco frecuente y los transfiere a una clase de almacenamiento en frío más rentable. Esto le permite organizar los datos por niveles y reducir los costos de almacenamiento.
Notas
Antes de configurar reglas de ciclo de vida basadas en la última modificación o el último acceso, asegúrese de comprender esta función. Para obtener más información, consulte Lifecycle rules based on the last modified time y Lifecycle rules based on the last access time.
El código de ejemplo de este tema usa la región China (Hangzhou) (
cn-hangzhou) como referencia. De forma predeterminada, se usa un endpoint público. Si accede a OSS desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.El código de ejemplo muestra cómo obtener credenciales de acceso desde variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.
Establecer una regla de ciclo de vida requiere el permiso
oss:PutBucketLifecycle. Consultar reglas de ciclo de vida requiere el permisooss:GetBucketLifecycle. Eliminar todas las reglas de ciclo de vida de un bucket requiere el permisooss:DeleteBucketLifecycle. Para obtener más información sobre cómo otorgar permisos, consulte Grant custom permission policies to RAM users.
Establecer reglas de ciclo de vida
A continuación se muestra cómo establecer reglas de ciclo de vida basadas en la última modificación y el último acceso. Si desea modificar una o más reglas después de configurarlas, consulte How do I modify one or more lifecycle rule configurations?.
Transferir objetos según la última modificación
El siguiente código muestra cómo establecer una regla de ciclo de vida que transfiere objetos a una clase de almacenamiento diferente según su última fecha de modificación.
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{
{
// Specify lifecycle rule "rule1".
// This rule transitions objects with the prefix "foo/" and the tag {k1: v1}
// to the Infrequent Access (IA) storage class 30 days after they are last modified.
Status: oss.Ptr("Enabled"),
ID: oss.Ptr("rule1"),
Prefix: oss.Ptr("foo/"),
Transitions: []oss.LifecycleRuleTransition{
{
Days: oss.Ptr(int32(30)),
StorageClass: oss.StorageClassIA,
IsAccessTime: oss.Ptr(false), // Set to false for a rule based on last modified time.
},
},
Tags: []oss.Tag{
{
Key: oss.Ptr("k1"),
Value: oss.Ptr("v1"),
},
},
},
{
// Specify lifecycle rule "rule2". This rule applies to objects with the prefix "dir/".
// It automatically removes expired object delete markers, deletes non-current versions after 30 days,
// and transitions non-current versions to the IA storage class 10 days after they become non-current.
ID: oss.Ptr("rule2"),
Prefix: oss.Ptr("dir/"),
Status: oss.Ptr("Enabled"),
Expiration: &oss.LifecycleRuleExpiration{
Days: oss.Ptr(int32(10)),
ExpiredObjectDeleteMarker: oss.Ptr(true),
},
NoncurrentVersionExpiration: &oss.NoncurrentVersionExpiration{
NoncurrentDays: oss.Ptr(int32(30)),
},
NoncurrentVersionTransitions: []oss.NoncurrentVersionTransition{{
NoncurrentDays: oss.Ptr(int32(10)),
StorageClass: oss.StorageClassIA,
IsAccessTime: oss.Ptr(false), // Set to false for a rule based on last modified time.
}},
},
},
},
}
// 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)
}
Filtrar objetos según la última modificación
El siguiente código muestra cómo crear una regla de ciclo de vida basada en la última modificación. Esta regla se aplica a objetos en un bucket con el prefijo logs/ y tamaños entre 500 y 1,000 bytes. Transfiere dichos objetos a la clase de almacenamiento Infrequent Access (IA) 30 días después de su última modificación, pero excluye aquellos que también tienen el prefijo logs/log y la etiqueta {key1: value1}.
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),
LifecycleConfiguration: &oss.LifecycleConfiguration{
Rules: []oss.LifecycleRule{
{
// Specify lifecycle rule "rule1". This rule transitions objects to the IA storage class
// 30 days after they are last modified. The rule applies to objects with the prefix "logs/",
// sizes between 500 and 1000 bytes, but excludes those with the prefix "logs/log" and tag {key1: value1}.
ID: oss.Ptr("rule1"),
Status: oss.Ptr("Enabled"),
Prefix: oss.Ptr("logs/"),
Transitions: []oss.LifecycleRuleTransition{
{
Days: oss.Ptr(int32(30)),
StorageClass: oss.StorageClassIA,
IsAccessTime: oss.Ptr(false), // Set to false for a rule based on last modified time.
},
},
Filter: &oss.LifecycleRuleFilter{
ObjectSizeGreaterThan: oss.Ptr(int64(500)),
ObjectSizeLessThan: oss.Ptr(int64(1000)),
Nots: []oss.LifecycleRuleNot{
{
Prefix: oss.Ptr("logs/log"),
Tag: &oss.Tag{
Key: oss.Ptr("key1"),
Value: oss.Ptr("value1"),
},
},
},
},
},
},
},
}
// 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)
}
Transferir objetos según el último acceso
El siguiente código muestra cómo establecer una regla de ciclo de vida que transfiere objetos a una clase de almacenamiento diferente según su última fecha de acceso.
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)
}
Consultar reglas de ciclo de vida
El siguiente código muestra cómo consultar las reglas de ciclo de vida de un bucket.
package main
import (
"context"
"flag"
"fmt"
"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 get the lifecycle configuration for the bucket.
request := &oss.GetBucketLifecycleRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
}
// Get the lifecycle configuration and handle the result.
result, err := client.GetBucketLifecycle(context.TODO(), request)
if err != nil {
log.Fatalf("failed to get bucket lifecycle %v", err)
}
// Print the information contained in the lifecycle rules.
for _, rule := range result.LifecycleConfiguration.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 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 Transition 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)
}
if rule.NoncurrentVersionTransitions != nil {
for _, nonVersionTransition := range rule.NoncurrentVersionTransitions {
fmt.Println("Lifecycle Rule Non Version Transitions Non current Days:", nonVersionTransition.NoncurrentDays)
fmt.Println("Lifecycle Rule Non Version Transition Storage Class:", nonVersionTransition.StorageClass)
if nonVersionTransition.IsAccessTime != nil {
fmt.Println("Lifecycle Rule Non Version Transition Is Access Time:", *nonVersionTransition.IsAccessTime)
}
if nonVersionTransition.ReturnToStdWhenVisit != nil {
fmt.Println("Lifecycle Rule Non Version 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 {
if rule.Filter.ObjectSizeGreaterThan != nil {
fmt.Println("Lifecycle Rule Filter Object Size Greater Than:", *rule.Filter.ObjectSizeGreaterThan)
}
if rule.Filter.ObjectSizeLessThan != nil {
fmt.Println("Lifecycle Rule Filter Object Size Less Than:", *rule.Filter.ObjectSizeLessThan)
}
if len(rule.Filter.Nots) > 0 {
for _, not := range rule.Filter.Nots {
fmt.Println("Lifecycle Rule Filter Not Prefix:", not.Prefix)
if not.Tag != nil {
fmt.Println("Lifecycle Rule Filter Not Tag Key:", not.Tag.Key)
fmt.Println("Lifecycle Rule Filter Not Tag Value:", not.Tag.Value)
}
}
}
}
}
}
}
}
Eliminar todas las reglas de ciclo de vida
El siguiente código muestra cómo eliminar todas las reglas de ciclo de vida de un bucket. Para eliminar una o más reglas específicas, consulte How do I delete one or more lifecycle rules?.
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 delete all lifecycle rules for the bucket.
request := &oss.DeleteBucketLifecycleRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
}
// Delete all lifecycle rules for the bucket.
result, err := client.DeleteBucketLifecycle(context.TODO(), request)
if err != nil {
log.Fatalf("failed to delete bucket lifecycle %v", err)
}
// Print the result of deleting the lifecycle rules.
log.Printf("delete bucket lifecycle result:%#v\n", result)
}
Temas relacionados
Para obtener más información sobre cómo establecer reglas de ciclo de vida, consulte PutBucketLifecycle.
Para obtener más información sobre cómo consultar reglas de ciclo de vida, consulte GetBucketLifecycle.
Para obtener más información sobre cómo eliminar todas las reglas de ciclo de vida de un bucket, consulte DeleteBucketLifecycle.