All Products
Search
Document Center

Object Storage Service:Aktifkan pengendalian versi untuk pemulihan data dan pengendalian versi

Last Updated:Jul 29, 2026

Pengendalian versi melindungi data di tingkat bucket dengan menyimpan versi historis objek saat ditimpa atau dihapus, sehingga Anda dapat memulihkan objek ke versi sebelumnya.

Kasus Penggunaan

Gunakan pengendalian versi dalam skenario berikut untuk melindungi data Anda.

  • Penghapusan data tidak sengaja

    Karena OSS tidak memiliki Keranjang daur ulang, pengendalian versi merupakan cara utama untuk memulihkan data yang terhapus secara tidak sengaja.

  • File yang ditimpa

    Untuk file yang sering dimodifikasi (seperti cloud drive atau alat kolaborasi), pengendalian versi memungkinkan Anda mengambil versi sebelumnya kapan saja.

Catatan Penggunaan

  • Penagihan

    Pengendalian versi itu sendiri gratis. Namun, semua versi objek (saat ini dan historis) dikenai biaya penyimpanan. Gunakan aturan siklus hidup untuk menghapus versi historis yang tidak diperlukan secara otomatis. Untuk informasi selengkapnya, lihat Aturan siklus hidup. Permintaan dan trafik dari pengunduhan atau pemulihan versi historis juga dikenai biaya. Metering dan penagihan.

  • Izin

    Hanya Pemilik bucket dan pengguna Resource Access Management (RAM) dengan izin PutBucketVersioning yang dapat mengonfigurasi pengendalian versi.

  • Fitur saling eksklusif

    Jika pengendalian versi untuk suatu bucket diaktifkan atau ditangguhkan:

    • Aturan yang melarang penimpaan objek tidak berlaku. Larang penimpaan objek.

    • Header permintaan x-oss-forbid-overwrite, yang digunakan untuk mencegah objek agar tidak ditimpa, tidak berlaku selama proses unggah. Untuk informasi selengkapnya, lihat PutObject.

  • Pengendalian versi dan OSS-HDFS

    Jangan aktifkan layanan OSS-HDFS dan pengendalian versi pada bucket yang sama. Hal ini dapat menyebabkan ketidakstabilan layanan. Untuk memastikan operasi stabil, segera tangguhkan pengendalian versi dan konfigurasikan aturan siklus hidup untuk membersihkan penanda hapus.

Status Pengendalian Versi

Pengendalian versi bucket dapat berada dalam salah satu dari tiga status: Disabled (default), Enabled, atau Suspended.

  • Secara default, pengendalian versi dinonaktifkan untuk bucket. Setelah diaktifkan, pengendalian versi tidak dapat kembali ke status Disabled. Status tersebut hanya dapat ditangguhkan.

  • Saat pengendalian versi diaktifkan, OSS menyimpan versi historis objek. Untuk informasi selengkapnya, lihat Kelola objek yang dikendalikan versinya.

  • Saat pengendalian versi ditangguhkan, objek yang baru diunggah akan menggantikan versi saat ini dari objek yang memiliki nama sama. Versi historis yang ada tetap disimpan. Untuk informasi selengkapnya, lihat Kelola objek di bucket dengan pengendalian versi ditangguhkan.

Catatan

Semua versi objek dikenai biaya penyimpanan. Gunakan aturan siklus hidup untuk memindahkan versi ke kelas penyimpanan berbiaya lebih rendah (seperti Infrequent Access atau Archive) atau menghapus versi historis yang tidak diperlukan. Untuk informasi selengkapnya, lihat Kurangi biaya penyimpanan dengan menggabungkan aturan siklus hidup berdasarkan waktu modifikasi terakhir dengan pengendalian versi.

Proteksi Data

Tabel berikut menjelaskan perbedaan perilaku penimpaan dan penghapusan objek di antara berbagai status pengendalian versi.

Status Pengendalian Versi

Menimpa objek

Menghapus objek

Disabled

Objek yang ada ditimpa dan tidak dapat dipulihkan. Anda hanya dapat mengambil versi terbaru objek tersebut.

Objek dihapus secara permanen dan tidak dapat diambil kembali.

Enabled

Versi baru dibuat. Versi historis tidak terpengaruh.

