Todos os produtos
Search
Central de documentação

Object Storage Service:Enable versioning for data restoration and version control

Última atualização: Sep 09, 2026

O versionamento protege dados no nível do bucket ao preservar versões históricas de objetos quando eles são sobrescritos ou excluídos, permitindo restaurar qualquer objeto para uma versão anterior.

Casos de uso

Use o versionamento nos cenários a seguir para proteger seus dados.

  • Exclusão acidental de dados

    Como o OSS não possui lixeira, o versionamento é a principal forma de recuperar dados excluídos acidentalmente.

  • Sobrescrita de arquivos

    Para arquivos modificados frequentemente (unidades de cloud, ferramentas colaborativas), o versionamento permite recuperar qualquer versão anterior.

Observações de uso

  • Faturamento

    O versionamento em si é gratuito. No entanto, todas as versões de objetos (atuais e históricas) geram custos de armazenamento. Use regras de ciclo de vida para excluir automaticamente versões históricas desnecessárias. Para mais informações, consulte Lifecycle rules. Solicitações e tráfego decorrentes do download ou da restauração de versões históricas também são cobrados. Metering and billing. Para interromper completamente todas as cobranças do OSS, exclua todos os dados no bucket (incluindo objetos, partes e versões anteriores) e o próprio bucket. Para mais informações, consulte Delete a bucket to stop billing.

  • Permissões

    Apenas o proprietário do bucket e usuários do Resource Access Management (RAM) com a permissão PutBucketVersioning podem configure o versionamento.

  • Recursos mutuamente exclusivos

    Se o versionamento de um bucket estiver ativado ou suspenso:

    • A regra que proíbe a sobrescrita de objetos não entra em vigor. Prohibit overwrites of objects.

    • O cabeçalho de solicitação x-oss-forbid-overwrite, usado para impedir a sobrescrita de objetos, não tem efeito durante uploads. Para mais informações, consulte PutObject.

  • Versionamento e OSS-HDFS

    Não ative o service OSS-HDFS e o versionamento no mesmo bucket. Isso pode causar instabilidade no service. Para garantir uma operação estável, suspenda o versionamento o mais rápido possível e configure uma regra de ciclo de vida para limpar marcadores de exclusão.

Estados de versionamento

O versionamento de um bucket pode estar em um dos três estados: Desativado (padrão), Ativado ou Suspenso.

  • Por padrão, o versionamento está desativado para um bucket. Uma vez ativado, o versionamento não pode retornar ao estado Desativado. Ele só pode ser suspenso.

  • Quando o versionamento está ativado, o OSS retém versões históricas dos objetos. Para mais informações, consulte Manage versioned objects.

  • Quando o versionamento está suspenso, um objeto recém-carregado substitui a versão atual de um objeto com o mesmo nome. As versões históricas existentes são mantidas. Para mais informações, consulte Manage objects in a versioning-suspended bucket.

Nota

Todas as versões de objetos geram custos de armazenamento. Use regras de ciclo de vida para mover versões para classes de armazenamento de menor custo (como Acesso Pouco Frequente ou Arquivo) ou excluir versões históricas desnecessárias. Para mais informações, consulte Reduce storage costs by combining lifecycle rules based on the last modified time with versioning.

Proteção de dados

A tabela a seguir descreve como o comportamento de sobrescrita e exclusão de objetos difere entre os estados de versionamento.

Estado de versionamento

Sobrescrever um objeto

Excluir um objeto

Desativado

O objeto existente é sobrescrito e não pode ser restaurado. É possível recuperar apenas a versão mais recente do objeto.

O objeto é excluído permanentemente e não pode ser recuperado.

Ativado

Uma nova versão é criada. As versões históricas não são afetadas.

O objeto é marcado como excluído. As versões históricas não são afetadas e podem ser restauradas.

Suspenso

Uma nova versão é criada. Se já existir uma versão do mesmo objeto do período de suspensão, a nova versão a substituirá. Outras versões históricas não são afetadas.

O objeto é marcado como excluído. Se já existir um marcador de exclusão para o mesmo objeto do período de suspensão, o novo marcador o substituirá. Outras versões históricas não são afetadas.

Ativar versionamento

