保持ポリシーの使用とロック

概要

このページでは、保持ポリシーを使用したバケットの永続的なロックなど、バケットロック機能の使用方法について説明します。

始める前に

この機能を Cloud Storage で使用する前に、次の要件を満たす必要があります。

  1. Cloud Storage のバケットを表示および更新するための十分な権限がある。

    • バケットを含むプロジェクトを所有している場合は、必要な権限があると考えられます。

    • IAM を使用する場合は、関連するバケットに対する storage.buckets.update 権限と storage.buckets.get 権限が必要です。これらの権限を持つロール(ストレージ管理者など)を取得する手順については、IAM 権限の使用をご覧ください。

    • ACL を使用する場合は、関連するバケットに対する OWNER 権限が必要です。設定方法については、ACL の設定をご覧ください。

  2. バケットでオブジェクトのバージョニングが無効になっている。バケットでオブジェクトのバージョニングが無効になっているかどうかを確認する方法については、オブジェクトのバージョニングを使用するをご覧ください。

バケットに保持ポリシーを設定する

バケットで保持ポリシーを追加、変更、削除するには:

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットのリストで、保持ポリシーを変更するバケットの名前をクリックします。

  3. ページ上部にある [保護] タブを選択します。

  4. [保持ポリシー] セクションで、保持ポリシーを設定します。

    1. 現在バケットに適用されている保持ポリシーがない場合は、[ 保持ポリシーを設定] をクリックします。保持期間の単位と長さを選択します。

    2. バケットに現在適用されている保持ポリシーがセクションに表示されます。[編集] をクリックして保持期間を変更するか、[削除] をクリックして保持ポリシーを完全に削除します。

    Google Cloud コンソールで別の時間単位に変換する方法については、保持期間をご覧ください。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

適切なフラグを指定して、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 を使用して JSON API を呼び出し、PATCH Bucket リクエストを行います。

    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. [ポリシーをロック] をクリックします。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

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 を使用して JSON API を呼び出し、POST Bucket リクエストを行います。

    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。バケットの metageneration 値を確認するには、JSON API を呼び出して、GET Bucket リクエストを行います。

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 Bucket リクエストで 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 ツールを使用してください。

次のステップ