Todos os produtos
Search
Central de documentação

Object Storage Service:Bucket-level retention policy (BucketWorm)

Última atualização: Jul 03, 2026

O BucketWorm aplica o modelo Write Once, Read Many (WORM) a um bucket do OSS, tornando todos os objetos imutáveis durante um período de retenção especificado. Nesse período, os objetos podem ser carregados e lidos, mas nenhum usuário, incluindo o proprietário do bucket, pode modificá-los ou excluí-los.

Casos de uso

As políticas de retenção do OSS ajudam a atender aos requisitos regulatórios de órgãos como SEC e FINRA. Os casos de uso típicos incluem arquivamento para conformidade e auditoria de dados de log nos setores financeiro, de seguros, saúde e valores mobiliários.

Nota

O OSS possui acreditação da Cohasset Associates e atende aos requisitos de retenção de registros eletrônicos, incluindo a Regra 17a-4(f) da SEC, a Regra 4511 da FINRA e a Regra 1.31 da Commodity Futures Trading Commission (CFTC). Relatório de Avaliação do OSS pela Cohasset.

Pré-requisitos

O versionamento deve estar ativado ou desativado para o bucket, não suspenso. Versionamento.

Observações de uso

  • Não é possível ativar o OSS-HDFS e configurar uma política de retenção no nível do bucket para o mesmo bucket simultaneamente.

  • Durante o período de retenção, você pode configurar uma regra de ciclo de vida para fazer a transição dos objetos para uma classe de armazenamento diferente, reduzindo custos de armazenamento e mantendo a conformidade.

  • A política de retenção no nível do bucket (BucketWorm) e a política de retenção no nível do objeto (ObjectWorm) são mutuamente exclusivas. Não é possível ativar ambas no mesmo bucket.

Como funciona

  • Regra de ativação

    Ao ser criada, a política de retenção entra no estado InProgress por 24 horas. Os recursos do bucket ficam protegidos durante esse período.

    • Dentro de 24 horas após a criação

      • Se não estiver bloqueada, o proprietário do bucket e usuários autorizados podem excluir a política.

      • Após o bloqueio, a política não pode ser excluída nem encurtada, apenas estendida. Tentativas de excluir ou modificar dados protegidos retornam 409 FileImmutable.

    • Após 24 horas

      Caso não seja bloqueada dentro de 24 horas, a política expira e pode ser excluída.

  • Regra de exclusão

    • Uma política de retenção é um atributo de metadados do bucket. A exclusão do bucket também remove sua política.

    • Se a política não for bloqueada dentro de 24 horas após a criação, o proprietário do bucket e usuários autorizados poderão excluí-la.

    • Não é possível excluir a política ou o bucket enquanto houver objetos dentro do período de retenção.

  • Exemplo

    Suponha que você crie e bloqueie uma política de retenção de 30 dias em 1º de junho de 2022 e carregue três objetos em momentos diferentes:

    Nome do objeto

    Hora do upload

    Hora de expiração

    file1.txt

    1º de abril de 2022

    30 de abril de 2022

    file2.txt

    1º de junho de 2022

    30 de junho de 2022

    file3.txt

    1º de setembro de 2022

    30 de setembro de 2022

Procedimento

OSS console

  1. Crie uma política de retenção.

    1. Faça login no OSS console.

    2. No painel de navegação à esquerda, clique em Buckets. Na página Buckets, clique no nome do bucket desejado.

    3. No painel de navegação à esquerda, escolha Content Security > Bucket-level Retention Policy.

    4. Na página Retention Policy, clique em Create Policy.

    5. Na caixa de diálogo Create Policy, especifique o Retention Period.

      Nota

      O período de retenção é medido em dias. Valores válidos: 1 a 25.550.

    6. Clique em OK.

      Nota

      A política entra no estado InProgress por 24 horas, período em que os recursos do bucket ficam protegidos. É possível excluir a política dentro dessa janela.

  2. Bloqueie a política de retenção.

    1. Clique em Lock.

    2. Na caixa de diálogo exibida, clique em OK.

      Importante

      Após o bloqueio, a política não pode ser modificada nem excluída, e os dados no bucket tornam-se imutáveis durante o período de retenção.

  3. (Opcional) Modifique o período de retenção.

    1. Clique em Edit.

    2. Na caixa de diálogo exibida, modifique o período de retenção.

      Importante

      É possível apenas estender o período de retenção, não encurtá-lo.

Alibaba Cloud SDKs

Os códigos a seguir configuram políticas de retenção com SDKs comuns. Outros SDKs estão abordados na Visão geral do SDK.

Java

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.InitiateBucketWormRequest;
import com.aliyun.oss.model.InitiateBucketWormResult;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 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. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        // Call the shutdown method to release resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Create an InitiateBucketWormRequest object. 
            InitiateBucketWormRequest initiateBucketWormRequest = new InitiateBucketWormRequest(bucketName);
            // Set the retention period to 1 day. 
            initiateBucketWormRequest.setRetentionPeriodInDays(1);

            // Create a retention policy. 
            InitiateBucketWormResult initiateBucketWormResult = ossClient.initiateBucketWorm(initiateBucketWormRequest);

            // Display the ID of the retention policy. 
            String wormId = initiateBucketWormResult.getWormId();
            System.out.println(wormId);
        } 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();
            }
        }
    }
}

