階層型名前空間が有効なバケットの作成と管理

このページでは、階層型名前空間を有効にしてバケットを作成、一覧表示、削除する方法について説明します。

バケットを作成する

このセクションでは、階層型名前空間が有効な状態でバケットを作成する方法について説明します。

コマンドライン

  1. Google Cloud コンソールで、「Cloud Shell をアクティブにする」をクリックします。

    Cloud Shell をアクティブにする

    Google Cloud コンソールの下部で Cloud Shell セッションが開始し、コマンドライン プロンプトが表示されます。Cloud Shell はシェル環境です。Google Cloud CLI がすでにインストールされており、現在のプロジェクトの値もすでに設定されています。セッションが初期化されるまで数秒かかることがあります。

  2. 開発環境で、gcloud alpha storage buckets create コマンドを実行します。

    gcloud alpha storage buckets create gs://BUCKET_NAME --location=BUCKET_LOCATION --uniform-bucket-level-access --enable-hierarchical-namespace

    ここで

    • BUCKET_NAME は、バケットに付ける名前で、命名要件の対象となります。例: my-bucket
    • BUCKET_LOCATION は、バケットのロケーションです。例: us-east1
    • --uniform-bucket-level-access: バケットの均一なバケットレベルのアクセスを有効にします。
    • --enable-hierarchical-namespace: バケットの階層型名前空間を有効にします。

    リクエストが成功すると、コマンドから次のメッセージが返されます。

    Creating gs://BUCKET_NAME/...

    次のフラグを設定すると、バケットの作成をより細かくコントロールできます。

    • --project: バケットが関連付けられるプロジェクト ID またはプロジェクト番号を指定します。例: my-project
    • --default-storage-class: バケットのデフォルトのストレージ クラスを指定します。例: STANDARD
    • Google Cloud CLI を使用してバケットを作成するオプションの完全なリストについては、buckets create オプションをご覧ください。

    例:

    gcloud alpha storage buckets create gs://BUCKET_NAME --project=PROJECT_ID --default-storage-class=STORAGE_CLASS --location=BUCKET_LOCATION --uniform-bucket-level-access

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto metadata = client.CreateBucket(
      bucket_name,
      gcs::BucketMetadata()
          .set_hierarchical_namespace(gcs::BucketHierarchicalNamespace{true})
          .set_iam_configuration(gcs::BucketIamConfiguration{
              gcs::UniformBucketLevelAccess{true, {}}, absl::nullopt}));
  if (!metadata) throw std::move(metadata).status();

  std::cout << "Bucket " << metadata->name() << " created."
            << "\nFull Metadata: " << *metadata << "\n";
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

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