Usar o console do OSS

Quando o versionamento é ativado para um bucket, o OSS atribui um ID exclusivo para cada versão de um objeto armazenado no bucket.

  • Ative o versionamento ao criar um bucket.

    1. Faça login no console do OSS.

    2. Clique em Buckets e, em seguida, clique em Create Bucket.

    3. Na página Create Bucket, configure os parâmetros.

      Na seção Versioning, defina a chave Versioning como On. Por padrão, este recurso está Off. Para mais informações sobre outros parâmetros, consulte Create a bucket.

    4. Clique em Create.

  • Ative o versionamento para um bucket existente.

    1. No painel de navegação à esquerda, clique em Buckets. Na página Buckets, localize e clique no bucket desejado.

    2. No painel de navegação à esquerda, escolha Content Security > Versioning.

    3. Na página Versioning, clique em Enable Now.

    4. Na caixa de diálogo exibida, clique em Confirm On.

Após ativar o versionamento, na página Objects, clique em Show ao lado de Previous Versions para visualizar todas as versões de arquivos. Para ver apenas as versões atuais dos arquivos, clique em Hide ao lado de Previous Versions. Ocultar versões anteriores não melhora o desempenho da listagem de arquivos. Se a página responder lentamente ao listar arquivos, consulte Slow response speed para solucionar o problema.

Usar SDKs da Alibaba Cloud

Os exemplos a seguir mostram como ativar o versionamento usando vários SDKs. Introduction to SDKs.

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Set the endpoint. Use China (Hangzhou) as an example. Set the endpoint to the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region where the bucket is located, for example, cn-hangzhou.
        String region = "cn-hangzhou";
        // 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 bucket name, for example, examplebucket.
        String bucketName = "examplebucket";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare that the V4 signature algorithm is used.
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Enable versioning.
            BucketVersioningConfiguration configuration = new BucketVersioningConfiguration();
            configuration.setStatus(BucketVersioningConfiguration.ENABLED);
            SetBucketVersioningRequest request = new SetBucketVersioningRequest(bucketName, configuration);
            ossClient.setBucketVersioning(request);
        } 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
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// 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.
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// Set the endpoint. Use Hangzhou as an example. Set the endpoint to the actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "yourBucketName";

$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

try {
    // Enable versioning.
    $ossClient->putBucketVersioning($bucket, "Enabled");
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}

print(__FUNCTION__ . ": OK" . "\n");
const OSS = require("ali-oss");

const client = new OSS({
  // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: "oss-cn-hangzhou",
  // 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.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the bucket name, for example, examplebucket.
  bucket: "examplebucket",
});

async function putBucketVersioning() {
  // Enable versioning.
  const status = "Enabled";
  const result = await client.putBucketVersioning("examplebucket", status);
  console.log(result);
}
putBucketVersioning();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import BucketVersioningConfig
# 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.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint based on the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Set yourBucketName to the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')

# Create a bucket versioning configuration.
config = BucketVersioningConfig()
# Enable versioning.
config.status = oss2.BUCKET_VERSIONING_ENABLE

result = bucket.put_bucket_versioning(config)
# View the HTTP status code.
print('http response code:', result.status)
using Aliyun.OSS;
using Aliyun.OSS.Common;

// 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. 
var endpoint = "yourEndpoint";
// 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. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var 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.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify parameters as required.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Set the versioning status of the bucket to Enabled. 
    client.SetBucketVersioning(new SetBucketVersioningRequest(bucketName, VersioningStatus.Enabled));
    Console.WriteLine("Create bucket Version succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Create bucket Version failed. {0}", ex.Message);
}
package main

import (
  "fmt"
  "os"

  "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 configured.
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance.
    // Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Set the endpoint to the actual endpoint.
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
       fmt.Println("Error:", err)
       os.Exit(-1)
  }

  // Create a bucket.
  // Set yourBucketName to the name of the bucket.
  err = client.CreateBucket("yourBucketName")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
  // The following code provides an example of how to set the versioning state of a bucket to Enabled.
  config := oss.VersioningConfig{Status: "Enabled"}
  err = client.SetBucketVersioning("yourBucketName", config)
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

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

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* 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. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    /* Create a bucket versioning configuration and set the status to Enabled. */
    SetBucketVersioningRequest setrequest(BucketName, VersioningStatus::Enabled);
    auto outcome = client.SetBucketVersioning(setrequest);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetBucketVersioning fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

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

