设置存储分区的默认 CMEK。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
C#
如需了解详情,请参阅 Cloud Storage C# API 参考文档。
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;
}
}
C++
如需了解详情,请参阅 Cloud Storage C++ API 参考文档。
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::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";
return;
}
std::cout << "Successfully set default KMS key on bucket "
<< updated->name() << " to "
<< updated->encryption().default_kms_key_name << "."
<< "\nFull metadata: " << *updated << "\n";
}
Go
如需了解详情,请参阅 Cloud Storage Go API 参考文档。
ctx := context.Background()
bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
Encryption: &storage.BucketEncryption{DefaultKMSKeyName: keyName},
}
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 参考文档。
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
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();
BucketInfo bucketInfo =
BucketInfo.newBuilder(bucketName).setDefaultKmsKeyName(kmsKeyName).build();
Bucket bucket = storage.update(bucketInfo);
System.out.println(
"KMS Key " + bucket.getDefaultKmsKeyName() + "was set to default for bucket " + bucketName);
}
}
Node.js
如需了解详情,请参阅 Cloud Storage Node.js API 参考文档。
/**
* 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
如需了解详情,请参阅 Cloud Storage PHP API 参考文档。
use Google\Cloud\Storage\StorageClient;
/**
* Enable a bucket's requesterpays metadata.
*
* @param string $bucketName The name of your Cloud Storage 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($bucketName, $kmsKeyName)
{
// $bucketName = 'my-bucket';
// $kmsKeyName = "";
$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
如需了解详情,请参阅 Cloud Storage Python API 参考文档。
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
如需了解详情,请参阅 Cloud Storage Ruby API 参考文档。
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
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。