보관 정책 사용 및 잠금

개요

이 페이지에서는 보관 정책 작업과 버킷 정책 영구 잠금을 포함하여 버킷 잠금 기능을 사용하는 방법을 설명합니다.

시작하기 전에

버킷 잠금 기능을 사용하려면 먼저 다음 섹션의 단계를 완료해야 합니다.

필요한 역할 얻기

버킷 잠금을 사용하는 데 필요한 권한을 얻으려면 관리자에게 버킷에 대한 스토리지 관리자(roles/storage.admin) 역할을 부여해 달라고 요청하세요. 이 사전 정의된 역할에는 버킷 잠금을 사용하는 데 필요한 권한이 포함되어 있습니다. 필요한 권한을 정확하게 확인하려면 필수 권한 섹션을 확장하세요.

필수 권한

  • storage.buckets.get
  • storage.buckets.list
    • 이 권한은 Google Cloud 콘솔을 사용하여 이 페이지의 안내를 수행하려는 경우에만 필요합니다.
  • storage.buckets.update

커스텀 역할을 사용하여 이러한 권한을 부여받을 수도 있습니다.

버킷의 역할 부여에 대한 자세한 내용은 버킷에 IAM 사용을 참조하세요.

객체 버전 관리 중지

사용할 버킷에 대해 객체 버전 관리가 중지되어 있는지 확인합니다. 객체 버전 관리를 중지하고 버킷에 객체 버전 관리가 사용 설정되어 있는지 확인하는 방법은 객체 버전 관리 사용을 참조하세요.

버킷에 보관 정책 설정

버킷에 보관 정책을 추가, 수정 또는 삭제하려면 다음 안내를 따르세요.

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 보관 정책을 변경할 버킷의 이름을 클릭합니다.

  3. 페이지 상단의 보호 탭을 선택합니다.

  4. 보관 정책 섹션에서 보관 정책을 설정합니다.

    1. 현재 버킷에 적용된 보관 정책이 없으면 보관 정책 설정 링크를 클릭합니다. 보관 시간 단위 및 기간을 선택합니다.

    2. 보관 정책이 현재 버킷에 적용되는 경우 섹션에 표시됩니다. 수정을 클릭하여 보관 기간을 수정하거나 삭제를 클릭하여 보관 정책을 완전히 삭제합니다.

    Google Cloud 콘솔에서 시간 단위가 변환되는 방식은 보관 기간을 참조하세요.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

gcloud storage buckets update 명령어를 적절한 플래그와 함께 사용합니다.

gcloud storage buckets update gs://BUCKET_NAME FLAG

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.

  • FLAG는 버킷 보관 기간에 사용하려는 설정입니다. 다음 형식 중 하나를 사용하세요.

    • --retention-period보관 기간(보관 정책을 추가하거나 변경하려는 경우). 예를 들면 --retention-period=1d43200s입니다.
    • --clear-retention-period(버킷에 대한 보관 정책을 삭제하려는 경우)

성공하면 다음과 같은 응답이 표시됩니다.

Updating gs://my-bucket/...
  Completed 1  

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 보관 정책을 설정합니다.

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

  StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetRetentionPolicy(period),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!patched) throw std::move(patched).status();

  if (!patched->has_retention_policy()) {
    std::cout << "The bucket " << patched->name()
              << " does not have a retention policy set.\n";
    return;
  }

  std::cout << "The bucket " << patched->name()
            << " retention policy is set to " << patched->retention_policy()
            << "\n";
}

다음 샘플은 버킷에서 보관 정책을 삭제합니다.

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> patched = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().ResetRetentionPolicy(),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!patched) throw std::move(patched).status();

  if (!patched->has_retention_policy()) {
    std::cout << "The bucket " << patched->name()
              << " does not have a retention policy set.\n";
    return;
  }

  std::cout << "The bucket " << patched->name()
            << " retention policy is set to " << patched->retention_policy()
            << ". This is unexpected, maybe a concurrent change by another"
            << " application?\n";
}

C#

자세한 내용은 Cloud Storage C# API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 보관 정책을 설정합니다.


