Configure regras de ciclo de vida para objetos com prefixos ou tags específicos. Você também pode definir uma combinação de prefixos e tags como condições das regras de ciclo de vida.
Se você configurar condições de tag, a regra se aplicará apenas aos objetos que atenderem às condições de chave e valor da tag. Caso uma regra contenha um prefixo e múltiplas tags de objeto, ela será aplicada somente aos objetos que corresponderem tanto ao prefixo quanto às condições de tag.
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização.
Especifique tags em uma regra de ciclo de vida
O código a seguir apresenta um exemplo de como especificar tags em uma regra de ciclo de vida:
# -*- coding: utf-8 -*-
import oss2
import datetime
from oss2.models import (LifecycleExpiration, LifecycleRule,
BucketLifecycle,AbortMultipartUpload,
TaggingRule, Tagging, StorageTransition)
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# 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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Specify that objects expire three days after they are last modified.
# Specify the name of the expiration rule and the prefix to match the objects.
rule1 = LifecycleRule('rule1', 'tests/',
# Enable the expiration rule.
status=LifecycleRule.ENABLED,
# Specify that objects expire three days after they are last modified.
expiration=LifecycleExpiration(days=3))
# Specify that the objects last modified before the specified date expire.
# Specify the name of the expiration rule and the prefix to match the objects.
rule2 = LifecycleRule('rule2', 'logging-',
# Disable the expiration rule.
status=LifecycleRule.DISABLED,
# Specify that the objects last modified before the specified date expire.
expiration=LifecycleExpiration(created_before_date=datetime.date(2018, 12, 12)))
# Specify that parts expire three days after they are last modified.
rule3 = LifecycleRule('rule3', 'tests1/',
status=LifecycleRule.ENABLED,
abort_multipart_upload=AbortMultipartUpload(days=3))
# Specify that the parts last modified before the specified date expire.
rule4 = LifecycleRule('rule4', 'logging1-',
status=LifecycleRule.DISABLED,
abort_multipart_upload = AbortMultipartUpload(created_before_date=datetime.date(2018, 12, 12)))
# Configure tags to match objects.
tagging_rule = TaggingRule()
tagging_rule.add('key1', 'value1')
tagging_rule.add('key2', 'value2')
tagging = Tagging(tagging_rule)
# Configure the rule to convert the storage class of an object. Specify that the storage class of an object is converted to Archive 365 days after the object is last modified.
# Tags that match objects are specified in rule5. The rule applies only to objects that match tag conditions of key1=value1 and key2=value2.
rule5 = LifecycleRule('rule5', 'logging2-',
status=LifecycleRule.ENABLED,
storage_transitions=[StorageTransition(days=365, storage_class=oss2.BUCKET_STORAGE_CLASS_ARCHIVE)],
tagging = tagging)
lifecycle = BucketLifecycle([rule1, rule2, rule3, rule4, rule5])
bucket.put_bucket_lifecycle(lifecycle)
Consultar tags configuradas em uma regra de ciclo de vida
O código a seguir apresenta um exemplo de como consultar as tags definidas em uma regra de ciclo de vida:
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# 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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Query the lifecycle rules.
lifecycle = bucket.get_bucket_lifecycle()
for rule in lifecycle.rules:
# Query the part expiration rules.
if rule.abort_multipart_upload is not None:
print('id={0}, prefix={1}, tagging={2}, status={3}, days={4}, created_before_date={5}'
.format(rule.id, rule.prefix, rule.tagging, rule.status,
rule.abort_multipart_upload.days,
rule.abort_multipart_upload.created_before_date))
# Query the object expiration rules.
if rule.expiration is not None:
print('id={0}, prefix={1}, tagging={2}, status={3}, days={4}, created_before_date={5}'
.format(rule.id, rule.prefix, rule.tagging, rule.status,
rule.expiration.days,
rule.expiration.created_before_date))
# Query the rules that convert the storage class of an object.
if len(rule.storage_transitions) > 0:
storage_trans_info = ''
for storage_rule in rule.storage_transitions:
storage_trans_info += 'days={0}, created_before_date={1}, storage_class={2} **** '.format(
storage_rule.days, storage_rule.created_before_date, storage_rule.storage_class)
print('id={0}, prefix={1}, tagging={2}, status={3},, StorageTransition={4}'
.format(rule.id, rule.prefix, rule.tagging, rule.status, storage_trans_info))
Referências
Para obter o código de exemplo completo de gerenciamento de regras de ciclo de vida, visite o GitHub.
Para obter mais informações sobre a operação de API usada para configurar regras de ciclo de vida, consulte PutBucketLifecycle.
Para obter mais informações sobre a operação de API usada para consultar regras de ciclo de vida, consulte GetBucketLifecycle.