Mengunci kebijakan retensi bucket

Memberikan contoh cara mengunci kebijakan retensi bucket.

Jelajahi lebih lanjut

Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat berikut:

Contoh kode

C++

Untuk informasi selengkapnya, lihat Dokumentasi referensi Cloud Storage C++ API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> original =
      client.GetBucketMetadata(bucket_name);
  if (!original) throw std::move(original).status();

  StatusOr<gcs::BucketMetadata> updated_metadata =
      client.LockBucketRetentionPolicy(bucket_name,
                                       original->metageneration());
  if (!updated_metadata) throw std::move(updated_metadata).status();

  if (!updated_metadata->has_retention_policy()) {
    std::cerr << "The bucket " << updated_metadata->name()
              << " does not have a retention policy, even though the"
              << " operation to set it was successful.\n"
              << "This is unexpected, and may indicate that another"
              << " application has modified the bucket concurrently.\n";
    return;
  }

  std::cout << "Retention policy successfully locked for bucket "
            << updated_metadata->name() << "\nNew retention policy is: "
            << updated_metadata->retention_policy()
            << "\nFull metadata: " << *updated_metadata << "\n";
}

C#

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C# API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


using Google.Cloud.Storage.V1;
using System;

public class LockRetentionPolicySample
{
    /// <summary>
    /// Locks the retention policy of a bucket. This is a one-way process: once a retention
    /// policy is locked, it cannot be shortened, removed or unlocked, although it can
    /// be increased in duration. The lock persists until the bucket is deleted.
    /// </summary>
    /// <param name="bucketName">The name of the bucket whose retention policy should be locked.</param>
    public bool? LockRetentionPolicy(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        storage.LockBucketRetentionPolicy(bucketName, bucket.Metageneration.Value);
        bucket = storage.GetBucket(bucketName);
        Console.WriteLine($"Retention policy for {bucketName} is now locked");
        Console.WriteLine($"Retention policy effective as of {bucket.RetentionPolicy.EffectiveTime}");

        return bucket.RetentionPolicy.IsLocked;
    }
}

Go

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Go API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

ctx := context.Background()
bucket := c.Bucket(bucketName)

ctx, cancel := context.WithTimeout(ctx, time.Second*50)
defer cancel()
attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}

conditions := storage.BucketConditions{
	MetagenerationMatch: attrs.MetaGeneration,
}
if err := bucket.If(conditions).LockRetentionPolicy(ctx); err != nil {
	return err
}

lockedAttrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}
log.Printf("Retention policy for %v is now locked\n", bucketName)
log.Printf("Retention policy effective as of %v\n",
	lockedAttrs.RetentionPolicy.EffectiveTime)

Java

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Java API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
import java.util.Date;

public class LockRetentionPolicy {
  public static void lockRetentionPolicy(String projectId, String bucketName)
      throws StorageException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket =
        storage.get(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.METAGENERATION));
    Bucket lockedBucket =
        bucket.lockRetentionPolicy(Storage.BucketTargetOption.metagenerationMatch());

    System.out.println("Retention period for " + bucketName + " is now locked");
    System.out.println(
        "Retention policy effective as of " + new Date(lockedBucket.getRetentionEffectiveTime()));
  }
}

Node.js

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Node.js API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function lockRetentionPolicy() {
  // Gets the current metageneration value for the bucket, required by
  // lock_retention_policy
  const [unlockedMetadata] = await storage.bucket(bucketName).getMetadata();

  // Warning: Once a retention policy is locked, it cannot be unlocked. The
  // retention period can only be increased
  const [lockedMetadata] = await storage
    .bucket(bucketName)
    .lock(unlockedMetadata.metageneration);
  console.log(`Retention policy for ${bucketName} is now locked`);
  console.log(
    `Retention policy effective as of ${lockedMetadata.retentionPolicy.effectiveTime}`
  );

  return lockedMetadata;
}

lockRetentionPolicy().catch(console.error);

PHP

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage PHP API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

use Google\Cloud\Storage\StorageClient;

/**
 * Locks a bucket's retention policy.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function lock_retention_policy(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();
    $bucket->lockRetentionPolicy();
    printf('Bucket %s retention policy locked' . PHP_EOL, $bucketName);
}

Python

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Python API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from google.cloud import storage

def lock_retention_policy(bucket_name):
    """Locks the retention policy on a given bucket"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    # get_bucket gets the current metageneration value for the bucket,
    # required by lock_retention_policy.
    bucket = storage_client.get_bucket(bucket_name)

    # Warning: Once a retention policy is locked it cannot be unlocked
    # and retention period can only be increased.
    bucket.lock_retention_policy()

    print(f"Retention policy for {bucket_name} is now locked")
    print(
        f"Retention policy effective as of {bucket.retention_policy_effective_time}"
    )

Ruby

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Ruby API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

def lock_retention_policy bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  # Warning: Once a retention policy is locked it cannot be unlocked
  # and retention period can only be increased.
  # Uses Bucket#metageneration as a precondition.
  bucket.lock_retention_policy!

  puts "Retention policy for #{bucket_name} is now locked."
  puts "Retention policy effective as of #{bucket.retention_effective_at}."
end

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.