객체 수명 주기 관리

개요 구성 샘플

이 페이지에서는 버킷에서 객체 수명 주기 관리를 설정하는 방법과 버킷의 현재 수명 주기 구성을 보는 방법을 설명합니다. 수명 주기 구성은 버킷의 모든 현재 개체와 미래 객체에 적용됩니다.

필요한 역할

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

필수 권한

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

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

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

버킷의 수명 주기 구성 설정

콘솔

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

    버킷으로 이동

  2. 버킷 목록에서 사용 설정하려는 버킷을 찾고 버킷 이름을 클릭합니다.

  3. 수명 주기 탭을 클릭합니다.

    수명 주기 규칙 페이지가 나타납니다. 여기에서 기존 규칙을 수정하거나 삭제할 수 있습니다. 새 규칙을 추가하려면 다음 안내를 따르세요.

  4. 규칙 추가를 클릭합니다.

  5. 나타나는 페이지에서 구성을 지정합니다.

    1. 객체가 조건을 충족할 때 수행할 작업을 선택합니다.

    2. 계속을 클릭합니다.

    3. 작업이 수행되는 조건을 선택합니다.

    4. 계속을 클릭합니다.

    5. 만들기를 클릭합니다.

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

명령줄

  1. 적용하려는 수명 주기 구성 규칙으로 JSON 파일을 만듭니다. 샘플 JSON 파일은 구성 예시를 참조하세요.

  2. gcloud storage buckets update 명령어를 --lifecycle-file 플래그와 함께 사용합니다.

    gcloud storage buckets update gs://BUCKET_NAME --lifecycle-file=LIFECYCLE_CONFIG_FILE

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

    • BUCKET_NAME은 관련 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • LIFECYCLE_CONFIG_FILE은 1단계에서 만든 JSON 파일의 경로입니다.

클라이언트 라이브러리

C++

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

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

다음 샘플에서는 버킷에 수명 주기 구성을 설정합니다.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  gcs::BucketLifecycle bucket_lifecycle_rules = gcs::BucketLifecycle{
      {gcs::LifecycleRule(gcs::LifecycleRule::ConditionConjunction(
                              gcs::LifecycleRule::MaxAge(30),
                              gcs::LifecycleRule::IsLive(true)),
                          gcs::LifecycleRule::Delete())}};

  StatusOr<gcs::BucketMetadata> updated_metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetLifecycle(bucket_lifecycle_rules));
  if (!updated_metadata) throw std::move(updated_metadata).status();

  if (!updated_metadata->has_lifecycle() ||
      updated_metadata->lifecycle().rule.empty()) {
    std::cout << "Bucket lifecycle management is not enabled for bucket "
              << updated_metadata->name() << ".\n";
    return;
  }
  std::cout << "Successfully enabled bucket lifecycle management for bucket "
            << updated_metadata->name() << ".\n";
  std::cout << "The bucket lifecycle rules are";
  for (auto const& kv : updated_metadata->lifecycle().rule) {
    std::cout << "\n " << kv.condition() << ", " << kv.action();
  }
  std::cout << "\n";
}

다음 샘플에서는 버킷에서 모든 기존 수명 주기 구성을 삭제합니다.

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

  std::cout << "Successfully disabled bucket lifecycle management for bucket "
            << updated_metadata->name() << ".\n";
}

C#

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

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

다음 샘플에서는 버킷에 수명 주기 구성을 설정합니다.


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

public class EnableBucketLifecycleManagementSample
{
    public Bucket EnableBucketLifecycleManagement(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.Lifecycle = new Bucket.LifecycleData
        {
            Rule = new List<Bucket.LifecycleData.RuleData>
            {
                new Bucket.LifecycleData.RuleData
                {
                    Condition = new Bucket.LifecycleData.RuleData.ConditionData { Age = 100 },
                    Action = new Bucket.LifecycleData.RuleData.ActionData { Type = "Delete" }
                }
            }
        };
        bucket = storage.UpdateBucket(bucket);

        Console.WriteLine($"Lifecycle management is enabled for bucket {bucketName} and the rules are:");
        foreach (var rule in bucket.Lifecycle.Rule)
        {
            Console.WriteLine("Action:");
            Console.WriteLine($"Type: {rule.Action.Type}");
            Console.WriteLine($"Storage Class: {rule.Action.StorageClass}");

            Console.WriteLine("Condition:");
            Console.WriteLine($"Age: \t{rule.Condition.Age}");
            Console.WriteLine($"Created Before: \t{rule.Condition.CreatedBefore}");
            Console.WriteLine($"Time Before: \t{rule.Condition.CustomTimeBefore}");
            Console.WriteLine($"Days Since Custom Time: \t{rule.Condition.DaysSinceCustomTime}");
            Console.WriteLine($"Days Since Non-current Time: \t{rule.Condition.DaysSinceNoncurrentTime}");
            Console.WriteLine($"IsLive: \t{rule.Condition.IsLive}");
            Console.WriteLine($"Storage Class: \t{rule.Condition.MatchesStorageClass}");
            Console.WriteLine($"Noncurrent Time Before: \t{rule.Condition.NoncurrentTimeBefore}");
            Console.WriteLine($"Newer Versions: \t{rule.Condition.NumNewerVersions}");
        }
        return bucket;
    }
}

