Using retention policies and Bucket Lock

This page describes how to use the Bucket Lock feature, including working with retention policies and locking buckets. For details about this feature, see Retention Policies and Bucket Lock.

Prerequisites

Before using this feature in Cloud Storage, you should:

  1. Have sufficient permission to view and update buckets in Cloud Storage:

    • If you own the project that contains the bucket, you most likely have the necessary permissions.

    • If you use IAM, you should have storage.buckets.update and storage.buckets.get permissions on the relevant bucket. See Using IAM Permissions for instructions on how to get a role, such as roles/storage.admin, that has these permissions.

    • If you use ACLs, you should have OWNER permission on the relevant bucket. See Setting ACLs for instructions on how to do this.

  2. Check that Object Versioning is disabled for the bucket.

Setting a retention policy on a bucket

To set a retention policy on a bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that you want to add a retention policy for.

  3. Select the Bucket Lock tab near the top of the page.

  4. In the Retention policy entry, click the Add policy link.

    The Set a retention policy dialog box appears.

  5. In the drop down, select the unit of time for your retention period.

    See Retention periods for information about how the Console converts between different units of time.

  6. In the value box, enter the length of time for your retention period.

  7. Click Save policy.

gsutil

Use the gsutil retention set command:

gsutil retention set [TIME_DURATION] gs://[BUCKET_NAME]

Where:

  • [TIME_DURATION] is the amount of time objects in the bucket must be retained. For example, 2678400s. See Retention periods for information about how gsutil converts between different units of time.
  • [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.

If successful, the response looks like:

Setting retention policy on gs://[BUCKET_NAME]/...

Code samples

C++

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 bucket_name, std::chrono::seconds period) {
  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().SetRetentionPolicy(period),
      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() << "\n";
}

C#

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

        private void SetBucketRetentionPolicy(string bucketName,
            long retentionPeriod)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            bucket.RetentionPolicy = new Bucket.RetentionPolicyData();
            bucket.RetentionPolicy.RetentionPeriod = retentionPeriod;
            bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
            {
                IfMetagenerationMatch = bucket.Metageneration
            });

            Console.WriteLine($"Retention policy for {bucketName} was set to {retentionPeriod}");
        }

Go

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

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	RetentionPolicy: &storage.RetentionPolicy{
		RetentionPeriod: retentionPeriod,
	},
}
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Java

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

// The retention period for objects in bucket
// Long retentionPeriod = 3600L; // 1 hour in seconds

Bucket bucketWithRetentionPolicy =
    storage.update(
        BucketInfo.newBuilder(bucketName).setRetentionPeriod(retentionPeriod).build());

System.out.println(
    "Retention period for "
        + bucketName
        + " is now "
        + bucketWithRetentionPolicy.getRetentionPeriod());

Node.js

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

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

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

const [metadata] = await storage
  .bucket(bucketName)
  .setRetentionPeriod(retentionPeriod);
console.log(
  `Bucket ${bucketName} retention period set for ${metadata.retentionPolicy.retentionPeriod} seconds.`
);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Sets a bucket's retention policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $retentionPeriod the number of seconds for your retention period.
 */
function set_retention_policy($bucketName, $retentionPeriod)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'retentionPolicy' => [
            'retentionPeriod' => $retentionPeriod
        ]]);
    printf('Bucket %s retention period set for %s seconds' . PHP_EOL, $bucketName,
        $retentionPeriod);
}

Python

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

# bucket_name = "my-bucket"
# retention_period = 10

storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)

bucket.retention_period = retention_period
bucket.patch()

print('Bucket {} retention period set for {} seconds'.format(
    bucket.name,
    bucket.retention_period))

Ruby

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

# project_id       = "Your Google Cloud project ID"
# bucket_name      = "Name of your Google Cloud Storage bucket"
# retention_period = "Object retention period defined in seconds"

require "google/cloud/storage"

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

bucket.retention_period = retention_period

puts "Retention period for #{bucket_name} is now #{bucket.retention_period} seconds."

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the following information:

    {
      "retentionPolicy": {
        "retentionPeriod": "[TIME_IN_SECONDS]"
      }
    }

    Where [TIME_IN_SECONDS] is the amount of time in seconds that objects in the bucket must be retained. For example, 2678400. See Retention periods for information about how different units of time are measured using seconds.

  3. Use cURL to call the JSON API with a PATCH Bucket request:

    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=retentionPolicy"

    Where:

    • [JSON_FILE_NAME] is the name of the file you created in Step 2.
    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.

