Menetapkan kunci KMS default untuk bucket

Menetapkan CMEK default untuk bucket.

Jelajahi lebih lanjut

Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat artikel berikut:

Contoh kode

C++

Untuk informasi selengkapnya, lihat Dokumentasi referensi Cloud Storage C++ API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

  if (!updated->has_encryption()) {
    std::cerr << "The change to set the encryption attribute on bucket "
              << updated->name()
              << " was successful, but the encryption is not set."
              << "This is unexpected, maybe a concurrent change?\n";
    return;
  }

  std::cout << "Successfully set default KMS key on bucket "
            << updated->name() << " to "
            << updated->encryption().default_kms_key_name << "."
            << "\nFull metadata: " << *updated << "\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, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

public class EnableDefaultKMSKeySample
{
    public Bucket EnableDefaultKMSKey(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name",
        string keyLocation = "us-west1",
        string kmsKeyRing = "kms-key-ring",
        string kmsKeyName = "key-name")
    {
        // KMS Key identifier of an already created KMS key.
        // If you use the Google.Cloud.Kms.V1 library, you can construct these names using helper class CryptoKeyName.
        // var fullKeyName = new CryptoKeyName(projectId, keyLocation, kmsKeyRing, kmsKeyName).ToString();
        string keyPrefix = $"projects/{projectId}/locations/{keyLocation}";
        string fullKeyringName = $"{keyPrefix}/keyRings/{kmsKeyRing}";
        string fullKeyName = $"{fullKeyringName}/cryptoKeys/{kmsKeyName}";
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });
        bucket.Encryption = new Bucket.EncryptionData { DefaultKmsKeyName = fullKeyName };
        var updatedBucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Default KMS key for {bucketName} was set to {kmsKeyName}.");
        return updatedBucket;
    }
}

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, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

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

// setBucketDefaultKMSKey sets the Cloud KMS encryption key for the bucket.
func setBucketDefaultKMSKey(w io.Writer, bucketName, keyName string) error {
	// bucketName := "bucket-name"
	// keyName := "key"
	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{
		Encryption: &storage.BucketEncryption{DefaultKMSKeyName: keyName},
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Default KMS Key Name: %v", bucketAttrsToUpdate.Encryption.DefaultKMSKeyName)
	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, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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;

public class SetBucketDefaultKmsKey {
  public static void setBucketDefaultKmsKey(String projectId, String bucketName, String kmsKeyName)
      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 name of the KMS key to use as a default
    // String kmsKeyName =
    // "projects/your-project-id/locations/us/keyRings/my_key_ring/cryptoKeys/my_key"

    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 updated =
        storage.update(
            bucket.toBuilder().setDefaultKmsKeyName(kmsKeyName).build(),
            BucketTargetOption.metagenerationMatch());

    System.out.println(
        "KMS Key "
            + updated.getDefaultKmsKeyName()
            + "was set to default for bucket "
            + bucketName);
  }
}

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, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

// The name of the KMS-key to use as a default
// const defaultKmsKeyName = 'my-key';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

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

async function enableDefaultKMSKey() {
  await storage.bucket(bucketName).setMetadata({
    encryption: {
      defaultKmsKeyName,
    },
  });

  console.log(
    `Default KMS key for ${bucketName} was set to ${defaultKmsKeyName}.`
  );
}

enableDefaultKMSKey().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, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

use Google\Cloud\Storage\StorageClient;

/**
 * Enable a bucket's requesterpays metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $kmsKeyName The KMS key to use as the default KMS key.
 *     Key names are provided in the following format:
 *     `projects/<PROJECT>/locations/<LOCATION>/keyRings/<RING_NAME>/cryptoKeys/<KEY_NAME>`.
 */
function enable_default_kms_key(string $bucketName, string $kmsKeyName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'encryption' => [
            'defaultKmsKeyName' => $kmsKeyName
        ]
    ]);
    printf('Default KMS key for %s was set to %s' . PHP_EOL,
        $bucketName,
        $bucket->info()['encryption']['defaultKmsKeyName']);
}

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, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from google.cloud import storage

def enable_default_kms_key(bucket_name, kms_key_name):
    """Sets a bucket's default KMS key."""
    # bucket_name = "your-bucket-name"
    # kms_key_name = "projects/PROJ/locations/LOC/keyRings/RING/cryptoKey/KEY"

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    bucket.default_kms_key_name = kms_key_name
    bucket.patch()

    print(
        "Set default KMS key for bucket {} to {}.".format(
            bucket.name, bucket.default_kms_key_name
        )
    )

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, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

def set_bucket_default_kms_key bucket_name:, default_kms_key:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The name of the KMS key to manage this object with
  # default_kms_key = "projects/your-project-id/locations/global/keyRings/your-key-ring/cryptoKeys/your-key"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.default_kms_key = default_kms_key

  puts "Default KMS key for #{bucket.name} was set to #{bucket.default_kms_key}"
end

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.