using Google.Cloud.Storage.V1;
using System;
using static Google.Apis.Storage.v1.Data.Bucket;

public class SetRetentionPolicySample
{
    /// <summary>
    /// Sets the bucket's retention policy.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <param name="retentionPeriod">The duration in seconds that objects need to be retained. The retention policy enforces a minimum retention
    /// time for all objects contained in the bucket, based on their creation time. Any
    /// attempt to overwrite or delete objects younger than the retention period will
    /// result in a PERMISSION_DENIED error. An unlocked retention policy can be modified
    /// or removed from the bucket via a storage.buckets.update operation. A locked retention
    /// policy cannot be removed or shortened in duration for the lifetime of the bucket.
    /// Attempting to remove or decrease the period of a locked retention policy will result
    /// in a PERMISSION_DENIED error.</param>
    public RetentionPolicyData SetRetentionPolicy(
        string bucketName = "your-unique-bucket-name",
        long retentionPeriod = 10)
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.RetentionPolicy = new RetentionPolicyData { RetentionPeriod = retentionPeriod };

        bucket = storage.UpdateBucket(bucket);

        Console.WriteLine($"Retention policy for {bucketName} was set to {retentionPeriod}");
        return bucket.RetentionPolicy;
    }
}

다음 샘플은 버킷에서 보관 정책을 삭제합니다.


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

public class RemoveRetentionPolicySample
{
    public void RemoveRetentionPolicy(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        if (bucket.RetentionPolicy != null)
        {
            bool isLocked = bucket.RetentionPolicy.IsLocked ?? false;
            if (isLocked)
            {
                throw new Exception("Retention Policy is locked.");
            }

            bucket.RetentionPolicy.RetentionPeriod = null;
            storage.UpdateBucket(bucket);

            Console.WriteLine($"Retention period for {bucketName} has been removed.");
        }
    }
}

Go

자세한 내용은 Cloud Storage Go API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 보관 정책을 설정합니다.

ctx := context.Background()

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	RetentionPolicy: &storage.RetentionPolicy{
		RetentionPeriod: retentionPeriod,
	},
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

다음 샘플은 버킷에서 보관 정책을 삭제합니다.

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

attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}
if attrs.RetentionPolicy.IsLocked {
	return errors.New("retention policy is locked")
}

bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	RetentionPolicy: &storage.RetentionPolicy{},
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Java

자세한 내용은 Cloud Storage Java API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 보관 정책을 설정합니다.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.BucketTargetOption;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
import java.time.Duration;

public class SetRetentionPolicy {
  public static void setRetentionPolicy(
      String projectId, String bucketName, Long retentionPeriodSeconds) 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";

    // The retention period for objects in bucket
    // Long retentionPeriodSeconds = 3600L; // 1 hour in seconds

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // first look up the bucket so we will have its metageneration
    Bucket bucket = storage.get(bucketName);
    Bucket bucketWithRetentionPolicy =
        storage.update(
            bucket
                .toBuilder()
                .setRetentionPeriodDuration(Duration.ofSeconds(retentionPeriodSeconds))
                .build(),
            BucketTargetOption.metagenerationMatch());

    System.out.println(
        "Retention period for "
            + bucketName
            + " is now "
            + bucketWithRetentionPolicy.getRetentionPeriodDuration());
  }
}

다음 샘플은 버킷에서 보관 정책을 삭제합니다.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

