객체 버전 관리 사용

개요 사용

이 페이지에서는 버킷에서 객체 버전 관리 상태를 사용 설정, 중지, 확인하는 방법을 설명합니다. 객체 버전 관리에서 보관되는 객체를 나열, 복원, 삭제하는 방법은 버전 관리된 객체 작업을 참조하세요.

필요한 역할

버킷에서 객체 버전 관리를 설정하고 관리하는 데 필요한 권한을 얻으려면 관리자에게 버킷 또는 버킷을 포함하는 프로젝트에 대해 스토리지 관리자(roles/storage.admin) IAM 역할을 부여해 달라고 요청하세요. 이 사전 정의된 역할에는 버킷에 대해 객체 버전 관리를 설정하고 관리하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 확장하세요.

필수 권한

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

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

버킷의 역할 부여에 대한 자세한 내용은 버킷에 IAM 사용을 참조하세요. 프로젝트에 대해 역할을 부여하는 방법은 프로젝트에 대한 액세스 관리를 참조하세요.

버킷에 객체 버전 관리 설정

콘솔

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

    버킷으로 이동

  2. 버킷 목록에서 객체 버전 관리를 사용 설정하거나 중지할 버킷의 이름을 클릭합니다.

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

    객체 버전 관리의 현재 상태는 객체 버전 관리 섹션에서 확인할 수 있습니다.

  4. 객체 버전 관리 섹션에서 현재 상태를 클릭하여 변경합니다.

    객체 버전 관리 대화상자가 나타납니다.

    1. 객체 버전 관리를 사용 설정하고 스토리지 비용을 최소화하려면 권장 수명 주기 규칙을 추가하여 버전 비용 관리 체크박스를 선택합니다.
  5. 확인을 클릭합니다.

명령줄

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

gcloud storage buckets update gs://BUCKET_NAME FLAG

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

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

  • FLAG--versioning이면 객체 버전 관리를 사용 설정하고 --no-versioning이면 사용 중지합니다.

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

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

  if (patched->versioning().has_value()) {
    std::cout << "Object versioning for bucket " << bucket_name << " is "
              << (patched->versioning()->enabled ? "enabled" : "disabled")
              << "\n";
  } else {
    std::cout << "Object versioning for bucket " << bucket_name
              << " is disabled.\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().SetVersioning(
          gcs::BucketVersioning{false}),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!patched) throw std::move(patched).status();

  auto versioning =
      patched->versioning().value_or(gcs::BucketVersioning{false});
  std::cout << "Object versioning for bucket " << bucket_name << " is "
            << (versioning.enabled ? "enabled" : "disabled") << "\n";
}

C#

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

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

다음 샘플은 버킷에서 객체 버전 관리를 사용 설정합니다.


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

public class BucketEnableVersioningSample
{
	public Bucket BucketEnableVersioning(string bucketName = "your-bucket-name")
	{
		var storage = StorageClient.Create();
		var bucket = storage.GetBucket(bucketName);

		if (bucket.Versioning == null)
		{
			bucket.Versioning = new Bucket.VersioningData();
		}
		bucket.Versioning.Enabled = true;

		bucket = storage.UpdateBucket(bucket);
		Console.WriteLine($"Versioning is now enabled for bucket {bucketName}.");
		return bucket;
	}
}

다음 샘플은 버킷에서 객체 버전 관리를 사용 중지합니다.


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

public class BucketDisableVersioningSample
{
	public Bucket BucketDisableVersioning(string bucketName = "your-bucket-name")
	{
		var storage = StorageClient.Create();
		var bucket = storage.GetBucket(bucketName);

		if (bucket.Versioning?.Enabled != true)
		{
			Console.WriteLine($"Versioning already disabled for bucket {bucketName}.");
		}
		else
		{
        	    bucket.Versioning.Enabled = false;

		    bucket = storage.UpdateBucket(bucket);
                    Console.WriteLine($"Versioning is now disabled for bucket {bucketName}.");
                }
		return bucket;
	}
}

Go

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

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

다음 샘플은 버킷에서 객체 버전 관리를 사용 설정합니다.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// enableVersioning enables object versioning on a bucket.
func enableVersioning(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		VersioningEnabled: true,
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Versioning was enabled for %v\n", bucketName)
	return nil
}

다음 샘플은 버킷에서 객체 버전 관리를 사용 중지합니다.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// disableVersioning disables object versioning on a bucket.
func disableVersioning(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		VersioningEnabled: false,
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Versioning was disabled for %v\n", bucketName)
	return nil
}

Java

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

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

다음 샘플은 버킷에서 객체 버전 관리를 사용 설정합니다.

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

public class EnableBucketVersioning {
  public static void enableBucketVersioning(String projectId, String bucketName) {
    // 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);
    bucket.toBuilder().setVersioningEnabled(true).build().update();

    System.out.println("Versioning is now enabled for bucket " + bucketName);
  }
}

다음 샘플은 버킷에서 객체 버전 관리를 사용 중지합니다.

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

