Membuat bucket dengan namespace hierarkis diaktifkan

Halaman ini menjelaskan cara membuat bucket dengan namespace hierarkis diaktifkan.

Peran yang diperlukan

Untuk mendapatkan izin yang diperlukan untuk membuat bucket dengan namespace hierarkis diaktifkan, minta administrator Anda untuk memberi Anda peran IAM Storage Admin (roles/storage.admin) di project. Untuk mengetahui informasi selengkapnya tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

Peran bawaan ini berisi izin storage.buckets.create , yang diperlukan untuk membuat bucket dengan namespace hierarkis yang diaktifkan.

Anda mungkin juga bisa mendapatkan izin ini dengan peran khusus atau peran bawaan lainnya.

Membuat bucket dengan namespace hierarkis diaktifkan

Konsol

Untuk mengaktifkan namespace hierarkis di bucket, mulai dengan mengikuti langkah-langkah untuk membuat bucket baru, lalu lakukan langkah berikut:

  1. Di bagian Pilih cara menyimpan data Anda, temukan bagian Optimalkan penyimpanan untuk beban kerja intensif data, lalu pilih Aktifkan Namespace hierarkis di bucket ini.
  2. Selesaikan langkah-langkah yang tersisa untuk menyelesaikan pembuatan bucket Anda.

Command line

  1. In the Trusted Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Trusted Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Di lingkungan pengembangan Anda, jalankan perintah gcloud storage buckets create:

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

    Dengan:

    • BUCKET_NAME adalah nama yang ingin Anda berikan pada bucket, sesuai dengan persyaratan penamaan. Contoh, my-bucket.
    • BUCKET_LOCATION adalah lokasi bucket Anda. Misalnya, us-east1.
    • --uniform-bucket-level-access: Mengaktifkan akses level bucket yang seragam untuk bucket.
    • --enable-hierarchical-namespace: Aktifkan namespace hierarkis untuk bucket. Anda tidak dapat mengaktifkan namespace hierarkis di bucket yang sudah ada.

    Jika permintaan berhasil, perintah akan menampilkan pesan berikut ini:

    Creating gs://BUCKET_NAME/...

    Tetapkan flag berikut untuk memiliki kontrol yang lebih besar atas pembuatan bucket Anda:

    • --project: Tentukan project ID atau nomor project yang akan dikaitkan dengan bucket Anda. Contoh, my-project.
    • --default-storage-class: Menentukan kelas penyimpanan default bucket Anda. Misalnya, STANDARD.
    • Untuk mengetahui daftar lengkap opsi pembuatan bucket menggunakan Google Cloud CLI, lihat opsi buckets create.

    Contoh:

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

    C++

    Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C++ API.

    Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

    Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

    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";
    }

    C#

    Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C# API.

    Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

    Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

    using Google.Apis.Storage.v1.Data;
    using Google.Cloud.Storage.V1;
    using System;
    
    public class CreateBucketWithHierarchicalNamespaceEnabledSample
    {
        public Bucket CreateBucketWithHierarchicalNamespace(
            string projectId = "your-project-id",
            string bucketName = "your-unique-bucket-name")
        {
            var storage = StorageClient.Create();
            var bucket = storage.CreateBucket(projectId,
                new Bucket
                {
                    Name = bucketName,
                    IamConfiguration = new Bucket.IamConfigurationData
                    {
                        UniformBucketLevelAccess = new Bucket.IamConfigurationData.UniformBucketLevelAccessData { Enabled = true }
                    },
                    HierarchicalNamespace = new Bucket.HierarchicalNamespaceData { Enabled = true }
                });
            Console.WriteLine($"Created {bucketName} with Hierarchical Namespace enabled.");
            return bucket;
        }
    }

    Go

    Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Go API.

    Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

    Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

    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

    Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Java API.

    Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

    Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

    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

    Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Node.js API.

    Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

    Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

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

    Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage PHP API.

    Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

    Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

    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

    Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Python API.

    Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

    Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

    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

    Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Ruby API.

    Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

    Sebelum menjalankan contoh kode, tetapkan variabel lingkungan GOOGLE_CLOUD_UNIVERSE_DOMAIN ke s3nsapis.fr.

    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. Menginstal dan melakukan inisialisasi gcloud CLI, yang memungkinkan Anda membuat token akses untuk header Authorization.

    2. Buat file JSON yang berisi setelan untuk bucket, yang harus menyertakan name untuk bucket. Lihat dokumentasi Buckets: Insert untuk daftar lengkap setelan. Berikut adalah setelan umum yang dapat disertakan:
    3. {
        "name": "BUCKET_NAME",
        "location": "BUCKET_LOCATION",
        "storageClass": "STORAGE_CLASS",
        "hierarchicalNamespace": {
          "enabled": "BOOLEAN"
        },
        "iamConfiguration": {
          "uniformBucketLevelAccess": {
            "enabled": true
        },
      },
      }

      Dengan keterangan:

      • BUCKET_NAME adalah nama yang ingin Anda berikan pada bucket, sesuai dengan persyaratan penamaan. Misalnya, my-bucket.
      • BUCKET_LOCATION adalah lokasi tempat Anda ingin menyimpan data objek bucket. Misalnya, US-EAST1.
      • STORAGE_CLASS adalah kelas penyimpanan default untuk bucket Anda. Misalnya, STANDARD.
      • hierarchicalNamespace.enabled ditetapkan ke TRUE untuk mengaktifkan namespace hierarkis untuk bucket Anda. Anda tidak dapat mengaktifkan namespace hierarkis di bucket yang sudah ada.
    4. uniformBucketLevelAccess.enabled disetel ke TRUE untuk mengaktifkan akses level bucket yang seragam untuk bucket Anda.
    5. Gunakan cURL untuk memanggil 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.s3nsapis.fr/storage/v1/b?project=PROJECT_IDENTIFIER"

      Dengan:

      • JSON_FILE_NAME adalah nama file JSON yang berisi setelan bucket.
      • PROJECT_IDENTIFIER adalah ID atau nomor project yang akan dikaitkan dengan bucket Anda. Contoh, my-project.

Langkah berikutnya