public class RemoveRetentionPolicy {
  public static void removeRetentionPolicy(String projectId, String bucketName)
      throws StorageException, IllegalArgumentException {
    // 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.RETENTION_POLICY));
    if (bucket.retentionPolicyIsLocked() != null && bucket.retentionPolicyIsLocked()) {
      throw new IllegalArgumentException(
          "Unable to remove retention policy as retention policy is locked.");
    }

    bucket.toBuilder().setRetentionPeriod(null).build().update();

    System.out.println("Retention policy for " + bucketName + " has been removed");
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 보관 정책을 설정합니다.

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

// The retention period for objects in bucket
// const retentionPeriod = 3600; // 1 hour in seconds

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

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

async function setRetentionPolicy() {
  const [metadata] = await storage
    .bucket(bucketName)
    .setRetentionPeriod(retentionPeriod);
  console.log(
    `Bucket ${bucketName} retention period set for ${metadata.retentionPolicy.retentionPeriod} seconds.`
  );
}

setRetentionPolicy().catch(console.error);

다음 샘플은 버킷에서 보관 정책을 삭제합니다.

/**
 * 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 removeRetentionPolicy() {
  const [metadata] = await storage.bucket(bucketName).getMetadata();
  if (metadata.retentionPolicy && metadata.retentionPolicy.isLocked) {
    console.log(
      'Unable to remove retention period as retention policy is locked.'
    );
    return null;
  } else {
    const results = await storage.bucket(bucketName).removeRetentionPeriod();
    console.log(`Removed bucket ${bucketName} retention policy.`);
    return results;
  }
}

removeRetentionPolicy().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 보관 정책을 설정합니다.

use Google\Cloud\Storage\StorageClient;

/**
 * Sets a bucket's retention policy.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param int $retentionPeriod The retention period for objects in bucket, in seconds.
 *        (e.g. 3600)
 */
function set_retention_policy(string $bucketName, int $retentionPeriod): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'retentionPolicy' => [
            'retentionPeriod' => $retentionPeriod
        ]]);
    printf('Bucket %s retention period set to %s seconds' . PHP_EOL, $bucketName,
        $retentionPeriod);
}

다음 샘플은 버킷에서 보관 정책을 삭제합니다.

use Google\Cloud\Storage\StorageClient;