XML API

The XML API cannot be used to set a retention policy on an existing bucket. It can only be used to include a retention policy with a new bucket.

Removing a retention policy from a bucket

To remove a retention policy from a bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that you want to remove the retention policy from.

  3. Select the Bucket Lock tab near the top of the page.

  4. In the Retention policy entry, click the Trash can icon.

    The Delete retention policy? dialog box appears.

  5. Click Delete.

gsutil

Use the gsutil retention clear command:

gsutil retention clear gs://[BUCKET_NAME]

Where [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.

If successful, the response looks like:

Clearing retention policy on gs://[BUCKET_NAME]/...

Code samples

C++

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

C#

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

        private void RemoveBucketRetentionPolicy(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);
            if (bucket.RetentionPolicy != null)
            {
                bool? isLockedOrNull = bucket?.RetentionPolicy.IsLocked;
                bool isLocked =
                    isLockedOrNull.HasValue ? isLockedOrNull.Value : false;
                if (isLocked)
                {
                    throw new Exception("Retention Policy is locked.");
                }

                bucket.RetentionPolicy.RetentionPeriod = null;
                bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
                {
                    IfMetagenerationMatch = bucket.Metageneration
                });

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

Go

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

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{},
}
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Java

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 =
    bucket.toBuilder().setRetentionPeriod(null).build().update();

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

Node.js

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

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

// Creates a client
const storage = new Storage();
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;
}

PHP

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)
{
    $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

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

# 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

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project_id: project_id
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

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the following information:

    {
      "retentionPolicy": {
        "retentionPeriod": null
      }
    }
  3. Use cURL to call the JSON API with a PATCH Bucket request:

    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    -H "Content-Type: application/json" \
    "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=retentionPolicy"

    Where:

    • [JSON_FILE_NAME] is the name of the file you created in Step 2.
    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.

XML API

The XML API cannot be used to remove a retention policy from a bucket. Use one of the other Cloud Storage tools, such as gsutil, instead.

Locking a bucket

To lock a bucket and permanently restrict edits to the bucket's retention policy:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that you want to lock the retention policy for.

  3. Select the Bucket Lock tab near the top of the page.

  4. In the Locked entry, click the Lock icon.

    The Lock retention policy for this bucket? dialog box appears.

  5. Read the Permanent notice.

  6. In the Bucket name text box, type in the name of your bucket.

  7. Click Lock policy.

gsutil

  1. Use the gsutil retention lock command:

    gsutil retention lock gs://[BUCKET_NAME]

    Where [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.

  2. When prompted to continue, type y.

If successful, the response looks like:

Locking retention policy on gs://[BUCKET_NAME]/...

Code samples

C++

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 bucket_name) {
  StatusOr<gcs::BucketMetadata> original =
      client.GetBucketMetadata(bucket_name);

  if (!original) {
    throw std::runtime_error(original.status().message());
  }

  StatusOr<gcs::BucketMetadata> updated_metadata =
      client.LockBucketRetentionPolicy(bucket_name,
                                       original->metageneration());

  if (!updated_metadata) {
    throw std::runtime_error(updated_metadata.status().message());
  }

  if (!updated_metadata->has_retention_policy()) {
    std::cerr << "The bucket " << updated_metadata->name()
              << " does not have a retention policy, even though the"
              << " operation to set it was successful.\n"
              << "This is unexpected, and may indicate that another"
              << " application has modified the bucket concurrently.\n";
    return;
  }

  std::cout << "Retention policy successfully locked for bucket "
            << updated_metadata->name() << "\nNew retention policy is: "
            << updated_metadata->retention_policy()
            << "\nFull metadata: " << *updated_metadata << "\n";
}

C#

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

private void LockBucketRetentionPolicy(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName);
    storage.LockBucketRetentionPolicy(bucketName,
        bucket.Metageneration.Value);
    bucket = storage.GetBucket(bucketName);
    Console.WriteLine($"Retention policy for {bucketName} is now locked");
    Console.WriteLine($"Retention policy effective as of {bucket.RetentionPolicy.EffectiveTime}");
}

Go

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