다음 샘플에서는 버킷에서 모든 기존 수명 주기 구성을 삭제합니다.


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

public class DisableBucketLifecycleManagementSample
{
    public Bucket DisableBucketLifecycleManagement(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.Lifecycle = null;
        bucket = storage.UpdateBucket(bucket);

        Console.WriteLine($"Lifecycle management is disabled for bucket {bucketName}.");
        return bucket;
    }
}

Go

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

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

다음 샘플에서는 버킷에 수명 주기 구성을 설정합니다.

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

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

// enableBucketLifecycleManagement adds a lifecycle delete rule with the
// condition that the object is 100 days old.
func enableBucketLifecycleManagement(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{
		Lifecycle: &storage.Lifecycle{
			Rules: []storage.LifecycleRule{
				{
					Action: storage.LifecycleAction{Type: "Delete"},
					Condition: storage.LifecycleCondition{
						AgeInDays: 100,
					},
				},
			},
		},
	}

	attrs, err := bucket.Update(ctx, bucketAttrsToUpdate)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Lifecycle management is enabled for bucket %v\n and the rules are:\n", bucketName)
	for _, rule := range attrs.Lifecycle.Rules {
		fmt.Fprintf(w, "Action: %v\n", rule.Action)
		fmt.Fprintf(w, "Condition: %v\n", rule.Condition)
	}

	return nil
}

다음 샘플에서는 버킷에서 모든 기존 수명 주기 구성을 삭제합니다.

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

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

// disableBucketLifecycleManagement removes all existing lifecycle rules
// from the bucket.
func disableBucketLifecycleManagement(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{
		Lifecycle: &storage.Lifecycle{},
	}

	_, err = bucket.Update(ctx, bucketAttrsToUpdate)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Lifecycle management is disabled for bucket %v.\n", bucketName)

	return nil
}

Java

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

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

다음 샘플에서는 버킷에 수명 주기 구성을 설정합니다.

import static com.google.cloud.storage.BucketInfo.LifecycleRule.LifecycleAction;
import static com.google.cloud.storage.BucketInfo.LifecycleRule.LifecycleCondition;

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo.LifecycleRule;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.common.collect.ImmutableList;

public class EnableLifecycleManagement {
  public static void enableLifecycleManagement(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);

    // See the LifecycleRule documentation for additional info on what you can do with lifecycle
    // management rules. This one deletes objects that are over 100 days old.
    // https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/storage/BucketInfo.LifecycleRule.html
    bucket
        .toBuilder()
        .setLifecycleRules(
            ImmutableList.of(
                new LifecycleRule(
                    LifecycleAction.newDeleteAction(),
                    LifecycleCondition.newBuilder().setAge(100).build())))
        .build()
        .update();

    System.out.println("Lifecycle management was enabled and configured for bucket " + bucketName);
  }
}

다음 샘플에서는 버킷에서 모든 기존 수명 주기 구성을 삭제합니다.

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