public class DisableBucketVersioning {
  public static void disableBucketVersioning(String projectId, String bucketName) {
    // 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);
    bucket.toBuilder().setVersioningEnabled(false).build().update();

    System.out.println("Versioning is now disabled for bucket " + bucketName);
  }
}

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 enableBucketVersioning() {
  await storage.bucket(bucketName).setMetadata({
    versioning: {
      enabled: true,
    },
  });

  console.log(`Versioning is enabled for bucket ${bucketName}`);
}

enableBucketVersioning().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 disableBucketVersioning() {
  await storage.bucket(bucketName).setMetadata({
    versioning: {
      enabled: false,
    },
  });

  console.log(`Versioning is disabled for bucket ${bucketName}`);
}

disableBucketVersioning().catch(console.error);

PHP

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

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

다음 샘플은 버킷에서 객체 버전 관리를 사용 설정합니다.

use Google\Cloud\Storage\StorageClient;

/**
 * Enable versioning on the specified bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function enable_versioning(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'versioning' => [
            'enabled' => true,
        ]
    ]);

    printf('Versioning is now enabled for bucket %s', $bucketName);
}

다음 샘플은 버킷에서 객체 버전 관리를 사용 중지합니다.

use Google\Cloud\Storage\StorageClient;

/**
 * Disable versioning of the given bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function disable_versioning(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'versioning' => [
            'enabled' => false,
        ]
    ]);

    printf('Versioning is now disabled for bucket %s', $bucketName);
}

Python

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

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

다음 샘플은 버킷에서 객체 버전 관리를 사용 설정합니다.

from google.cloud import storage


def enable_versioning(bucket_name):
    """Enable versioning for this bucket."""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.versioning_enabled = True
    bucket.patch()

    print(f"Versioning was enabled for bucket {bucket.name}")
    return bucket

다음 샘플은 버킷에서 객체 버전 관리를 사용 중지합니다.

from google.cloud import storage


def disable_versioning(bucket_name):
    """Disable versioning for this bucket."""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.versioning_enabled = False
    bucket.patch()

    print(f"Versioning was disabled for bucket {bucket}")
    return bucket

Ruby

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

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

다음 샘플은 버킷에서 객체 버전 관리를 사용 설정합니다.

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

  bucket.versioning = true

  puts "Versioning was enabled for bucket #{bucket_name}"
end

다음 샘플은 버킷에서 객체 버전 관리를 사용 중지합니다.

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

  bucket.versioning = false

  puts "Versioning was disabled for bucket #{bucket_name}"
end

REST API

JSON API

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

    {
      "versioning": {
        "enabled": STATE
      }
    }

    여기서 STATEtrue 또는 false입니다.

  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=versioning"

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

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

XML API

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

    <VersioningConfiguration>
      <Status>STATE</Status>
    </VersioningConfiguration>

    여기서 STATEEnabled 또는 Suspended입니다.

  3. cURL을 사용하여 PUT 버킷 요청 및 versioning 쿼리 문자열 매개변수로 XML API를 호출합니다.

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?versioning"

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

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

객체 버전 관리가 사용 설정되면 실시간 객체 버전이 대체되거나 삭제될 때마다 해당 버전은 이전 버전이 됩니다.

객체 버전 관리 사용 설정 여부 확인

버킷에서 객체 버전 관리 사용이 설정되었는지 여부를 확인하려면 다음을 따르세요.

콘솔

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

    버킷으로 이동

  2. 버킷 목록의 보호 열에 각 버킷의 객체 버전 관리 상태가 있습니다.

사용 설정하면 객체 버전 관리 텍스트가 나타납니다.

명령줄

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

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

여기서 BUCKET_NAME은 상태를 보려는 버킷의 이름입니다. 예를 들면 my-bucket입니다.

성공하고 객체 버전 관리가 사용 설정되면 다음 예시와 비슷한 응답이 표시됩니다.

versioning:
  enabled: true

성공하고 객체 버전 관리가 사용 설정되지 않으면 다음 예시와 비슷한 응답이 표시됩니다.

null

REST API

JSON API

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

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

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

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

성공하고 객체 버전 관리가 사용 설정되면 다음 예시와 비슷한 응답이 표시됩니다.

{
  "versioning": {
    "enabled": true
  }
}

성공하고 객체 버전 관리가 사용 설정되지 않으면 다음 예시와 비슷한 응답이 표시됩니다.

{}

XML API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET 버킷 요청 및 versioning 쿼리 문자열 매개변수로 XML API를 호출합니다.

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?versioning"

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

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

성공하고 객체 버전 관리가 사용 설정되면 다음 예시와 비슷한 응답이 표시됩니다.

<VersioningConfiguration>
  <Status>Enabled</Status>
</VersioningConfiguration>

성공하고 객체 버전 관리가 사용 설정되지 않으면 다음 예시와 비슷한 응답이 표시됩니다.

<VersioningConfiguration/>

다음 단계