Remove retention policy

Shows an example of how to remove a retention policy on a bucket. The bucket retention policy must be unlocked to successfully remove a policy.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample


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

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;

            Console.WriteLine($"Retention period for {bucketName} has been removed.");


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) {
  StatusOr<gcs::BucketMetadata> original =

  if (!original) throw std::runtime_error(original.status().message());
  StatusOr<gcs::BucketMetadata> patched_metadata = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().ResetRetentionPolicy(),

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

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


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

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


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

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

System.out.println("Retention period for " + bucketName + " has been removed");


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

// 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) {
      '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;



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

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)
    // $bucketName = 'my-bucket';

    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

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

        'retentionPolicy' => []
    printf('Removed bucket %s retention policy' . PHP_EOL, $bucketName);


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

from 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)

    if bucket.retention_policy_locked:
            "Unable to remove retention period as retention policy is locked."

    bucket.retention_period = None

    print("Removed bucket {} retention policy".format(


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

def remove_retention_policy bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage =
  bucket  = storage.bucket bucket_name

  if !bucket.retention_policy_locked?
    bucket.retention_period = nil
    puts "Retention policy for #{bucket_name} has been removed."
    puts "Policy is locked and retention policy can't be removed."

What's next

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