Objek ditandai sebagai dihapus. Versi historis tidak terpengaruh dan dapat dipulihkan.

Suspended

Versi baru dibuat. Jika versi objek yang sama sudah ada sejak periode penangguhan, versi baru akan menimpanya. Versi historis lainnya tidak terpengaruh.

Objek ditandai sebagai dihapus. Jika penanda hapus untuk objek yang sama sudah ada sejak periode penangguhan, penanda baru akan menimpanya. Versi historis lainnya tidak terpengaruh.

Aktifkan Pengendalian Versi

Gunakan Konsol OSS

Saat pengendalian versi diaktifkan untuk bucket, OSS menetapkan ID unik untuk setiap versi objek yang disimpan di bucket tersebut.

  • Aktifkan pengendalian versi saat membuat bucket.

    1. Masuk ke Konsol OSS.

    2. Klik Buckets, lalu klik Create Bucket.

    3. Pada halaman Create Bucket, konfigurasikan parameter.

      Pada bagian Versioning, atur sakelar Versioning ke On. Secara default, fitur ini Off. Untuk informasi selengkapnya tentang parameter lainnya, lihat Buat bucket.

    4. Klik Create.

  • Aktifkan pengendalian versi untuk bucket yang sudah ada.

    1. Di panel navigasi kiri, klik Buckets. Di halaman Buckets, temukan dan klik bucket yang diinginkan.

    2. Di panel navigasi kiri, pilih Content Security > Versioning.

    3. Pada halaman Versioning, klik Enable Now.

    4. Pada kotak dialog yang muncul, klik Confirm On.

Setelah Anda mengaktifkan pengendalian versi, pada halaman Objects, klik Show di samping Previous Versions untuk melihat semua versi file. Untuk hanya melihat versi terkini file, klik Hide di samping Previous Versions. Menyembunyikan versi sebelumnya tidak meningkatkan performa pencatatan file. Jika halaman merespons lambat saat mencatat file, lihat Kecepatan respons lambat untuk memecahkan masalah tersebut.

Gunakan SDK Alibaba Cloud

Contoh berikut menunjukkan cara mengaktifkan pengendalian versi menggunakan berbagai SDK. Pengenalan SDK.

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

Gunakan antarmuka baris perintah ossutil

Gunakan ossutil untuk mengatur status pengendalian versi bucket. Untuk informasi cara menginstal ossutil, lihat Instal ossutil.

Perintah berikut mengaktifkan pengendalian versi untuk bucket tertentu.

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

Untuk informasi selengkapnya tentang perintah ini, lihat put-bucket-versioning.

Tangguhkan Pengendalian Versi

Jika kebijakan retensi diaktifkan untuk bucket, Anda tidak dapat mengubah status pengendalian versi dari Enabled ke Suspended. Namun, Anda dapat mengubah status dari Suspended ke Enabled.

Gunakan Konsol OSS

Anda dapat menangguhkan pengendalian versi untuk bucket yang telah dikendalikan versinya agar OSS tidak membuat versi baru untuk objek. Jika versi baru dibuat untuk objek di bucket dengan pengendalian versi ditangguhkan, OSS akan mengatur ID versi baru tersebut menjadi null dan menyimpan versi sebelumnya objek tersebut.

Untuk menangguhkan pengendalian versi bucket, lakukan langkah-langkah berikut:

  1. Di panel navigasi kiri, klik Buckets. Di halaman Buckets, temukan dan klik bucket yang diinginkan.

  2. Di panel navigasi kiri, pilih Content Security > Versioning.

  3. Pada halaman Versioning, klik Suspend.

  4. Pada kotak dialog yang muncul, klik OK.

Gunakan SDK Alibaba Cloud

Contoh berikut menunjukkan cara menangguhkan pengendalian versi menggunakan SDK umum. Pengenalan SDK.

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

Gunakan antarmuka baris perintah ossutil

Gunakan ossutil untuk mengatur status pengendalian versi bucket. Untuk informasi cara menginstal ossutil, lihat Instal ossutil.

Perintah berikut menangguhkan pengendalian versi untuk bucket tertentu.

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

Untuk informasi selengkapnya tentang perintah ini, lihat put-bucket-versioning.

Lihat Versi