/**
 * Removes a bucket's retention policy.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function remove_retention_policy(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();

    if (array_key_exists('isLocked', $bucket->info()['retentionPolicy']) &&
        $bucket->info()['retentionPolicy']['isLocked']) {
        printf('Unable to remove retention period as retention policy is locked.' . PHP_EOL);
        return;
    }

    $bucket->update([
        'retentionPolicy' => []
    ]);
    printf('Removed bucket %s retention policy' . PHP_EOL, $bucketName);
}

Python

자세한 내용은 Cloud Storage Python API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 보관 정책을 설정합니다.

from google.cloud import storage


def set_retention_policy(bucket_name, retention_period):
    """Defines a retention policy on a given bucket"""
    # bucket_name = "my-bucket"
    # retention_period = 10

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    bucket.retention_period = retention_period
    bucket.patch()

    print(
        "Bucket {} retention period set for {} seconds".format(
            bucket.name, bucket.retention_period
        )
    )

다음 샘플은 버킷에서 보관 정책을 삭제합니다.

from google.cloud import storage


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

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    bucket.reload()

    if bucket.retention_policy_locked:
        print(
            "Unable to remove retention period as retention policy is locked."
        )
        return

    bucket.retention_period = None
    bucket.patch()

    print(f"Removed bucket {bucket.name} retention policy")

Ruby

자세한 내용은 Cloud Storage Ruby API 참조 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

다음 샘플에서는 버킷에 보관 정책을 설정합니다.

def set_retention_policy bucket_name:, retention_period:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The retention period for objects in bucket
  # retention_period = 3600 # 1 hour in seconds

  require "google/cloud/storage"

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

  bucket.retention_period = retention_period

  puts "Retention period for #{bucket_name} is now #{bucket.retention_period} seconds."
end

다음 샘플은 버킷에서 보관 정책을 삭제합니다.

def remove_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

  if !bucket.retention_policy_locked?
    bucket.retention_period = nil
    puts "Retention policy for #{bucket_name} has been removed."
  else
    puts "Policy is locked and retention policy can't be removed."
  end
end

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 다음 정보를 포함하는 JSON 파일을 만듭니다.

    {
      "retentionPolicy": {
        "retentionPeriod": "TIME_IN_SECONDS"
      }
    }

    여기서 TIME_IN_SECONDS는 버킷의 객체를 보관해야 하는 시간(초)입니다. 예를 들면 2678400입니다. 다양한 시간 단위가 초 단위로 변환되는 방법에 대한 내용은 보관 기간을 참조하세요.

    버킷에서 보관 정책을 삭제하려면 JSON 파일에서 다음을 사용합니다.

    {
      "retentionPolicy": null
    }
  3. cURL을 사용하여 PATCH 버킷 요청으로 JSON API를 호출합니다.

    curl -X PATCH --data-binary @JSON_FILE_NAME \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=retentionPolicy"

    각 항목의 의미는 다음과 같습니다.

    • JSON_FILE_NAME은 2단계에서 만든 JSON 파일의 경로입니다.
    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.

XML API

XML API는 기존 버킷에 보관 정책을 설정하거나 삭제하는 데 사용할 수 없습니다. 새 버킷과 함께 보관 정책을 포함하는 데만 사용할 수 있습니다.

버킷 잠그기

버킷을 잠그고 버킷의 보관 정책에 대한 수정을 영구적으로 제한하려면 다음을 수행합니다.

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 보관 정책을 잠글 버킷의 이름을 클릭합니다.

  3. 페이지 상단의 보호 탭을 선택합니다.

  4. 보관 정책 항목에서 잠금 버튼을 클릭합니다.

    보관 정책을 잠글까요? 대화상자가 나타납니다.

  5. 영구 알림을 확인합니다.

  6. 버킷 이름 입력란에 버킷 이름을 입력합니다.

  7. 정책 잠그기를 클릭합니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

gcloud storage buckets update 명령어를 --lock-retention-period 플래그와 함께 사용합니다.

gcloud storage buckets update gs://BUCKET_NAME --lock-retention-period

여기서 BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.

성공하면 다음 예시와 비슷한 응답이 표시됩니다.

Updating gs://my-bucket/...
  Completed 1  

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

자세한 내용은 Cloud Storage Node.js API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * 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

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 POST 버킷 요청으로 JSON API를 호출합니다.

    curl -X POST \
    -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/lockRetentionPolicy?ifMetagenerationMatch=BUCKET_METAGENERATION_NUMBER"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰의 이름입니다.
    • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • BUCKET_METAGENERATION_NUMBER는 버킷의 metageneration 값입니다. 예를 들면 8입니다. GET Bucket 요청으로 JSON API를 호출하여 버킷의 metageneration 값을 찾을 수 있습니다.

XML API

XML API는 버킷을 잠그는 데 사용할 수 없습니다. 대신 Google Cloud 콘솔과 같은 다른 Cloud Storage 도구 중 하나를 사용하세요.

버킷의 보관 정책 및 잠금 상태 보기

버킷에 설정된 보관 정책(있는 경우)과 보존 정책 잠금 여부를 보려면 다음을 수행합니다.

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 상태를 보려는 버킷의 이름을 클릭합니다.

    버킷에 보관 정책이 있으면 버킷의 보호 필드에 보관 기간이 표시됩니다. 보관 정책이 잠겨 있지 않으면 잠금 해제된 상태의 보관 기간 옆에 자물쇠 아이콘이 표시됩니다. 보관 정책이 잠겨 있으면 잠긴 상태의 보관 기간 옆에 자물쇠 아이콘이 표시됩니다.

명령줄

gcloud storage buckets describe 명령어를 --format 플래그와 함께 사용합니다.

gcloud storage buckets describe gs://BUCKET_NAME --format="default(retention_policy)"

여기서 BUCKET_NAME은 확인하려는 보관 정책의 버킷 이름입니다. 예를 들면 my-bucket입니다.

성공한 경우 버킷에 보관 정책이 있으면 다음과 유사한 응답이 표시됩니다.

retention_policy:
  effectiveTime: '2022-10-04T18:51:22.161000+00:00'
  retentionPeriod: '129600'

성공한 경우 버킷에 보관 정책이 없으면 다음과 유사한 응답이 표시됩니다.

null

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

  if (!bucket_metadata->has_retention_policy()) {
    std::cout << "The bucket " << bucket_metadata->name()
              << " does not have a retention policy set.\n";
    return;
  }

  std::cout << "The bucket " << bucket_metadata->name()
            << " retention policy is set to "
            << bucket_metadata->retention_policy() << "\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Cloud.Storage.V1;
using System;
using static Google.Apis.Storage.v1.Data.Bucket;

public class GetRetentionPolicySample
{
    public RetentionPolicyData GetRetentionPolicy(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        if (bucket.RetentionPolicy != null)
        {
            Console.WriteLine("Retention policy:");
            Console.WriteLine($"Period: {bucket.RetentionPolicy.RetentionPeriod}");
            Console.WriteLine($"Effective time: {bucket.RetentionPolicy.EffectiveTime}");
            bool isLocked = bucket.RetentionPolicy.IsLocked ?? false;
            Console.WriteLine($"Policy locked: {isLocked}");
        }
        return bucket.RetentionPolicy;
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return nil, err
}
if attrs.RetentionPolicy != nil {
	log.Print("Retention Policy\n")
	log.Printf("period: %v\n", attrs.RetentionPolicy.RetentionPeriod)
	log.Printf("effective time: %v\n", attrs.RetentionPolicy.EffectiveTime)
	log.Printf("policy locked: %v\n", attrs.RetentionPolicy.IsLocked)
}

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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 GetRetentionPolicy {
  public static void getRetentionPolicy(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.RETENTION_POLICY));

    System.out.println("Retention Policy for " + bucketName);
    System.out.println("Retention Period: " + bucket.getRetentionPeriod());
    if (bucket.retentionPolicyIsLocked() != null && bucket.retentionPolicyIsLocked()) {
      System.out.println("Retention Policy is locked");
    }
    if (bucket.getRetentionEffectiveTime() != null) {
      System.out.println("Effective Time: " + new Date(bucket.getRetentionEffectiveTime()));
    }
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * 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 getRetentionPolicy() {
  const [metadata] = await storage.bucket(bucketName).getMetadata();
  if (metadata.retentionPolicy) {
    const retentionPolicy = metadata.retentionPolicy;
    console.log('A retention policy exists!');
    console.log(`Period: ${retentionPolicy.retentionPeriod}`);
    console.log(`Effective time: ${retentionPolicy.effectiveTime}`);
    if (retentionPolicy.isLocked) {
      console.log('Policy is locked');
    } else {
      console.log('Policy is unlocked');
    }
  }
}

getRetentionPolicy().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Storage\StorageClient;

/**
 * Gets a bucket's retention policy.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function get_retention_policy(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();

    printf('Retention Policy for ' . $bucketName . PHP_EOL);
    printf('Retention Period: ' . $bucket->info()['retentionPolicy']['retentionPeriod'] . PHP_EOL);
    if (array_key_exists('isLocked', $bucket->info()['retentionPolicy']) &&
        $bucket->info()['retentionPolicy']['isLocked']) {
        printf('Retention Policy is locked' . PHP_EOL);
    }
    if ($bucket->info()['retentionPolicy']['effectiveTime']) {
        printf('Effective Time: ' . $bucket->info()['retentionPolicy']['effectiveTime'] . PHP_EOL);
    }
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import storage


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

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    bucket.reload()

    print(f"Retention Policy for {bucket_name}")
    print(f"Retention Period: {bucket.retention_period}")
    if bucket.retention_policy_locked:
        print("Retention Policy is locked")

    if bucket.retention_policy_effective_time:
        print(
            f"Effective Time: {bucket.retention_policy_effective_time}"
        )

Ruby

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def get_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

  puts "Retention policy:"
  puts "period: #{bucket.retention_period}"
  puts "effective time: #{bucket.retention_effective_at}"
  puts "policy locked: #{bucket.retention_policy_locked?}"
end

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 원하는 fields가 포함된 GET 버킷 요청으로 JSON API를 호출합니다.

    curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=retentionPolicy"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰의 이름입니다.
    • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.

    버킷에 보관 정책이 설정되어 있으면 다음 예와 같은 응답이 표시됩니다.

    {
      "retentionPolicy": {
          "retentionPeriod": "TIME_IN_SECONDS",
          "effectiveTime": "DATETIME",
          "isLocked": "BOOLEAN"
       },
    }

XML API

XML API는 버킷의 보관 정책을 보는 데 사용할 수 없습니다. 대신 Google Cloud 콘솔과 같은 다른 Cloud Storage 도구 중 하나를 사용하세요.

다음 단계