PHP

<?php

// Import the autoloader file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define command line argument descriptions.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // Required. The region where the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // Optional. The domain name that other services can use to access OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // Required. The name of the bucket.
];

// Generate a long options list to parse command line arguments.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after each argument to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts); 

// Check if any required arguments are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Prompt the user that a required argument is missing.
        exit(1); 
    }
}

// Get the command line argument values.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Load credential information, such as AccessKey ID and AccessKey secret, from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the software development kit (SDK).
$cfg = Oss\Config::loadDefault();

// Set the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Set the region.
$cfg->setRegion($region);

// If an endpoint is provided, set the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a request object to initialize the retention policy for the bucket. Set the retention period to 3 days.
$request = new Oss\Models\InitiateBucketWormRequest(
    bucket: $bucket, 
    initiateWormConfiguration: new Oss\Models\InitiateWormConfiguration(
        retentionPeriodInDays: 3 // The retention period in days.
));

// Call the initiateBucketWorm method to initialize the retention policy for the bucket.
$result = $client->initiateBucketWorm($request);

// Print the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
    'request id:' . $result->requestId . PHP_EOL . // The unique ID of the request.
    'worm id:' . $result->wormId // The ID of the retention policy.
);

Node.js

const OSS = require('ali-oss');

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,  
  authorizationV4: true,
  // Set bucket to your bucket name.
  bucket: 'yourBucketName',
});
// Create a data retention policy.
async function initiateBucketWorm() {
 // Set bucket to your bucket name.
  const bucket = 'yourbucketname'
  // Specify the retention period in days.
  const days = '<Retention Days>'
    const res = await client.initiateBucketWorm(bucket, days)
  console.log(res.wormId)
}

initiateBucketWorm()

Python

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the script's purpose: This sample shows how to initialize the WORM configuration for an OSS bucket.
parser = argparse.ArgumentParser(description="initiate bucket worm sample")

# Add the --region command-line argument, which specifies the bucket region. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the bucket name. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --retention_period_in_days command-line argument, which specifies the retention period in days. This argument is required.
parser.add_argument('--retention_period_in_days', help='The number of days for which objects can be retained.', required=True)

def main():
    # Parse the command-line arguments to get the user-provided values.
    args = parser.parse_args()

    # Load the access credentials for OSS from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the SDK's default configurations and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client with the configuration to interact with OSS.
    client = oss.Client(cfg)

    # Send a request to initialize the WORM configuration for the specified bucket.
    result = client.initiate_bucket_worm(oss.InitiateBucketWormRequest(
        bucket=args.bucket,  # Bucket name.
        initiate_worm_configuration=oss.InitiateWormConfiguration(
            retention_period_in_days=int(args.retention_period_in_days),  # Retention period in days, converted to an integer.
        ),
    ))

    # Print the status code, request ID, and WORM ID of the operation to confirm the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' worm id: {result.worm_id}'
    )

# When this script is run directly, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # Script entry point, where the program flow starts.

Go

package main

import (
	"log"

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

func main() {
	// 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 set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	// Specify the name of the bucket for which you want to configure a retention policy.
	bucketName := "<yourBucketName>"

	// Set the retention period for objects to 1 day.
	result, err := client.InitiateBucketWorm(bucketName, 1)
	if err != nil {
		log.Fatalf("Error initiating bucket WORM: %v", err)
	}

	log.Println("WORM policy initiated successfully:", result)
}

C++

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set Region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Enter the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";

      /* Initialize resources such as the network. */
      InitializeSdk();

      ClientConfiguration conf;
      conf.signatureVersion = SignatureVersionType::V4;
      /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
  
      /* Create a data retention policy and set the object protection period to 1 day. */
      auto outcome = client.InitiateBucketWorm(InitiateBucketWormRequest(BucketName, 1));

      if (outcome.isSuccess()) {      
            std::cout << " InitiateBucketWorm success " << std::endl;
            std::cout << "WormId:" << outcome.result().WormId() << std::endl;
      }
      else {
        /* Handle the exception. */
        std::cout << "InitiateBucketWorm fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
      }

      /* Release resources such as the network. */
      ShutdownSdk();
      return 0;
}

ossutil

É possível criar uma política WORM com o ossutil. Para configurar a ferramenta, siga Instalar o ossutil.

O comando a seguir cria uma política WORM no examplebucket com um período de retenção de 365 dias.

ossutil api initiate-bucket-worm --bucket examplebucket --initiate-worm-configuration "{\"RetentionPeriodInDays\":\"365\"}"

Referência do comando: initiate-bucket-worm.

Referência da API

Para personalizações avançadas, chame a REST API diretamente. Isso requer cálculo manual de assinatura. InitiateBucketWorm.

Uso com versionamento