Gunakan ossutil untuk melihat semua versi objek. Untuk informasi cara menginstal ossutil, lihat Instal ossutil.

Perintah berikut mencantumkan informasi tentang semua versi semua objek di bucket examplebucket.

ossutil api list-object-versions --bucket examplebucket

Untuk informasi selengkapnya tentang perintah ini, lihat list-object-versions.

Pulihkan Versi

Gunakan Konsol OSS

Saat Anda menghapus objek dari bucket dengan pengendalian versi diaktifkan, objek tersebut tidak dihapus secara permanen. Sebaliknya, objek tersebut ditandai sebagai dihapus. Anda dapat memulihkan versi sebelumnya di konsol.

  1. Di panel navigasi kiri, klik Buckets. Di halaman Buckets, temukan dan klik bucket yang diinginkan.

  2. Di panel navigasi kiri, pilih Object Management > Objects.

  3. Klik Show di samping Previous Versions.

  4. Pilih versi yang ingin dipulihkan dan klik Restore di bagian bawah halaman.

  5. Pada kotak dialog yang muncul, klik OK.

Gunakan antarmuka baris perintah ossutil

Gunakan ossutil untuk memulihkan versi historis file yang dihapus. Untuk informasi cara menginstal ossutil, lihat Instal ossutil.

Perintah berikut memulihkan objek example.txt di bucket examplebucket ke versi 123.

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

Untuk informasi selengkapnya tentang perintah ini, lihat revert.

Operasi API Terkait

Operasi di atas diimplementasikan berdasarkan operasi API. Jika program Anda memiliki kebutuhan kustomisasi tinggi, Anda dapat langsung memanggil operasi REST API. Perhatikan bahwa Anda harus menulis kode secara manual untuk menghitung signature. Untuk informasi selengkapnya, lihat PutBucketVersioning.

Bekerja dengan Kebijakan Retensi

Dalam skenario seperti proteksi backup (Veeam), pelacakan perubahan aset (diagram desain sirkuit), atau pengarsipan kepatuhan (keuangan), Anda mungkin perlu mengizinkan pembaruan data sekaligus menjaga semua versi historis tetap immutable. Aktifkan baik pengendalian versi maupun kebijakan retensi: pengendalian versi menyimpan versi historis saat ditimpa atau dihapus, dan kebijakan retensi mencegah versi apa pun dihapus atau dimodifikasi selama periode proteksi.

Pengendalian versi dan kebijakan retensi bekerja bersama berdasarkan prinsip-prinsip berikut:

  • Urutan pengaktifan fitur: Anda dapat mengaktifkan pengendalian versi dan kebijakan retensi dalam urutan apa pun.

  • Konfigurasi yang diizinkan:

    • Kebijakan retensi + Pengendalian versi dinonaktifkan

    • Kebijakan retensi + Pengendalian versi diaktifkan

  • Batasan:

    • Anda tidak dapat mengaktifkan kebijakan retensi untuk bucket yang pengendalian versinya ditangguhkan.

    • Setelah kebijakan retensi diaktifkan, batasan berikut berlaku untuk status pengendalian versi:

      • Anda tidak dapat mengubah status dari Enabled ke Suspended.

      • Anda tidak dapat mengubah status dari Disabled ke Suspended.

  • Mekanisme proteksi versi objek:

    • Kebijakan retensi melindungi semua versi objek. Tidak ada versi yang dapat dihapus atau dimodifikasi selama periode proteksi.

    • Anda dapat mengunggah objek dengan nama yang sama untuk membuat versi baru, tetapi versi baru tersebut juga dilindungi oleh kebijakan retensi.

    • Kebijakan retensi tidak berlaku untuk penanda hapus. Pembersihan penanda hapus tidak dibatasi oleh kebijakan retensi.

  • Interaksi dengan replikasi data:

    • Bucket sumber dan tujuan mendukung konfigurasi independen untuk pengendalian versi dan kebijakan retensi.

    • Informasi versi ditransfer secara normal selama replikasi. Bucket tujuan mengelola versi berdasarkan konfigurasinya sendiri.

    • Mencoba menghapus versi yang direplikasi di bucket tujuan akan gagal jika versi tersebut dilindungi oleh kebijakan retensi, tetapi akan berhasil setelah kebijakan tersebut berakhir.

Referensi