public class DisableLifecycleManagement {
  public static void disableLifecycleManagement(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();
    // first look up the bucket, so we will have its metageneration
    Bucket bucket = storage.get(bucketName);
    storage.update(
        bucket.toBuilder().deleteLifecycleRules().build(),
        BucketTargetOption.metagenerationMatch());

    System.out.println("Lifecycle management was 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 enableBucketLifecycleManagement() {
  const [metadata] = await storage.bucket(bucketName).addLifecycleRule({
    action: {
      type: 'Delete',
    },
    condition: {age: 100},
  });

  console.log(
    `Lifecycle management is enabled for bucket ${bucketName} and the rules are:`
  );

  console.log(metadata.lifecycle.rule);
}

enableBucketLifecycleManagement().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 disableBucketLifecycleManagement() {
  await storage.bucket(bucketName).setMetadata({lifecycle: null});

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

disableBucketLifecycleManagement().catch(console.error);

PHP

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

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

다음 샘플에서는 버킷에 수명 주기 구성을 설정합니다.

use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Storage\Bucket;

/**
 * Enable bucket lifecycle management.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function enable_bucket_lifecycle_management(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    $lifecycle = Bucket::lifecycle()
        ->addDeleteRule([
            'age' => 100
        ]);

    $bucket->update([
        'lifecycle' => $lifecycle
    ]);

    $lifecycle = $bucket->currentLifecycle();

    printf('Lifecycle management is enabled for bucket %s and the rules are:' . PHP_EOL, $bucketName);
    foreach ($lifecycle as $rule) {
        print_r($rule);
        print(PHP_EOL);
    }
}

다음 샘플에서는 버킷에서 모든 기존 수명 주기 구성을 삭제합니다.

use Google\Cloud\Storage\StorageClient;

/**
 * Disable bucket lifecycle management.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function disable_bucket_lifecycle_management(string $bucketName): void
{
    $storage = new StorageClient();

    $bucket = $storage->bucket($bucketName);

    $bucket->update([
        'lifecycle' => null
    ]);

    printf('Lifecycle management is disabled for bucket %s.' . PHP_EOL, $bucketName);
}

Python

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

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

다음 샘플에서는 버킷에 수명 주기 구성을 설정합니다.

from google.cloud import storage


def enable_bucket_lifecycle_management(bucket_name):
    """Enable lifecycle management for a bucket"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    rules = bucket.lifecycle_rules

    print(f"Lifecycle management rules for bucket {bucket_name} are {list(rules)}")
    bucket.add_lifecycle_delete_rule(age=2)
    bucket.patch()

    rules = bucket.lifecycle_rules
    print(f"Lifecycle management is enable for bucket {bucket_name} and the rules are {list(rules)}")

    return bucket

다음 샘플에서는 버킷에서 모든 기존 수명 주기 구성을 삭제합니다.

from google.cloud import storage


def disable_bucket_lifecycle_management(bucket_name):
    """Disable lifecycle management for a bucket"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.clear_lifecyle_rules()
    bucket.patch()
    rules = bucket.lifecycle_rules

    print(f"Lifecycle management is disable for bucket {bucket_name} and the rules are {list(rules)}")
    return bucket

Ruby

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

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

다음 샘플에서는 버킷에 수명 주기 구성을 설정합니다.

def enable_bucket_lifecycle_management bucket_name:
  # Enable lifecycle management for a bucket
  # 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

  rules = bucket.lifecycle do |l|
    l.add_delete_rule age: 2
  end

  puts "Lifecycle management is enabled for bucket #{bucket_name} and the rules are #{rules}"
end

다음 샘플에서는 버킷에서 모든 기존 수명 주기 구성을 삭제합니다.

def disable_bucket_lifecycle_management bucket_name:
  # Disable lifecycle management for a bucket
  # 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.lifecycle do |l|
    l.clear
  end

  puts "Lifecycle management is disabled for bucket #{bucket_name}"
end

Terraform

Terraform 리소스를 사용하여 Terraform에서 관리하는 버킷의 수명 주기 구성을 설정할 수 있습니다. Terraform에서 아직 관리하지 않는 기존 버킷에 수명 주기 구성을 설정하려면 먼저 기존 버킷을 가져와야 합니다.

Terraform에서 수명 주기 조건이 지원되는지 확인하려면 condition 블록에 대한 Terraform 문서를 참조하세요.

resource "random_id" "bucket_prefix" {
  byte_length = 8
}

resource "google_storage_bucket" "auto_expire" {
  provider                    = google-beta
  name                        = "${random_id.bucket_prefix.hex}-example-bucket"
  location                    = "US"
  uniform_bucket_level_access = true

  lifecycle_rule {
    condition {
      age = 3
    }
    action {
      type = "Delete"
    }
  }
}

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 적용하려는 수명 주기 구성 규칙으로 JSON 파일을 만듭니다. 샘플 JSON 파일은 구성 예시를 참조하세요.

  3. cURL을 사용하여 PATCH 버킷 요청으로 JSON API를 호출합니다.

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

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

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

XML API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 적용하려는 수명 주기 구성 규칙으로 XML 파일을 만듭니다. 샘플 XML 파일은 구성 예시를 참조하세요.

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

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

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

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

버킷의 수명 주기 구성 확인

콘솔

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

    버킷으로 이동

  2. 버킷 목록에서 수명 주기 열에 각 버킷의 수명 주기 상태가 표시됩니다.

    이 상태를 클릭하여 규칙을 추가, 보기, 수정, 삭제할 수 있습니다.

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

명령줄

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

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

여기서 BUCKET_NAME은 수명 주기 구성을 보려는 버킷의 이름입니다. 예를 들면 my-bucket입니다.

클라이언트 라이브러리

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> updated_metadata =
      client.GetBucketMetadata(bucket_name);
  if (!updated_metadata) throw std::move(updated_metadata).status();

  if (!updated_metadata->has_lifecycle() ||
      updated_metadata->lifecycle().rule.empty()) {
    std::cout << "Bucket lifecycle management is not enabled for bucket "
              << updated_metadata->name() << ".\n";
    return;
  }
  std::cout << "Bucket lifecycle management is enabled for bucket "
            << updated_metadata->name() << ".\n";
  std::cout << "The bucket lifecycle rules are";
  for (auto const& kv : updated_metadata->lifecycle().rule) {
    std::cout << "\n " << kv.condition() << ", " << kv.action();
  }
  std::cout << "\n";
}

C#

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

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

버킷의 수명 주기 정책을 보려면 버킷의 메타데이터 표시 안내를 따라 응답에서 수명 주기 정책 필드를 찾습니다.

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

public class GetBucketMetadataSample
{
    public Bucket GetBucketMetadata(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });
        Console.WriteLine($"Bucket:\t{bucket.Name}");
        Console.WriteLine($"Acl:\t{bucket.Acl}");
        Console.WriteLine($"Billing:\t{bucket.Billing}");
        Console.WriteLine($"Cors:\t{bucket.Cors}");
        Console.WriteLine($"DefaultEventBasedHold:\t{bucket.DefaultEventBasedHold}");
        Console.WriteLine($"DefaultObjectAcl:\t{bucket.DefaultObjectAcl}");
        Console.WriteLine($"Encryption:\t{bucket.Encryption}");
        if (bucket.Encryption != null)
        {
            Console.WriteLine($"KmsKeyName:\t{bucket.Encryption.DefaultKmsKeyName}");
        }
        Console.WriteLine($"Id:\t{bucket.Id}");
        Console.WriteLine($"Kind:\t{bucket.Kind}");
        Console.WriteLine($"Lifecycle:\t{bucket.Lifecycle}");
        Console.WriteLine($"Location:\t{bucket.Location}");
        Console.WriteLine($"LocationType:\t{bucket.LocationType}");
        Console.WriteLine($"Logging:\t{bucket.Logging}");
        Console.WriteLine($"Metageneration:\t{bucket.Metageneration}");
        Console.WriteLine($"Owner:\t{bucket.Owner}");
        Console.WriteLine($"ProjectNumber:\t{bucket.ProjectNumber}");
        Console.WriteLine($"RetentionPolicy:\t{bucket.RetentionPolicy}");
        Console.WriteLine($"SelfLink:\t{bucket.SelfLink}");
        Console.WriteLine($"StorageClass:\t{bucket.StorageClass}");
        Console.WriteLine($"TimeCreated:\t{bucket.TimeCreated}");
        Console.WriteLine($"Updated:\t{bucket.Updated}");
        Console.WriteLine($"Versioning:\t{bucket.Versioning}");
        Console.WriteLine($"Website:\t{bucket.Website}");
        Console.WriteLine($"TurboReplication:\t{bucket.Rpo}");
        if (bucket.Labels != null)
        {
            Console.WriteLine("Labels:");
            foreach (var label in bucket.Labels)
            {
                Console.WriteLine($"{label.Key}:\t{label.Value}");
            }
        }
        return bucket;
    }
}

Go

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

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

버킷의 수명 주기 정책을 보려면 버킷의 메타데이터 표시 안내를 따라 응답에서 수명 주기 정책 필드를 찾습니다.
import (
	"context"
	"fmt"
	"io"
	"time"

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

// getBucketMetadata gets the bucket metadata.
func getBucketMetadata(w io.Writer, bucketName string) (*storage.BucketAttrs, error) {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return nil, fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
	}
	fmt.Fprintf(w, "BucketName: %v\n", attrs.Name)
	fmt.Fprintf(w, "Location: %v\n", attrs.Location)
	fmt.Fprintf(w, "LocationType: %v\n", attrs.LocationType)
	fmt.Fprintf(w, "StorageClass: %v\n", attrs.StorageClass)
	fmt.Fprintf(w, "Turbo replication (RPO): %v\n", attrs.RPO)
	fmt.Fprintf(w, "TimeCreated: %v\n", attrs.Created)
	fmt.Fprintf(w, "Metageneration: %v\n", attrs.MetaGeneration)
	fmt.Fprintf(w, "PredefinedACL: %v\n", attrs.PredefinedACL)
	if attrs.Encryption != nil {
		fmt.Fprintf(w, "DefaultKmsKeyName: %v\n", attrs.Encryption.DefaultKMSKeyName)
	}
	if attrs.Website != nil {
		fmt.Fprintf(w, "IndexPage: %v\n", attrs.Website.MainPageSuffix)
		fmt.Fprintf(w, "NotFoundPage: %v\n", attrs.Website.NotFoundPage)
	}
	fmt.Fprintf(w, "DefaultEventBasedHold: %v\n", attrs.DefaultEventBasedHold)
	if attrs.RetentionPolicy != nil {
		fmt.Fprintf(w, "RetentionEffectiveTime: %v\n", attrs.RetentionPolicy.EffectiveTime)
		fmt.Fprintf(w, "RetentionPeriod: %v\n", attrs.RetentionPolicy.RetentionPeriod)
		fmt.Fprintf(w, "RetentionPolicyIsLocked: %v\n", attrs.RetentionPolicy.IsLocked)
	}
	fmt.Fprintf(w, "RequesterPays: %v\n", attrs.RequesterPays)
	fmt.Fprintf(w, "VersioningEnabled: %v\n", attrs.VersioningEnabled)
	if attrs.Logging != nil {
		fmt.Fprintf(w, "LogBucket: %v\n", attrs.Logging.LogBucket)
		fmt.Fprintf(w, "LogObjectPrefix: %v\n", attrs.Logging.LogObjectPrefix)
	}
	if attrs.CORS != nil {
		fmt.Fprintln(w, "CORS:")
		for _, v := range attrs.CORS {
			fmt.Fprintf(w, "\tMaxAge: %v\n", v.MaxAge)
			fmt.Fprintf(w, "\tMethods: %v\n", v.Methods)
			fmt.Fprintf(w, "\tOrigins: %v\n", v.Origins)
			fmt.Fprintf(w, "\tResponseHeaders: %v\n", v.ResponseHeaders)
		}
	}
	if attrs.Labels != nil {
		fmt.Fprintf(w, "\n\n\nLabels:")
		for key, value := range attrs.Labels {
			fmt.Fprintf(w, "\t%v = %v\n", key, value)
		}
	}
	return attrs, nil
}

Java

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

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

버킷의 수명 주기 정책을 보려면 버킷의 메타데이터 표시 안내를 따라 응답에서 수명 주기 정책 필드를 찾습니다.

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;

public class GetBucketMetadata {
  public static void getBucketMetadata(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();

    // Select all fields. Fields can be selected individually e.g. Storage.BucketField.NAME
    Bucket bucket =
        storage.get(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.values()));

    // Print bucket metadata
    System.out.println("BucketName: " + bucket.getName());
    System.out.println("DefaultEventBasedHold: " + bucket.getDefaultEventBasedHold());
    System.out.println("DefaultKmsKeyName: " + bucket.getDefaultKmsKeyName());
    System.out.println("Id: " + bucket.getGeneratedId());
    System.out.println("IndexPage: " + bucket.getIndexPage());
    System.out.println("Location: " + bucket.getLocation());
    System.out.println("LocationType: " + bucket.getLocationType());
    System.out.println("Metageneration: " + bucket.getMetageneration());
    System.out.println("NotFoundPage: " + bucket.getNotFoundPage());
    System.out.println("RetentionEffectiveTime: " + bucket.getRetentionEffectiveTime());
    System.out.println("RetentionPeriod: " + bucket.getRetentionPeriod());
    System.out.println("RetentionPolicyIsLocked: " + bucket.retentionPolicyIsLocked());
    System.out.println("RequesterPays: " + bucket.requesterPays());
    System.out.println("SelfLink: " + bucket.getSelfLink());
    System.out.println("StorageClass: " + bucket.getStorageClass().name());
    System.out.println("TimeCreated: " + bucket.getCreateTime());
    System.out.println("VersioningEnabled: " + bucket.versioningEnabled());
    System.out.println("ObjectRetention: " + bucket.getObjectRetention());
    if (bucket.getLabels() != null) {
      System.out.println("\n\n\nLabels:");
      for (Map.Entry<String, String> label : bucket.getLabels().entrySet()) {
        System.out.println(label.getKey() + "=" + label.getValue());
      }
    }
    if (bucket.getLifecycleRules() != null) {
      System.out.println("\n\n\nLifecycle Rules:");
      for (BucketInfo.LifecycleRule rule : bucket.getLifecycleRules()) {
        System.out.println(rule);
      }
    }
  }
}

Node.js

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

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

버킷의 수명 주기 정책을 보려면 버킷의 메타데이터 표시 안내를 따라 응답에서 수명 주기 정책 필드를 찾습니다.
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

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

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

  // Get Bucket Metadata
  const [metadata] = await storage.bucket(bucketName).getMetadata();

  console.log(JSON.stringify(metadata, null, 2));
}

PHP

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

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

버킷의 수명 주기 정책을 보려면 버킷의 메타데이터 표시 안내를 따라 응답에서 수명 주기 정책 필드를 찾습니다.
use Google\Cloud\Storage\StorageClient;

/**
 * Get bucket metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function get_bucket_metadata(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $info = $bucket->info();

    printf('Bucket Metadata: %s' . PHP_EOL, print_r($info));
}

Python

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

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

버킷의 수명 주기 정책을 보려면 버킷의 메타데이터 표시 안내를 따라 응답에서 수명 주기 정책 필드를 찾습니다.

from google.cloud import storage


def bucket_metadata(bucket_name):
    """Prints out a bucket's metadata."""
    # bucket_name = 'your-bucket-name'

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

    print(f"ID: {bucket.id}")
    print(f"Name: {bucket.name}")
    print(f"Storage Class: {bucket.storage_class}")
    print(f"Location: {bucket.location}")
    print(f"Location Type: {bucket.location_type}")
    print(f"Cors: {bucket.cors}")
    print(f"Default Event Based Hold: {bucket.default_event_based_hold}")
    print(f"Default KMS Key Name: {bucket.default_kms_key_name}")
    print(f"Metageneration: {bucket.metageneration}")
    print(
        f"Public Access Prevention: {bucket.iam_configuration.public_access_prevention}"
    )
    print(f"Retention Effective Time: {bucket.retention_policy_effective_time}")
    print(f"Retention Period: {bucket.retention_period}")
    print(f"Retention Policy Locked: {bucket.retention_policy_locked}")
    print(f"Requester Pays: {bucket.requester_pays}")
    print(f"Self Link: {bucket.self_link}")
    print(f"Time Created: {bucket.time_created}")
    print(f"Versioning Enabled: {bucket.versioning_enabled}")
    print(f"Labels: {bucket.labels}")

Ruby

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

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

버킷의 수명 주기 정책을 보려면 버킷의 메타데이터 표시 안내를 따라 응답에서 수명 주기 정책 필드를 찾습니다.
def get_bucket_metadata 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 "ID:                       #{bucket.id}"
  puts "Name:                     #{bucket.name}"
  puts "Storage Class:            #{bucket.storage_class}"
  puts "Location:                 #{bucket.location}"
  puts "Location Type:            #{bucket.location_type}"
  puts "Cors:                     #{bucket.cors}"
  puts "Default Event Based Hold: #{bucket.default_event_based_hold?}"
  puts "Default KMS Key Name:     #{bucket.default_kms_key}"
  puts "Logging Bucket:           #{bucket.logging_bucket}"
  puts "Logging Prefix:           #{bucket.logging_prefix}"
  puts "Metageneration:           #{bucket.metageneration}"
  puts "Retention Effective Time: #{bucket.retention_effective_at}"
  puts "Retention Period:         #{bucket.retention_period}"
  puts "Retention Policy Locked:  #{bucket.retention_policy_locked?}"
  puts "Requester Pays:           #{bucket.requester_pays}"
  puts "Self Link:                #{bucket.api_url}"
  puts "Time Created:             #{bucket.created_at}"
  puts "Versioning Enabled:       #{bucket.versioning?}"
  puts "Index Page:               #{bucket.website_main}"
  puts "Not Found Page:           #{bucket.website_404}"
  puts "Labels:"
  bucket.labels.each do |key, value|
    puts " - #{key} = #{value}"
  end
  puts "Lifecycle Rules:"
  bucket.lifecycle.each do |rule|
    puts "#{rule.action} - #{rule.storage_class} - #{rule.age} - #{rule.matches_storage_class}"
  end
end

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

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

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

XML API

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

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

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

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

다음 단계