Usar a interface de linha de comando ossutil

Use o ossutil para definir o estado de versionamento de um bucket. Para obter informações sobre como instalar o ossutil, consulte Install ossutil.

O comando a seguir ativa o versionamento para um bucket especificado.

ossutil api put-bucket-versioning --bucket examplebucket --versioning-configuration "{\"Status\":\"Enabled\"}"

Para mais informações sobre este comando, consulte put-bucket-versioning.

Suspender versionamento

Se uma política de retenção estiver ativada para um bucket, não será possível alterar o estado de versionamento de Ativado para Suspenso. No entanto, é possível alterar o estado de Suspenso para Ativado.

Usar o console do OSS

É possível suspender o versionamento de um bucket versionado para impedir que o OSS gere novas versões para objetos. Se uma nova versão for gerada para um objeto em um bucket com versionamento suspenso, o OSS definirá o ID da nova versão como nulo e reterá as versões anteriores do objeto.

Para suspender o versionamento de um bucket, execute as etapas a seguir:

  1. No painel de navegação à esquerda, clique em Buckets. Na página Buckets, localize e clique no bucket desejado.

  2. No painel de navegação à esquerda, escolha Content Security > Versioning.

  3. Na página Versioning, clique em Suspend.

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

Usar SDKs da Alibaba Cloud

Os exemplos a seguir mostram como suspender o versionamento usando SDKs comuns. Introduction to SDKs.

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

