Object Storage Service:Enable versioning for data restoration and version control
Última actualización: Sep 09, 2026
El control de versiones protege los datos a nivel de bucket al conservar las versiones históricas de los objetos cuando se sobrescriben o eliminan. Esto le permite restaurar cualquier objeto a una versión anterior.
Casos de uso
Utilice el control de versiones en los siguientes escenarios para proteger sus datos.
Eliminación accidental de datos
Dado que OSS no cuenta con una papelera de reciclaje, el control de versiones es el método principal para recuperar datos eliminados por accidente.
Sobrescritura de archivos
En archivos que se modifican con frecuencia (unidades en la nube, herramientas colaborativas), esta función le permite recuperar cualquier versión anterior.
Notas de uso
Facturación
El control de versiones en sí mismo es gratuito. Sin embargo, todas las versiones de los objetos (actuales e históricas) generan cargos de almacenamiento. Utilice reglas de ciclo de vida para eliminar automáticamente las versiones históricas que ya no necesite. Para obtener más información, consulte Lifecycle rules. Las solicitudes y el tráfico generados al descargar o restaurar versiones históricas también se facturan. Metering and billing. Para detener por completo todos los cargos de OSS, elimine todos los datos del bucket (incluidos objetos, partes y versiones anteriores) y el bucket mismo. Para obtener más información, consulte Delete a bucket to stop billing.
Permisos
Solo el propietario del bucket y los usuarios de Resource Access Management (RAM) con el permiso PutBucketVersioning pueden configurar el control de versiones.
Funciones mutuamente excluyentes
Si el control de versiones de un bucket está habilitado o suspendido:
El encabezado de solicitud x-oss-forbid-overwrite, que evita que un objeto se sobrescriba, no surte efecto durante las cargas. Para obtener más información, consulte PutObject.
Control de versiones y OSS-HDFS
No habilite el servicio OSS-HDFS y el control de versiones en el mismo bucket, ya que esto puede provocar inestabilidad en el servicio. Para garantizar un funcionamiento estable, suspenda el control de versiones lo antes posible y configure una regla de ciclo de vida para limpiar los marcadores de eliminación.
Estados del control de versiones
El control de versiones de un bucket puede encontrarse en uno de tres estados: Disabled (predeterminado), Enabled o Suspended.
De forma predeterminada, el control de versiones de un bucket está deshabilitado. Una vez habilitado, no puede volver al estado Disabled; únicamente se puede suspender.
Cuando el control de versiones está habilitado, OSS conserva las versiones históricas de los objetos. Para obtener más información, consulte Manage versioned objects.
Cuando el control de versiones está suspendido, un objeto recién cargado reemplaza la versión actual de un objeto con el mismo nombre. Las versiones históricas existentes se conservan. Para obtener más información, consulte Manage objects in a versioning-suspended bucket.
Nota
Todas las versiones de los objetos generan costos de almacenamiento. Utilice reglas de ciclo de vida para transferir las versiones a clases de almacenamiento de menor costo (como Infrequent Access o Archive) o para eliminar las versiones históricas innecesarias. Para obtener más información, consulte Reduce storage costs by combining lifecycle rules based on the last modified time with versioning.
Protección de datos
A continuación se describe cómo varía el comportamiento de sobrescritura y eliminación de objetos según el estado del control de versiones.
Estado del control de versiones
Sobrescribir un objeto
Eliminar un objeto
Disabled
El objeto existente se sobrescribe y no se puede restaurar. Solo es posible recuperar la versión más reciente del objeto.
El objeto se elimina de forma permanente y no se puede recuperar.
Enabled
Se crea una nueva versión. Las versiones históricas no se ven afectadas.
El objeto se marca como eliminado. Las versiones históricas no se ven afectadas y se pueden restaurar.
Suspended
Se crea una nueva versión. Si ya existe una versión del mismo objeto generada durante el periodo de suspensión, la nueva versión la sobrescribe. Las demás versiones históricas no se ven afectadas.
El objeto se marca como eliminado. Si ya existe un marcador de eliminación para el mismo objeto generado durante el periodo de suspensión, el nuevo marcador lo sobrescribe. Las demás versiones históricas no se ven afectadas.
Habilitar el control de versiones
Usar la consola de OSS
Cuando se habilita el control de versiones para un bucket, OSS asigna un identificador único a cada versión de un objeto almacenado en dicho bucket.
Habilite el control de versiones al crear un bucket.
Haga clic en Buckets y luego haga clic en Create Bucket.
En la página Create Bucket, configure los parámetros.
En la sección Versioning, establezca el interruptor Versioning en On. De forma predeterminada, esta función está en Off. Para obtener más información sobre los demás parámetros, consulte Create a bucket.
Haga clic en Create.
Habilite el control de versiones para un bucket existente.
En el panel de navegación izquierdo, haga clic en Buckets. En la página Buckets, busque el bucket deseado y haga clic en él.
En el panel de navegación izquierdo, elija Content Security > Versioning.
En la página Versioning, haga clic en Enable Now.
En el cuadro de diálogo que aparece, haga clic en Confirm On.
Una vez habilitado el control de versiones, vaya a la página Objects y haga clic en Show junto a Previous Versions para consultar todas las versiones de los archivos. Si desea ver solo las versiones actuales, haga clic en Hide junto a Previous Versions. Ocultar las versiones anteriores no mejora el rendimiento al listar archivos. Si la página responde lentamente al listar archivos, consulte Slow response speed para solucionar el problema.
Usar los SDK de Alibaba Cloud
A continuación se muestra cómo habilitar el control de versiones mediante diversos SDK. 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 la interfaz de línea de comandos de ossutil
Utilice ossutil para establecer el estado del control de versiones de un bucket. Para obtener información sobre cómo instalar ossutil, consulte Install ossutil.
El siguiente comando habilita el control de versiones para un bucket específico.
ossutil api put-bucket-versioning --bucket examplebucket --versioning-configuration "{\"Status\":\"Enabled\"}"
Si un bucket tiene habilitada una directiva de retención, no es posible cambiar el estado del control de versiones de Enabled a Suspended. No obstante, sí se puede cambiar de Suspended a Enabled.
Usar la consola de OSS
Puede suspender el control de versiones de un bucket para evitar que OSS genere nuevas versiones de los objetos. Si se genera una nueva versión de un objeto en un bucket con el control de versiones suspendido, OSS establece el identificador de dicha versión como null y conserva las versiones anteriores del objeto.
Siga estos pasos para suspender el control de versiones de un bucket:
En el panel de navegación izquierdo, haga clic en Buckets. En la página Buckets, busque el bucket deseado y haga clic en él.
En el panel de navegación izquierdo, elija Content Security > Versioning.
En la página Versioning, haga clic en Suspend.
En el cuadro de diálogo que aparece, haga clic en OK.
Usar los SDK de Alibaba Cloud
A continuación se muestra cómo suspender el control de versiones mediante los SDK más comunes. 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 la interfaz de línea de comandos de ossutil
Utilice ossutil para establecer el estado del control de versiones de un bucket. Para obtener información sobre cómo instalar ossutil, consulte Install ossutil.
El siguiente comando suspende el control de versiones para un bucket específico.
ossutil api put-bucket-versioning --bucket examplebucket --versioning-configuration "{\"Status\":\"Suspended\"}"
Cuando elimina un objeto de un bucket con el control de versiones habilitado, el objeto no se elimina de forma permanente, sino que se marca como eliminado. Puede restaurar una versión anterior desde la consola.
En el panel de navegación izquierdo, haga clic en Buckets. En la página Buckets, busque el bucket deseado y haga clic en él.
En el panel de navegación izquierdo, elija Object Management > Objects.
Haga clic en Show junto a Previous Versions.
Seleccione la versión que desea restaurar y haga clic en Restore en la parte inferior de la página.
En el cuadro de diálogo que aparece, haga clic en OK.
Usar la interfaz de línea de comandos de ossutil
Utilice ossutil para restaurar una versión histórica de un archivo eliminado. Para obtener información sobre cómo instalar ossutil, consulte Install ossutil.
El siguiente comando restaura el objeto example.txt del bucket examplebucket a la versión 123.
Para obtener más información sobre este comando, consulte revert.
Operaciones de API relacionadas
Las operaciones anteriores se implementan mediante llamadas a la API. Si su programa requiere un alto grado de personalización, puede llamar directamente a las API REST. Tenga en cuenta que deberá escribir manualmente el código para calcular las firmas. Para obtener más información, consulte PutBucketVersioning.
Trabajar con directivas de retención
En escenarios como la protección de copias de seguridad (Veeam), el seguimiento de cambios en activos (diagramas de diseño de circuitos) o el archivado por cumplimiento normativo (sector financiero), es posible que necesite permitir la actualización de datos y mantener inmutables todas las versiones históricas. Para ello, habilite tanto el control de versiones como una directiva de retención: el control de versiones conserva las versiones históricas al sobrescribir o eliminar objetos, mientras que la directiva de retención impide que cualquier versión se elimine o modifique durante el periodo de protección.
El control de versiones y las directivas de retención funcionan de manera conjunta bajo los siguientes principios:
Orden de habilitación de funciones: puede habilitar el control de versiones y las directivas de retención en cualquier orden.
Configuraciones permitidas:
Directiva de retención + control de versiones deshabilitado
Directiva de retención + control de versiones habilitado
Restricciones:
No es posible habilitar una directiva de retención en un bucket cuyo control de versiones esté suspendido.
Una vez habilitada una directiva de retención, se aplican las siguientes restricciones al estado del control de versiones:
No se puede cambiar el estado de Enabled a Suspended.
No se puede cambiar el estado de Disabled a Suspended.
Mecanismo de protección de versiones de objetos:
La directiva de retención protege todas las versiones de un objeto. Ninguna versión se puede eliminar ni modificar durante el periodo de protección.
Es posible cargar un objeto con el mismo nombre para crear una nueva versión, pero esta también queda protegida por la directiva de retención.
La directiva de retención no aplica a los marcadores de eliminación, por lo que su limpieza no está restringida por dicha directiva.
Interacción con la replicación de datos:
Los buckets de origen y destino admiten configuraciones independientes para el control de versiones y las directivas de retención.
La información de versiones se transfiere con normalidad durante la replicación. El bucket de destino gestiona las versiones según su propia configuración.
Si intenta eliminar una versión replicada en el bucket de destino y esta está protegida por una directiva de retención, la operación fallará. Una vez que expire la directiva, la eliminación se completará correctamente.