bucket := c.Bucket(bucketName)
attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}

conditions := storage.BucketConditions{
	MetagenerationMatch: attrs.MetaGeneration,
}
if err := bucket.If(conditions).LockRetentionPolicy(ctx); err != nil {
	return err
}

lockedAttrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}
log.Printf("Retention policy for %v is now locked\n", bucketName)
log.Printf("Retention policy effective as of %v\n",
	lockedAttrs.RetentionPolicy.EffectiveTime)

Java

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, Storage.BucketGetOption.fields(BucketField.METAGENERATION));
Bucket lockedBucket =
    bucket.lockRetentionPolicy(Storage.BucketTargetOption.metagenerationMatch());

System.out.println("Retention period for " + bucketName + " is now locked");
System.out.println(
    "Retention policy effective as of " + new Date(lockedBucket.getRetentionEffectiveTime()));

Node.js

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

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

// Creates a client
const storage = new Storage();
// get_bucket gets the current metageneration value for the bucket,
// required by lock_retention_policy.
const [unlockedMetadata] = await storage.bucket(bucketName).getMetadata();
// Warning: Once a retention policy is locked it cannot be unlocked
// and retention period can only be increased.
const [lockedMetadata] = await storage
  .bucket(bucketName)
  .lock(unlockedMetadata.metageneration);
console.log(`Retention policy for ${bucketName} is now locked.`);
console.log(
  `Retention policy effective as of ${lockedMetadata.retentionPolicy.effectiveTime}`
);

return lockedMetadata;

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Locks a bucket's retention policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function lock_retention_policy($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();
    $bucket->lockRetentionPolicy();
    printf('Bucket %s retention policy locked' . PHP_EOL, $bucketName);
}

Python

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

# bucket_name = "my-bucket"

storage_client = storage.Client()
# get_bucket gets the current metageneration value for the bucket,
# required by lock_retention_policy.
bucket = storage_client.get_bucket(bucket_name)

# Warning: Once a retention policy is locked it cannot be unlocked
# and retention period can only be increased.
bucket.lock_retention_policy()

print('Retention policy for {} is now locked'.format(bucket_name))
print('Retention policy effective as of {}'.format(
    bucket.retention_policy_effective_time))

Ruby

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

# Warning: Once a retention policy is locked it cannot be unlocked
# and retention period can only be increased.
# Uses Bucket#metageneration as a precondition.
bucket.lock_retention_policy!

puts "Retention policy for #{bucket_name} is now locked."
puts "Retention policy effective as of #{bucket.retention_effective_at}."

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a POST Bucket request:

    curl -X POST \
    -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/lockRetentionPolicy?ifMetagenerationMatch=[BUCKET_METAGENERATION_NUMBER]"

    Where:

    • [OAUTH2_TOKEN] is the name of the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.
    • [BUCKET_METAGENERATION_NUMBER] is the metageneration value for the bucket. For example, 8. You can find the metageneration value for your bucket by calling the JSON API with a GET Bucket request.

XML API

The XML API cannot be used to lock a bucket. Use one of the other Cloud Storage tools, such as gsutil, instead.

Viewing a bucket's retention policy and lock status

To view what, if any, retention policy is set on a bucket and whether that retention policy is locked:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the Columns drop-down menu make sure Retention policy is checked.

  3. In the list of buckets, the retention period of each bucket is found in the Retention policy column. If the retention policy is locked, an image of a lock appears directly to the left of the retention period.

gsutil

Use the gsutil retention get command:

gsutil retention get gs://[BUCKET_NAME]

Where [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.

If successful, the response looks like:

gs://[BUCKET_NAME]/ has no retention policy.

or:

gs://retention-test/:
    Retention policy [LOCK_STATUS]:
    Duration: [TIME_LENGTH]
    Effective Time: [SET_DATE]

Code samples

C++

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 bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name);

  if (!bucket_metadata) {
    throw std::runtime_error(bucket_metadata.status().message());
  }

  if (!bucket_metadata->has_retention_policy()) {
    std::cout << "The bucket " << bucket_metadata->name()
              << " does not have a retention policy set.\n";
    return;
  }

  std::cout << "The bucket " << bucket_metadata->name()
            << " retention policy is set to "
            << bucket_metadata->retention_policy() << "\n";
}