public class Demo {
    public static void main(String[] args) throws Exception {
        // Set the endpoint. Use China (Hangzhou) as an example. Set the endpoint to the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region where the bucket is located, for example, cn-hangzhou.
        String region = "cn-hangzhou";
        // 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 bucket name, for example, examplebucket.
        String bucketName = "examplebucket";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Explicitly declare that the V4 signature algorithm is used.
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Suspend versioning.
            BucketVersioningConfiguration configuration = new BucketVersioningConfiguration();
            configuration.setStatus(BucketVersioningConfiguration.SUSPENDED);
            SetBucketVersioningRequest request = new SetBucketVersioningRequest(bucketName, configuration);
            ossClient.setBucketVersioning(request);
        } 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
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\OssClient;
use OSS\Core\OssException;

// 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.
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// Set the endpoint. Use Hangzhou as an example. Set the endpoint to the actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "yourBucketName";

$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

try {
    // Suspend versioning.
    $ossClient->putBucketVersioning($bucket, "Suspended");
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}

print(__FUNCTION__ . ": OK" . "\n");
const OSS = require("ali-oss");

const client = new OSS({
  // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: "oss-cn-hangzhou",
  // 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.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the bucket name, for example, examplebucket.
  bucket: "examplebucket",
});

async function putBucketVersioning() {
  // Suspend versioning.
  const status = "Suspended";
  const result = await client.putBucketVersioning("examplebucket", status);
  console.log(result);
}
putBucketVersioning();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import BucketVersioningConfig
# 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.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint based on the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Set yourBucketName to the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')

# Create a bucket versioning configuration.
config = BucketVersioningConfig()
# Suspend versioning.
config.status = oss2.BUCKET_VERSIONING_SUSPEND

result = bucket.put_bucket_versioning(config)
# View the HTTP status code.
print('http response code:', result.status)
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// 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.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name, for example, examplebucket.
var bucketName = "examplebucket";
// Configure the client to use V4 signature.
var conf = new ClientConfiguration();
conf.SignatureVersion = SignatureVersion.V4;
// Initialize the OSSClient with V4 signature.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
try
{
    // Set the versioning state of the bucket to Suspended.
    client.SetBucketVersioning(new SetBucketVersioningRequest(bucketName, VersioningStatus.Suspended));
    Console.WriteLine("SetBucketVersioning succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("SetBucketVersioning failed. {0}", ex.Message);
}
package main

import (
  "fmt"
  "os"

  "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 configured.
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance.
    // Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Set the endpoint to the actual endpoint.
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
       fmt.Println("Error:", err)
       os.Exit(-1)
  }

  // Create a bucket.
  // Set yourBucketName to the name of the bucket.
  err = client.CreateBucket("yourBucketName")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
  // Suspend versioning.
  config := oss.VersioningConfig{Status: "Suspended"}
  err = client.SetBucketVersioning("yourBucketName", config)
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

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

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    /* 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. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    /* Create a bucket versioning configuration and set the status to Suspended. */
    SetBucketVersioningRequest setrequest(BucketName, VersioningStatus::Suspended);
    auto outcome = client.SetBucketVersioning(setrequest);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetBucketVersioning fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

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

Usar a interface de linha de comando ossutil

Use o ossutil para definir o estado de versionamento de um bucket. Para obter informações sobre como instalar o ossutil, consulte Install ossutil.

O comando a seguir suspende o versionamento para um bucket especificado.

ossutil api put-bucket-versioning --bucket examplebucket --versioning-configuration "{\"Status\":\"Suspended\"}"

Para mais informações sobre este comando, consulte put-bucket-versioning.

Visualizar versões

Use o ossutil para visualizar todas as versões de um objeto. Para obter informações sobre como instalar o ossutil, consulte Install ossutil.

O comando a seguir lista informações sobre todas as versões de todos os objetos no bucket examplebucket.

ossutil api list-object-versions --bucket examplebucket

Para mais informações sobre este comando, consulte list-object-versions.

Restaurar uma versão

Usar o console do OSS

Ao excluir um objeto de um bucket com versionamento ativado, o objeto não é excluído permanentemente. Em vez disso, ele é marcado como excluído. É possível restaurar uma versão anterior no console.

  1. No painel de navegação à esquerda, clique em Buckets. Na página Buckets, localize e clique no bucket desejado.

  2. No painel de navegação à esquerda, escolha Object Management > Objects.

  3. Clique em Show ao lado de Previous Versions.

  4. Selecione a versão que deseja restaurar e clique em Restore na parte inferior da página.

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

Usar a interface de linha de comando ossutil

Use o ossutil para restaurar uma versão histórica de um arquivo excluído. Para obter informações sobre como instalar o ossutil, consulte Install ossutil.

O comando a seguir restaura o objeto example.txt no bucket examplebucket para a versão 123.

ossutil revert oss://examplebucket/example.txt 123

Para mais informações sobre este comando, consulte revert.

Operações de API relacionadas

As operações anteriores são implementadas com base em operações de API. Se o seu programa tiver requisitos de personalização elevados, chame diretamente as operações da API REST. Observe que você deve escrever manualmente o código para calcular assinaturas. Para mais informações, consulte PutBucketVersioning.

Trabalhar com políticas de retenção

Em cenários como proteção de backup (Veeam), rastreamento de alterações de ativos (diagramas de projetos de circuitos) ou arquivamento de conformidade (finanças), pode ser necessário permitir atualizações de dados mantendo todas as versões históricas imutáveis. Ative tanto o versionamento quanto uma política de retenção: o versionamento preserva versões históricas na sobrescrita ou exclusão, e a política de retenção impede que qualquer versão seja excluída ou modificada durante o período de proteção.

O versionamento e as políticas de retenção funcionam juntos com base nos seguintes princípios:

  • Ordem de ativação dos recursos: É possível ativar o versionamento e as políticas de retenção em qualquer ordem.

  • Configurações permitidas:

    • Política de retenção + Versionamento desativado

    • Política de retenção + Versionamento ativado

  • Restrições:

    • Não é possível ativar uma política de retenção para um bucket cujo versionamento esteja suspenso.

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

      • Não é possível alterar o estado de Ativado para Suspenso.

      • Não é possível alterar o estado de Desativado para Suspenso.

  • Mecanismo de proteção de versão de objeto:

    • A 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 proteção.

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

    • A política de retenção não se aplica a marcadores de exclusão. A limpeza de marcadores de exclusão não é restringida pela política de retenção.

  • Interação com replicação de dados:

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

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

    • A tentativa de excluir uma versão replicada no bucket de destino falhará se ela estiver protegida por uma política de retenção, mas terá êxito após a expiração da política.

  • Referências