Para permitir atualizações contínuas de dados mantendo todas as versões históricas imutáveis — cenário comum em proteção de backups, rastreamento de ativos e conformidade financeira —, ative tanto o versionamento quanto uma política de retenção no mesmo bucket. O versionamento preserva versões antigas quando objetos são sobrescritos ou excluídos; já a política de retenção impede que qualquer versão seja modificada ou excluída durante o período de retenção.

Quando ambos os recursos estão ativados:

  • Ordem de ativação: Não há restrição de ordem. Ative o versionamento e as políticas de retenção em qualquer sequência.

  • Restrições de transição de estado:

    • Após a ativação de uma política de retenção, não é possível alterar o estado do versionamento de ativado para suspenso.

    • É possível ativar uma política de retenção para um bucket com versionamento suspenso. Depois que a política for ativada, você poderá alterar o estado do versionamento para ativado.

  • Proteção de versões de objetos:

    • Uma política de retenção protege todas as versões de um objeto. Nenhuma versão pode ser excluída ou modificada durante o período de retenção.

    • É possível carregar um objeto com o mesmo nome para criar uma nova versão. A nova versão também fica protegida pela política de retenção.

    • A política de retenção não protege marcadores de exclusão, portanto, a exclusão deles não é restringida pela política.

  • Sinergia com replicação de dados:

    • Tanto os buckets de origem quanto os de destino suportam configurações independentes para versionamento e políticas de retenção.

    • As informações de versão são transmitidas normalmente durante a replicação. O bucket de destino gerencia as versões com base em sua própria configuração.

    • A exclusão de uma versão no bucket de origem não é sincronizada com um bucket de destino que tenha uma política de retenção ativada.

Perguntas frequentes

Exclusão de objetos com versionamento

Quando uma política de retenção e o versionamento estão ambos ativados, a exclusão de um objeto gera os seguintes efeitos:

  • A operação de exclusão cria um marcador de exclusão, mas não remove fisicamente as versões históricas do objeto.

  • Uma política de retenção não protege marcadores de exclusão, que podem ser removidos normalmente.

  • Nenhuma versão do objeto pode ser excluída durante o período de retenção, mesmo que exista um marcador de exclusão.

  • O gerenciamento de ciclo de vida pode limpar marcadores de exclusão órfãos, mas não consegue excluir versões de objetos protegidas por uma política de retenção.

Modificação do estado de versionamento

Após a ativação de uma política de retenção, aplicam-se as seguintes restrições à modificação do estado de versionamento:

  • De ativado para suspenso: Se o estado do versionamento estiver ativado, não será possível alterá-lo para suspenso após o bloqueio da política de retenção.

  • De suspenso para ativado: Se o estado do versionamento estiver suspenso, ainda será possível alterá-lo para ativado após a ativação da política de retenção.

  • De desativado para ativado: Para um bucket com versionamento desativado, é possível ativar o versionamento após configurar uma política de retenção.

Custos de armazenamento

Sim, das seguintes formas:

  • Todas as versões dos objetos são retidas durante o período de retenção e não podem ser excluídas por uma regra de ciclo de vida.

  • O acúmulo de versões pode aumentar significativamente o uso de armazenamento, especialmente para objetos atualizados frequentemente.

  • Defina um período de retenção adequado e utilize regras de ciclo de vida para fazer a transição entre classes de armazenamento e reduzir custos.

Benefícios de uma política de retenção

Uma política de retenção oferece imutabilidade com grau de conformidade. Dados protegidos apenas por uma política do RAM ou Bucket Policy ainda podem ser modificados ou excluídos.

Quando usar uma política de retenção

Ative uma política de retenção para dados que devem permanecer inalterados a longo prazo, como prontuários médicos, documentos técnicos ou contratos.

Exclusão de uma política de retenção

A possibilidade de excluir uma política de retenção depende do seu estado:

  • Não bloqueada: O proprietário do bucket e usuários autorizados podem excluir a política.

  • Bloqueada: Nenhum usuário pode excluir a política.

Política no nível do objeto

O BucketWorm aplica-se a buckets inteiros, não a diretórios ou objetos individuais. Para definir retenção em um único objeto, use uma política de retenção no nível do objeto (ObjectWorm). BucketWorm e ObjectWorm são mutuamente exclusivos no mesmo bucket.

Cálculo do tempo de retenção

Tempo de retenção = hora da última modificação + período de retenção. Por exemplo, com uma política de 10 dias, um objeto modificado pela última vez em 15 de fevereiro de 2022 será retido até 25 de fevereiro de 2022.

Exclusão de um bucket protegido

  • Se o bucket não contiver objetos, você poderá excluí-lo diretamente.

  • Caso o bucket contenha objetos cujos períodos de retenção tenham expirado, será necessário excluir todos os objetos antes de excluir o bucket.

  • Se o bucket contiver objetos ainda dentro do período de retenção, não será possível excluí-lo.

Pagamentos em atraso e retenção de dados

Importante: Um pagamento em atraso pode levar a Alibaba Cloud a excluir dados conforme as regras de suspensão de serviço, mesmo para objetos protegidos por uma política de retenção.

Autorização de usuários RAM

Sim. O gerenciamento de políticas de retenção suporta autorização RAM. Usuários RAM autorizados podem gerenciar políticas por meio do OSS console, APIs ou SDKs.