// createBucketHierarchicalNamespace creates a new bucket with hierarchical
// namespace features enabled.
func createBucketHierarchicalNamespace(w io.Writer, projectID, bucketName string) error {
	// projectID := "my-project-id"
	// 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*30)
	defer cancel()

	attrs := &storage.BucketAttrs{
		HierarchicalNamespace: &storage.HierarchicalNamespace{
			Enabled: true,
		},
		// Hierarchical namespace buckets must use uniform bucket-level access.
		UniformBucketLevelAccess: storage.UniformBucketLevelAccess{
			Enabled: true,
		},
	}
	bucket := client.Bucket(bucketName)
	if err := bucket.Create(ctx, projectID, attrs); err != nil {
		return fmt.Errorf("Bucket(%q).Create: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Created bucket %v with hierarchical namespace enabled\n", bucketName)
	return 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.BucketInfo.HierarchicalNamespace;
import com.google.cloud.storage.BucketInfo.IamConfiguration;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public final class CreateHierarchicalNamespaceBucket {

  public static void createHierarchicalNamespaceBucket(String projectId, String bucketName)
      throws Exception {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";
    StorageOptions storageOptions = StorageOptions.newBuilder().setProjectId(projectId).build();
    try (Storage storage = storageOptions.getService()) {

      BucketInfo bucketInfo =
          BucketInfo.newBuilder(bucketName)
              .setIamConfiguration(
                  // Hierarchical namespace buckets must use uniform bucket-level access.
                  IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build())
              .setHierarchicalNamespace(HierarchicalNamespace.newBuilder().setEnabled(true).build())
              .build();

      Bucket bucket = storage.create(bucketInfo);

      System.out.printf(
          "Created bucket %s with Hierarchical Namespace enabled.%n", bucket.getName());
    }
  }
}

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
// The bucket in the sample below will be created in the project associated with this client.
// For more information, please see https://cloud.google.com/docs/authentication/production or https://googleapis.dev/nodejs/storage/latest/Storage.html
const storage = new Storage();

async function createBucketWithHierarchicalNamespace() {
  const [bucket] = await storage.createBucket(bucketName, {
    iamConfiguration: {
      uniformBucketLevelAccess: {
        enabled: true,
      },
    },
    hierarchicalNamespace: {
      enabled: true,
    },
  });

  console.log(
    `Created '${bucket.name}' with hierarchical namespace enabled.`
  );
}

createBucketWithHierarchicalNamespace().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

use Google\Cloud\Storage\StorageClient;

/**
 * Create a new bucket with Hierarchical Namespace enabled.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function create_bucket_hierarchical_namespace(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->createBucket($bucketName, [
        'hierarchicalNamespace' => ['enabled' => true],
        'iamConfiguration' => ['uniformBucketLevelAccess' => ['enabled' => true]]
    ]);

    printf('Created bucket %s with Hierarchical Namespace enabled.', $bucket->name());
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import storage


def create_bucket_hierarchical_namespace(bucket_name):
    """Creates a bucket with hierarchical namespace enabled."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    bucket.iam_configuration.uniform_bucket_level_access_enabled = True
    bucket.hierarchical_namespace_enabled = True
    bucket.create()

    print(f"Created bucket {bucket_name} with hierarchical namespace enabled.")

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def create_bucket_hierarchical_namespace bucket_name:
  # The ID to give your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  hierarchical_namespace = Google::Apis::StorageV1::Bucket::HierarchicalNamespace.new enabled: true

  storage.create_bucket bucket_name do |b|
    b.uniform_bucket_level_access = true
    b.hierarchical_namespace = hierarchical_namespace
  end

  puts "Created bucket #{bucket_name} with Hierarchical Namespace enabled."
end

REST API

JSON API

  1. Authorization ヘッダーのアクセス トークンを生成するには、gcloud CLI のインストールと初期化を行います。

    OAuth 2.0 Playground を使用してアクセス トークンを作成し、Authorization ヘッダーに含めることもできます。

  2. バケットの設定を含む JSON ファイルを作成します。この設定には、バケットの name を含める必要があります。設定の一覧については、Buckets:Insert のドキュメントをご覧ください。一般的な設定は次のとおりです。
  3. {
          "name": "BUCKET_NAME",
          "location": "BUCKET_LOCATION",
          "storageClass": "STORAGE_CLASS",
          "hierarchicalNamespace": {
              "enabled": "BOOLEAN"
            },
          }
        

    ここで

  4. cURL を使用して JSON API を呼び出します。
    curl -X POST --data-binary @JSON_FILE_NAME \
         -H "Authorization: Bearer $(gcloud auth print-access-token)" \
         -H "Content-Type: application/json" \
         "https://storage.googleapis.com/storage/v1/b?project=PROJECT_IDENTIFIER"

    ここで

    • JSON_FILE_NAME は、バケット設定を含む JSON ファイルの名前です。
    • PROJECT_IDENTIFIER は、バケットが関連付けられているプロジェクトの ID または番号です。例: my-project

バケットを一覧表示する

階層型名前空間が有効になっているバケットを一覧表示するプロセスは、階層型名前空間が有効になっていないバケットの場合と同じです。バケットを一覧表示する手順については、バケットを一覧表示するをご覧ください。

バケットを削除する

バケットに空のフォルダのみが含まれ、オブジェクトやマネージド フォルダが含まれていない場合は、バケットを削除できます。

階層型名前空間が有効になっているバケットを削除するプロセスは、階層型名前空間が有効になっていないバケットの場合と同じです。バケットを削除する手順については、バケットを削除するをご覧ください。

次のステップ

使ってみる

Google Cloud を初めて使用する場合は、アカウントを作成して、実際のシナリオでの Cloud Storage のパフォーマンスを評価してください。新規のお客様には、ワークロードの実行、テスト、デプロイができる無料クレジット $300 分を差し上げます。

Cloud Storage を無料で試す