All Products
Search
Document Center

Object Storage Service:Enable versioning for data recovery and version management

Last Updated:Mar 12, 2024

You can enable versioning for a bucket to protect objects stored in the bucket. When you overwrite or delete objects that are stored in a versioning-enabled bucket, Object Storage Service (OSS) saves the objects as previous versions in the bucket. After you enable versioning for a bucket, you can restore objects in the bucket to a previous version to protect your data from being accidentally overwritten or deleted.

Scenarios

To ensure data security, we recommend that you enable versioning in the following scenarios:

  • Restore deleted data

    OSS does not provide the recycle bin feature. You can use the versioning feature to restore deleted data.

  • Restore overwritten data

    Numerous temporary versions are created in scenarios in which modifications are frequently made, such as online collaborative documents and documents stored in online storage. You can use the versioning feature to restore a specific version of an object stored in the bucket.

Usage notes

  • Billing rules

    If you enable versioning for a bucket, you are charged for the storage of all versions of objects in the bucket. To reduce storage costs, we recommend that you configure bucket lifecycle rules to delete the previous versions of objects that you no longer need. For more information, see Overview. When you download a previous version of an object or restore an object to a previous version, you are charged request and traffic fees. For more information, see Billing Overview.

  • Required permissions

    Only the bucket owner or RAM users who have the PutBucketVersioning permission can enable versioning for a bucket.

  • Feature conflicts

    • A bucket cannot have versioning and retention policies configured at the same time.

    • The x-oss-forbid-overwrite header in a request to upload data to a versioning-enabled bucket does not take effect. For more information, see PutObject.

  • OSS-HDFS in versioning-enabled buckets

    Do not enable OSS-HDFS and versioning for a bucket.

    If OSS-HDFS and versioning are enabled for a bucket, OSS-HDFS may not work as expected. To ensure the stability of OSS-HDFS, you need to suspend versioning at the earliest opportunity and configure lifecycle rules to remove delete markers.

Versioning states

A bucket can be in one of the following versioning states: disabled, enabled, and suspended.

  • By default, the versioning state of a bucket is disabled. After versioning is enabled for a bucket, the versioning state of the bucket cannot be rolled back to disabled. However, you can suspend versioning for a bucket for which versioning is enabled.

  • When an object is uploaded to a bucket for which versioning is enabled, OSS generates a random string as the globally unique version ID of the object. For more information about operations on objects in a versioning-enabled bucket, see Manage objects in a versioning-enabled bucket.

  • When an object is uploaded to a bucket for which versioning is suspended, OSS generates the "null" string as the version ID of the object. For more information about operations on objects in a versioning-suspended bucket, see Manage objects in a versioning-suspended bucket.

Note

In a versioning-enabled bucket, all versions of an object are stored. These versions consume storage space and are billed storage fees. We recommend that you configure lifecycle rules to change the storage class of a version to Infrequent Access (IA) or Archive or delete historical versions that are no longer needed. This reduces your storage costs. For more information, see Configure lifecycle rules based on the last modified time for versioning-enabled buckets to reduce storage costs.

Data protection

The following table describes how OSS processes deleted and overwritten data in buckets in different versioning states to help you understand the data protection mechanism of versioning.

Versioning state

Object overwriting

Object deletion

Disabled

The existing object is overwritten and cannot be restored.

The object is deleted and no longer stored in OSS.

Enabled

A new version with a unique ID is generated for the object. The existing object is stored as a previous version.

A delete marker with a globally unique version ID is added to the object as the current version. The existing object is stored as a previous version.

Suspended

A new version whose version ID is null is generated for the object.

If the object already has a previous version or delete marker whose version ID is null, the previous version or delete marker is overwritten by the new null version. Other previous versions or delete markers whose version IDs are not null are not affected.

A delete marker whose version ID is null is added to the object.

If the object already has a previous version or delete marker whose version ID is null, the previous version or delete marker is overwritten by the new delete marker. Other previous versions or delete markers whose version IDs are not null are not affected.

The following figures show how OSS processes data when an object with the same name as an existing object is uploaded to or an object is deleted from a bucket for which versioning is enabled or suspended. For ease of viewing, all version IDs in the figures are in the simple format.

  • Overwrite an object in a versioning-enabled bucket

    When you upload an object repeatedly to a versioning-enabled bucket, the object is overwritten in each upload. A version with a unique version ID is generated for the object each time the object is overwritten.

    1

  • Delete an object from a versioning-enabled bucket

    When you delete an object from a versioning-enabled bucket, OSS adds a delete marker to the object as the current version of the object instead of permanently deleting the object. The previous versions of the object are not deleted. If you upload an object with the same name after the delete marker is added, a new version with a unique version ID is added as the current version.

    2

  • Overwrite an object in a versioning-suspended bucket

    When you upload an object with the same name as an existing object in a bucket for which versioning is suspended, a new version whose version ID is null is added to the bucket and the previous versions of the object are retained. If you upload another object with the same name to the bucket again, a new version whose version ID is null overwrites the current version whose version ID is also null.

    3

  • Delete an object from a versioning-suspended bucket

    When you delete an object from a bucket for which versioning is suspended, OSS adds a delete marker to the object as the current version of the object instead of permanently deleting this object. The previous versions of the object are not deleted.

    4