C#

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

        private void GetBucketRetentionPolicy(string bucketName)
        {
            var storage = StorageClient.Create();
            var bucket = storage.GetBucket(bucketName);

            if (bucket.RetentionPolicy != null)
            {
                Console.WriteLine("Retention policy:");
                Console.WriteLine($"period: {bucket.RetentionPolicy.RetentionPeriod}");
                Console.WriteLine($"effective time: {bucket.RetentionPolicy.EffectiveTime}");
                bool? isLockedOrNull = bucket?.RetentionPolicy.IsLocked;
                bool isLocked =
                    isLockedOrNull.HasValue ? isLockedOrNull.Value : false;
                Console.WriteLine("policy locked: {0}", isLocked);
            }
        }

Go

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

attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return nil, err
}
if attrs.RetentionPolicy != nil {
	log.Print("Retention Policy\n")
	log.Printf("period: %v\n", attrs.RetentionPolicy.RetentionPeriod)
	log.Printf("effective time: %v\n", attrs.RetentionPolicy.EffectiveTime)
	log.Printf("policy locked: %v\n", attrs.RetentionPolicy.IsLocked)
}

Java

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

System.out.println("Retention Policy for " + bucketName);
System.out.println("Retention Period: " + bucket.getRetentionPeriod());
if (bucket.retentionPolicyIsLocked() != null && bucket.retentionPolicyIsLocked()) {
  System.out.println("Retention Policy is locked");
}
if (bucket.getRetentionEffectiveTime() != null) {
  System.out.println("Effective Time: " + new Date(bucket.getRetentionEffectiveTime()));
}

Node.js

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

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

// Creates a client
const storage = new Storage();
const [metadata] = await storage.bucket(bucketName).getMetadata();
if (metadata.retentionPolicy) {
  const retentionPolicy = metadata.retentionPolicy;
  console.log('A retention policy exists!');
  console.log(`Period: ${retentionPolicy.retentionPeriod}`);
  console.log(`Effective time: ${retentionPolicy.effectiveTime}`);
  if (retentionPolicy.isLocked) {
    console.log('Policy is locked');
  } else {
    console.log('Policy is unlocked');
  }
}

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Gets a bucket's retention policy.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function get_retention_policy($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();

    printf('Retention Policy for ' . $bucketName . PHP_EOL);
    printf('Retention Period: ' . $bucket->info()['retentionPolicy']['retentionPeriod'] . PHP_EOL);
    if (array_key_exists('isLocked', $bucket->info()['retentionPolicy']) &&
        $bucket->info()['retentionPolicy']['isLocked']) {
        printf('Retention Policy is locked' . PHP_EOL);
    }
    if ($bucket->info()['retentionPolicy']['effectiveTime']) {
        printf('Effective Time: ' . $bucket->info()['retentionPolicy']['effectiveTime'] . PHP_EOL);
    }
}

Python

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

# bucket_name = "my-bucket"

storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
bucket.reload()

print('Retention Policy for {}'.format(bucket_name))
print('Retention Period: {}'.format(bucket.retention_period))
if bucket.retention_policy_locked:
    print('Retention Policy is locked')

if bucket.retention_policy_effective_time:
    print('Effective Time: {}'
          .format(bucket.retention_policy_effective_time))

Ruby

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

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

puts "Retention policy:"
puts "period: #{bucket.retention_period}"
puts "effective time: #{bucket.retention_effective_at}"
puts "policy locked: #{bucket.retention_policy_locked?}"

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a GET Bucket request that includes the desired fields:

    curl -X GET -H "Authorization: Bearer [OAUTH2_TOKEN]" \
    "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=retentionPolicy"

    Where:

    • [OAUTH2_TOKEN] is the name of the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.

    If the bucket has a retention policy set on it, the response looks like the following example:

    {
      "retentionPolicy": {
          "retentionPeriod": "[TIME_IN_SECONDS]",
          "effectiveTime": "[DATETIME]",
          "isLocked": "[BOOLEAN]"
       },
    }

XML API

The XML API cannot be used to view the retention policy on a bucket. Use one of the other Cloud Storage tools, such as gsutil, instead.

What's next

Bu sayfayı yararlı buldunuz mu? Lütfen görüşünüzü bildirin:

Şunun hakkında geri bildirim gönderin...

Yardım mı gerekiyor? Destek sayfamızı ziyaret edin.