Set a default KMS key for a bucket

Stay organized with collections Save and categorize content based on your preferences.

Sets a default CMEK for a bucket.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample


For more information, see the Cloud Storage C# API reference documentation.

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;


For more information, see the Cloud Storage C++ API reference documentation.

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(
  if (!updated) throw std::runtime_error(updated.status().message());

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

  std::cout << "Successfully set default KMS key on bucket "
            << updated->name() << " to "
            << updated->encryption().default_kms_key_name << "."
            << "\nFull metadata: " << *updated << "\n";


For more information, see the Cloud Storage Go API reference documentation.

import (


// 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: %v", 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: %v", bucketName, err)
	fmt.Fprintf(w, "Default KMS Key Name: %v", bucketAttrsToUpdate.Encryption.DefaultKMSKeyName)
	return nil


For more information, see the Cloud Storage Java API reference documentation.


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();

    BucketInfo bucketInfo =
    Bucket bucket = storage.update(bucketInfo);

        "KMS Key " + bucket.getDefaultKmsKeyName() + "was set to default for bucket " + bucketName);


For more information, see the Cloud Storage Node.js API reference documentation.

 * 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: {

    `Default KMS key for ${bucketName} was set to ${defaultKmsKeyName}.`



For more information, see the Cloud Storage PHP API reference documentation.

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);
        'encryption' => [
            'defaultKmsKeyName' => $kmsKeyName
    printf('Default KMS key for %s was set to %s' . PHP_EOL,


For more information, see the Cloud Storage Python API reference documentation.

from 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

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


For more information, see the Cloud Storage Ruby API reference documentation.

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 =
  bucket  = storage.bucket bucket_name

  bucket.default_kms_key = default_kms_key

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.