Todos os produtos
Search
Central de documentação

Object Storage Service:Gerenciamento de ciclo de vida (Go SDK V2)

Última atualização: Jul 03, 2026

Este tópico descreve como gerenciar regras de ciclo de vida de um bucket com o Go SDK V2.

Contexto

No OSS, nem todos os dados enviados exigem acesso frequente. Contudo, alguns precisam ser mantidos em armazenamento frio para fins de conformidade ou arquivamento. De acordo com seus requisitos de negócios, escolha uma das opções a seguir:

  1. Regras de ciclo de vida baseadas na última modificação: Use estas regras para excluir dados não modificados por um longo período e que não são mais necessários, ou para transferi-los a uma classe de armazenamento frio e liberar espaço.

  2. Regras de ciclo de vida baseadas no último acesso: Ative estas regras para que o OSS monitore automaticamente os padrões de acesso aos dados. O serviço identifica dados acessados com pouca frequência e os transfere para uma classe de armazenamento frio mais econômica. Essa abordagem ajuda a organizar os dados em camadas e reduzir custos de armazenamento.

Observações

  • Antes de configurar regras de ciclo de vida baseadas na última modificação ou no último acesso, certifique-se de entender esse recurso. Para obter mais informações, consulte Regras de ciclo de vida baseadas na última modificação e Regras de ciclo de vida baseadas no último acesso.

  • O código de exemplo neste tópico usa a região China (Hangzhou) (cn-hangzhou) como referência. Por padrão, utiliza-se um endpoint público. Se você acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Os exemplos mostram como obter credenciais de acesso a partir de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • A definição de uma regra de ciclo de vida requer a permissão oss:PutBucketLifecycle. A visualização exige a permissão oss:GetBucketLifecycle. Já a exclusão de todas as regras de ciclo de vida de um bucket demanda a permissão oss:DeleteBucketLifecycle. Para obter mais informações sobre como conceder permissões, consulte Conceder políticas de permissão personalizadas a usuários RAM.

Definir regras de ciclo de vida

O código a seguir mostra como definir regras de ciclo de vida com base na última modificação e no último acesso. Caso precise modificar uma ou mais regras após a definição, consulte Como modifico uma ou mais configurações de regra de ciclo de vida?.

Transferir objetos com base na última modificação

O exemplo abaixo demonstra como definir uma regra de ciclo de vida que transfere objetos para uma classe de armazenamento diferente conforme a data da última modificação.

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(&region, "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 com base na última modificação

O código a seguir ilustra a criação de uma regra de ciclo de vida baseada na última modificação. Essa regra aplica-se a objetos em um bucket com o prefixo logs/ e tamanho entre 500 e 1.000 bytes. Ela transfere esses objetos para a classe de armazenamento Infrequent Access (IA) 30 dias após a última modificação, mas exclui aqueles que também possuem o prefixo logs/log e a tag {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(&region, "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 com base no último acesso

O exemplo a seguir mostra como definir uma regra de ciclo de vida que transfere objetos para outra classe de armazenamento conforme a data do último acesso.

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(&region, "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)
}

Visualizar regras de ciclo de vida

Use o código abaixo para visualizar as regras de ciclo de vida de um 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(&region, "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)
							}
						}
					}
				}
			}
		}

	}
}

Excluir todas as regras de ciclo de vida

O código a seguir mostra como excluir todas as regras de ciclo de vida de um bucket. Para excluir regras específicas, consulte Como excluo uma ou mais regras de ciclo de vida?.

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(&region, "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)
}

Tópicos relacionados

  • Para obter mais detalhes sobre como definir regras de ciclo de vida, consulte PutBucketLifecycle.

  • Para mais informações sobre como visualizar regras de ciclo de vida, consulte GetBucketLifecycle.

  • Para saber mais sobre como excluir todas as regras de ciclo de vida de um bucket, consulte DeleteBucketLifecycle.