In summary, deleted and overwritten data is stored as previous versions in a versioning-enabled bucket. After you enable versioning for a bucket, you can restore objects in the bucket to a previous version to protect your data from being accidentally overwritten or deleted.

Enable versioning

Use the OSS console

When versioning is enabled for a bucket, OSS specifies a unique ID for each version of an object stored in the bucket.

  • Enable versioning when you create a bucket

    1. Log on to the OSS console.

    2. In the left-side navigation pane, click Buckets. On the Buckets page, click Create Bucket.

    3. In the Create Bucket panel, configure the parameters.

      Turn on Versioning For more information about how to configure other parameters, see Create buckets.

    4. Click OK.

  • Enable versioning for an existing bucket

    1. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

    2. In the left-side navigation tree, choose Content Security > Versioning.

    3. On the Versioning page, click Enable.

    4. In the message that appears, click OK.

After you enable versioning, to view all versions of objects in the bucket, click Show to the right of Previous Versions on the Objects page. To view only the current versions of objects, click Hide to the right of Previous Versions. Hiding previous versions of objects does not accelerate the response speed when you list objects. If the response speed is slow when you list objects, see FAQ to resolve the issue.

Use OSS SDKs

The following sample code provides examples on how to suspend versioning for a bucket by using OSS SDKs for common programming languages. For more information about how to suspend versioning for a bucket by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;

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 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";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        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 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");
// In this example, the China (Hangzhou) region is used as the endpoint. Specify your 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 in which the bucket is located. For example, if the bucket is located 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 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 name of the bucket. 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 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. 
# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')

# Initialize the versioning configurations of the bucket. 
config = BucketVersioningConfig()
# Enable versioning. 
config.status = oss2.BUCKET_VERSIONING_ENABLE

result = bucket.put_bucket_versioning(config)
# Display the HTTP status code. 
print('http response code:', result.status)
using Aliyun.OSS;
// 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";
// Initialize an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
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 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. 
    // 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. Specify your actual endpoint. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
       fmt.Println("Error:", err)
       os.Exit(-1)
  }

  // Create a bucket. 
  // Specify the name of the bucket. 
  err = client.CreateBucket("yourBucketName")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
  // Set the versioning status of the 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 information about the account that is used to access OSS. */
            
    /* 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. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources, such as 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);

    /* Set the versioning status of the bucket 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 resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Use ossutil

For more information about how to enable versioning by using ossutil, see bucket-versioning.

Use RESTful API operations

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutBucketVersioning.

Suspend versioning

Use the OSS console

You can suspend versioning for a versioned bucket to stop OSS from generating new versions for objects. If a new version is generated for an object in a versioning-suspended bucket, OSS sets the ID of the new version to null and retains the previous versions of the object.

To suspend versioning for a bucket, perform the following steps:

  1. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  2. In the left-side navigation tree, choose Content Security > Versioning.

  3. On the Versioning page, click Suspend.

  4. In the message that appears, click OK.

Use OSS SDKs

The following sample code provides examples on how to suspend versioning for a bucket by using OSS SDKs for common programming languages. For more information about how to suspend versioning for a bucket by using OSS SDKs for other programming languages, see Overview.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;

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 you specified the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        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");
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your 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 in which the bucket is located. For example, if the bucket is located 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 you specified the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 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 you specified the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables. 
auth = oss2.ProviderAuth(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. 
# Specify the name of the bucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')

# Initialize the versioning configurations of the bucket. 
config = BucketVersioningConfig()
# Suspend versioning. 
config.status = oss2.BUCKET_VERSIONING_SUSPENDED

result = bucket.put_bucket_versioning(config)
# Display the HTTP status code. 
print('http response code:', result.status)
using Aliyun.OSS;
// 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 you specified the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables. 
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";
// Initialize an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    // Set the versioning state of the bucket to Suspended. 
    client.SetBucketVersioning(new SetBucketVersioningRequest(bucketName, VersioningStatus.Suspended));
    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 you specified the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables. 
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance. 
    // 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. Specify your actual endpoint. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
       fmt.Println("Error:", err)
       os.Exit(-1)
  }

  // Create a bucket. 
  // Specify 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 information about the account that is used to access OSS. */
            
    /* 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. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

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

    ClientConfiguration conf;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that you specified the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);

    /* Set the versioning state of the bucket 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 resources, such as network resources. */
    ShutdownSdk();
    return 0;
}

Use ossutil

For more information about how to use ossutil to suspend versioning, see bucket-versioning.

Use RESTful API operations

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutBucketVersioning.

View the versions of an object

You can use ossutil to view all versions of an object. For example, you can run the following command to view all versions of an object named example.txt in the root directory of a bucket named examplebucket:

./ossutil64 ls oss://examplebucket/example.txt --all-versions

For more information, see Is.

Restore a previous version of an object

Use the OSS console

When you delete an object from a versioning-enabled bucket, OSS adds a delete marker to the object as the current version of the object instead of permanently deleting the object. The previous versions of the object are not deleted. You can restore a previous version of an object in the OSS console.

  1. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  2. In the left-side navigation tree, choose Object Management > Objects.

  3. In the upper-right corner of the object list, click Show to the right of Previous Versions.

  4. Select the previous version that you want to restore and click Restore.

  5. In the message that appears, click OK.

Use ossutil

You can run the revert-versioning command to restore a previous version of an object. For more information, see revert-versioning.