介绍了如何移除存储分区的保留政策的示例。必须解锁存储分区保留政策才能成功移除政策。
包含此代码示例的文档页面
如需查看上下文中使用的代码示例,请参阅以下文档:
代码示例
C#
如需了解详情,请参阅 Cloud Storage C# API 参考文档。
using Google.Cloud.Storage.V1;
using System;
public class RemoveRetentionPolicySample
{
public void RemoveRetentionPolicy(string bucketName = "your-unique-bucket-name")
{
var storage = StorageClient.Create();
var bucket = storage.GetBucket(bucketName);
if (bucket.RetentionPolicy != null)
{
bool isLocked = bucket.RetentionPolicy.IsLocked ?? false;
if (isLocked)
{
throw new Exception("Retention Policy is locked.");
}
bucket.RetentionPolicy.RetentionPeriod = null;
storage.UpdateBucket(bucket);
Console.WriteLine($"Retention period for {bucketName} has been removed.");
}
}
}
C++
如需了解详情,请参阅 Cloud Storage C++ API 参考文档。
namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
StatusOr<gcs::BucketMetadata> original =
client.GetBucketMetadata(bucket_name);
if (!original) throw std::runtime_error(original.status().message());
StatusOr<gcs::BucketMetadata> patched_metadata = client.PatchBucket(
bucket_name, gcs::BucketMetadataPatchBuilder().ResetRetentionPolicy(),
gcs::IfMetagenerationMatch(original->metageneration()));
if (!patched_metadata) {
throw std::runtime_error(patched_metadata.status().message());
}
if (!patched_metadata->has_retention_policy()) {
std::cout << "The bucket " << patched_metadata->name()
<< " does not have a retention policy set.\n";
return;
}
std::cout << "The bucket " << patched_metadata->name()
<< " retention policy is set to "
<< patched_metadata->retention_policy()
<< ". This is unexpected, maybe a concurrent change by another"
<< " application?\n";
}
Go
如需了解详情,请参阅 Cloud Storage Go API 参考文档。
ctx := context.Background()
bucket := c.Bucket(bucketName)
attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
return err
}
if attrs.RetentionPolicy.IsLocked {
return errors.New("retention policy is locked")
}
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
RetentionPolicy: &storage.RetentionPolicy{},
}
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 参考文档。
// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();
// The name of a bucket, e.g. "my-bucket"
// String bucketName = "my-bucket";
Bucket bucket = storage.get(bucketName, BucketGetOption.fields(BucketField.RETENTION_POLICY));
if (bucket.retentionPolicyIsLocked() != null && bucket.retentionPolicyIsLocked()) {
throw new IllegalArgumentException(
"Unable to remove retention period as retention policy is locked.");
}
Bucket bucketWithoutRetentionPolicy =
bucket.toBuilder().setRetentionPeriod(null).build().update();
System.out.println("Retention period for " + bucketName + " has been removed");
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';
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');
// Creates a client
const storage = new Storage();
async function removeRetentionPolicy() {
const [metadata] = await storage.bucket(bucketName).getMetadata();
if (metadata.retentionPolicy && metadata.retentionPolicy.isLocked) {
console.log(
'Unable to remove retention period as retention policy is locked.'
);
return null;
} else {
const results = await storage.bucket(bucketName).removeRetentionPeriod();
console.log(`Removed bucket ${bucketName} retention policy.`);
return results;
}
}
removeRetentionPolicy().catch(console.error);
PHP
如需了解详情,请参阅 Cloud Storage PHP API 参考文档。
use Google\Cloud\Storage\StorageClient;
/**
* Removes a bucket's retention policy.
*
* @param string $bucketName the name of your Cloud Storage bucket.
*/
function remove_retention_policy($bucketName)
{
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$bucket->reload();
if (array_key_exists('isLocked', $bucket->info()['retentionPolicy']) &&
$bucket->info()['retentionPolicy']['isLocked']) {
printf('Unable to remove retention period as retention policy is locked.' . PHP_EOL);
return;
}
$bucket->update([
'retentionPolicy' => []
]);
printf('Removed bucket %s retention policy' . PHP_EOL, $bucketName);
}
Python
如需了解详情,请参阅 Cloud Storage Python API 参考文档。
from google.cloud import storage
def remove_retention_policy(bucket_name):
"""Removes the retention policy on a given bucket"""
# bucket_name = "my-bucket"
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
bucket.reload()
if bucket.retention_policy_locked:
print(
"Unable to remove retention period as retention policy is locked."
)
return
bucket.retention_period = None
bucket.patch()
print("Removed bucket {} retention policy".format(bucket.name))
Ruby
如需了解详情,请参阅 Cloud Storage Ruby API 参考文档。
def remove_retention_policy bucket_name:
# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
require "google/cloud/storage"
storage = Google::Cloud::Storage.new
bucket = storage.bucket bucket_name
if !bucket.retention_policy_locked?
bucket.retention_period = nil
puts "Retention policy for #{bucket_name} has been removed."
else
puts "Policy is locked and retention policy can't be removed."
end
end
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器