Using object holds

This page describes how to use object holds, including placing holds by default on new objects and placing holds on individual objects. For details about this feature, including the types of holds that can be placed on objects, see Object Holds.

Prerequisites

Before using this feature in Cloud Storage, you should:

  1. Have sufficient permission to view and update buckets and objects 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, storage.buckets.get, storage.objects.update, and storage.objects.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 and on the objects within it. See Setting ACLs for instructions on how to do this.

Working with the default event-based hold property

The following tasks show you how to enable, view, and disable the default event-based hold property on a bucket. When this property is enabled, new objects added to the bucket automatically get an event-based hold placed on them.

Enabling the default event-based hold property

To automatically place an event-based hold on each new object added to a bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that you want to enable the default event-based hold property for.

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

  4. In the Event-based holds by default entry, click the Disabled button.

gsutil

Use the gsutil retention event-default set command:

gsutil retention event-default set gs://[BUCKET_NAME]

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

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().SetDefaultEventBasedHold(true),
      gcs::IfMetagenerationMatch(original->metageneration()));

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

  std::cout << "The default event-based hold for objects in bucket "
            << bucket_name << " is "
            << (patched_metadata->default_event_based_hold() ? "enabled"
                                                             : "disabled")
            << "\n";
}

C#

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

private void EnableBucketDefaultEventBasedHold(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName);
    bucket.DefaultEventBasedHold = true;
    bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration
    });
    Console.WriteLine($"Default event-based hold was enabled for {bucketName}");
}

Go

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

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	DefaultEventBasedHold: true,
}
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.update(BucketInfo.newBuilder(bucketName).setDefaultEventBasedHold(true).build());

System.out.println("Default event-based hold was enabled for " + bucketName);

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Enables a default event-based hold for the bucket.
await storage.bucket(bucketName).setMetadata({
  defaultEventBasedHold: true,
});

console.log(`Default event-based hold was enabled for ${bucketName}.`);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Enables a default event-based hold for a bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function enable_default_event_based_hold($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update(['defaultEventBasedHold' => true]);
    printf('Default event-based hold was enabled for %s' . 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.default_event_based_hold = True
bucket.patch()

print('Default event based hold was enabled for {}'.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

bucket.update do |b|
  b.default_event_based_hold = true
end

puts "Default event-based hold was enabled for #{bucket_name}."

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:

    {
      "defaultEventBasedHold": true
    }
  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://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=defaultEventBasedHold"

    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 work with object holds. Use one of the other Cloud Storage tools, such as gsutil, instead.

Getting the default hold status of a bucket

To view whether a bucket places event-based holds on new objects by default:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that you want to check the default event-based status for.

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

  4. The status appears in the Event-based holds by default entry.

gsutil

Use the following gsutil ls command:

gsutil ls -L -b gs://[BUCKET_NAME]/

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

The response looks like the following example:

gs://[BUCKET_NAME]/ :
  Storage class:         STANDARD
  ...
  ...
  Default Event-Based Hold: On
  ...

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

  std::cout << "The default event-based hold for objects in bucket "
            << bucket_metadata->name() << " is "
            << (bucket_metadata->default_event_based_hold() ? "enabled"
                                                            : "disabled")
            << "\n";
}

C#

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

private bool GetBucketDefaultEventBasedHold(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName);
    bool? defaultEventBasedHoldOrNull = bucket?.DefaultEventBasedHold;
    bool defaultEventBasedHold =
        defaultEventBasedHoldOrNull.HasValue ? defaultEventBasedHoldOrNull.Value : false;
    Console.WriteLine("Default event-based hold: {0}", defaultEventBasedHold);
    return defaultEventBasedHold;
}

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
}
log.Printf("Default event-based hold enabled? %t\n",
	attrs.DefaultEventBasedHold)

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

if (bucket.getDefaultEventBasedHold() != null && bucket.getDefaultEventBasedHold()) {
  System.out.println("Default event-based hold is enabled for " + bucketName);
} else {
  System.out.println("Default event-based hold is not enabled for " + bucketName);
}

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// get bucketName metadata
const [metadata] = await storage.bucket(bucketName).getMetadata();
console.log(`Default event-based hold: ${metadata.defaultEventBasedHold}.`);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Enables a default event-based hold for a bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function get_default_event_based_hold($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    if ($bucket->info()['defaultEventBasedHold']) {
        printf('Default event-based hold is enabled for ' . $bucketName . PHP_EOL);
    } else {
        printf('Default event-based hold is not enabled for ' . $bucketName . 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()

if bucket.default_event_based_hold:
    print('Default event-based hold is enabled for {}'.format(bucket_name))
else:
    print('Default event-based hold is not enabled for {}'
          .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.default_event_based_hold?
  puts "Default event-based hold is enabled for {bucket_name}."
else
  puts "Default event-based hold is not enabled for {bucket_name}."
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. 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://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=defaultEventBasedHold"

    Where

    • [OAUTH2_TOKEN] is 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 default event-based hold enabled for it, the response looks like the following example:

    {
      "retentionPolicy": true
    }

XML API

The XML API cannot be used to work with object holds. Use one of the other Cloud Storage tools, such as gsutil, instead.

Disabling a default event-based hold

To disable a default event-based hold on a bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that you want to disable the default event-based hold for.

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

  4. In the Event-based holds by default entry, click the Enabled button.

gsutil

Use the gsutil retention event-default release command:

gsutil retention event-default release gs://[BUCKET_NAME]

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

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().SetDefaultEventBasedHold(false),
      gcs::IfMetagenerationMatch(original->metageneration()));

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

  std::cout << "The default event-based hold for objects in bucket "
            << bucket_name << " is "
            << (patched_metadata->default_event_based_hold() ? "enabled"
                                                             : "disabled")
            << "\n";
}

C#

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

private void DisableBucketDefaultEventBasedHold(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName);
    bucket.DefaultEventBasedHold = false;
    bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration
    });
    Console.WriteLine($"Default event-based hold was disabled for {bucketName}");
}

Go

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

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	DefaultEventBasedHold: false,
}
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.update(BucketInfo.newBuilder(bucketName).setDefaultEventBasedHold(false).build());

System.out.println("Default event-based hold was disabled for " + bucketName);

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Disables a default event-based hold for a bucket.
await storage.bucket(bucketName).setMetadata({
  defaultEventBasedHold: false,
});
console.log(`Default event-based hold was disabled for ${bucketName}.`);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Disables a default event-based hold for a bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 */
function disable_default_event_based_hold($bucketName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update(['defaultEventBasedHold' => false]);
    printf('Default event-based hold was disabled for %s' . 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.default_event_based_hold = False
bucket.patch()

print("Default event based hold was disabled for {}".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

bucket.update do |b|
  b.default_event_based_hold = false
end

puts "Default event-based hold was disabled for #{bucket_name}."

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:

    {
      "defaultEventBasedHold": false
    }
  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://www.googleapis.com/storage/v1/b/[BUCKET_NAME]?fields=defaultEventBasedHold"

    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 work with object holds. Use one of the other Cloud Storage tools, such as gsutil, instead.

Working with object holds

The following tasks show you how to place, view, and release holds on objects.

Placing an object hold

To place a hold on an object in your bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that has the objects you want to place holds on.

  3. Select the checkbox next to the names of objects you want to place holds on.

  4. Click the Manage holds button.

    The Manage holds window appears.

  5. Select the checkbox for the types of hold you want to place on the selected objects

  6. Click Save hold settings.

gsutil

Use the gsutil retention command:

gsutil retention [HOLD_TYPE] set gs://[BUCKET_NAME]/[OBJECT_NAME]

Where:

  • [HOLD_TYPE] is the type of hold you want to apply to your object. For example, temp orevent. See Object holds for more information about hold types.
  • [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.
  • [OBJECT_NAME] is the name of the relevant object. For example, pets/dog.png.

Code samples

C++

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

The following sample sets an event-based hold on an object:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string object_name) {
  StatusOr<gcs::ObjectMetadata> original =
      client.GetObjectMetadata(bucket_name, object_name);

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

  StatusOr<gcs::ObjectMetadata> updated = client.PatchObject(
      bucket_name, object_name,
      gcs::ObjectMetadataPatchBuilder().SetEventBasedHold(true),
      gcs::IfMetagenerationMatch(original->metageneration()));

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

  std::cout << "The event hold for object " << updated->name()
            << " in bucket " << updated->bucket() << " is "
            << (updated->event_based_hold() ? "enabled" : "disabled") << "\n";
}

The following sample sets a temporary hold on an object:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string object_name) {
  StatusOr<gcs::ObjectMetadata> original =
      client.GetObjectMetadata(bucket_name, object_name);

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

  StatusOr<gcs::ObjectMetadata> updated = client.PatchObject(
      bucket_name, object_name,
      gcs::ObjectMetadataPatchBuilder().SetTemporaryHold(true),
      gcs::IfMetagenerationMatch(original->metageneration()));

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

  std::cout << "The temporary hold for object " << updated->name()
            << " in bucket " << updated->bucket() << " is "
            << (updated->temporary_hold() ? "enabled" : "disabled") << "\n";
}

C#

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

The following sample sets an event-based hold on an object:

private void SetObjectEventBasedHold(string bucketName,
    string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    storageObject.EventBasedHold = true;
    storageObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration
    });
}

The following sample sets a temporary hold on an object:

private void SetObjectTemporaryHold(string bucketName,
    string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    storageObject.TemporaryHold = true;
    storageObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration,
    });
}

Go

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

The following sample sets an event-based hold on an object:

o := client.Bucket(bucket).Object(object)
objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
	EventBasedHold: true,
}
if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
	return err
}

The following sample sets a temporary hold on an object:

o := client.Bucket(bucket).Object(object)
objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
	TemporaryHold: true,
}
if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
	return err
}

Java

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

The following sample sets an event-based hold on an object:

// 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 name of a blob, e.g. "my-blob"
// String blobName = "my-blob";

BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage.update(BlobInfo.newBuilder(blobId).setEventBasedHold(true).build());

System.out.println("Event-based hold was set for " + blobName);

The following sample sets a temporary hold on an object:

// 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 name of a blob, e.g. "my-blob"
// String blobName = "my-blob";

BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage.update(BlobInfo.newBuilder(blobId).setTemporaryHold(true).build());

System.out.println("Temporary hold was set for " + blobName);

Node.js

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

The following sample sets an event-based hold on an object:

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

// Set event-based hold
await storage
  .bucket(bucketName)
  .file(fileName)
  .setMetadata({
    eventBasedHold: true,
  });
console.log(`Event-based hold was set for ${fileName}.`);

The following sample sets a temporary hold on an object:

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

await storage
  .bucket(bucketName)
  .file(fileName)
  .setMetadata({
    temporaryHold: true,
  });
console.log(`Temporary hold was set for ${fileName}.`);

PHP

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

The following sample sets an event-based hold on an object:

use Google\Cloud\Storage\StorageClient;

/**
 * Sets an event-based hold for an object.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 */
function set_event_based_hold($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['eventBasedHold' => true]);
    printf('Event-based hold was set for %s' . PHP_EOL, $objectName);
}

The following sample sets a temporary hold on an object:

use Google\Cloud\Storage\StorageClient;

/**
 * Sets a temporary hold for an object.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 */
function set_temporary_hold($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['temporaryHold' => true]);
    printf('Temporary hold was set for %s' . PHP_EOL, $objectName);
}

Python

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

The following sample sets an event-based hold on an object:

# bucket_name = "my-bucket"
# blob_name = "my-blob"

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

blob.event_based_hold = True
blob.patch()

print('Event based hold was set for {}'.format(blob_name))

The following sample sets a temporary hold on an object:

# bucket_name = "my-bucket"
# blob_name = "my-blob"

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

blob.temporary_hold = True
blob.patch()

print("Temporary hold was set for #{blob_name}")

Ruby

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

The following sample sets an event-based hold on an object:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file in the Cloud Storage bucket"

require "google/cloud/storage"

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

file.set_event_based_hold!

puts "Event-based hold was set for #{file_name}."

The following sample sets a temporary hold on an object:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file in the Cloud Storage bucket"

require "google/cloud/storage"

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

file.set_temporary_hold!

puts "Temporary hold was set for #{file_name}."

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:

    {
      "[HOLD_TYPE]": true
    }

    Where [HOLD_TYPE] is the type of hold you want to apply to your object. For example, temporaryHold or eventBasedHold. See Object holds for more information about hold types.

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

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

    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.
    • [OBJECT_NAME] is the name of the relevant object. For example, pets/dog.png.

XML API

The XML API cannot be used to work with object holds. Use one of the other Cloud Storage tools, such as gsutil, instead.

Getting the hold status for an object

To view what, if any, holds exist on an object, follow the general instructions for Viewing Object Metadata.

Releasing an object hold

To release a hold on an object in your bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that has the objects you remove holds from.

  3. Select the checkbox next to the names of objects you want to remove holds from.

  4. Click the Manage holds button.

    The Manage holds window appears.

  5. De-select the checkbox for the holds you want to remove.

  6. Click Save hold settings.

gsutil

Use the gsutil retention command:

gsutil retention [HOLD_TYPE] release gs://[BUCKET_NAME]/[OBJECT_NAME]

Where:

  • [HOLD_TYPE] is the type of hold you want to release from your object. For example, temp orevent. See Object holds for more information about hold types.
  • [BUCKET_NAME] is the name of the relevant bucket. For example, my-bucket.
  • [OBJECT_NAME] is the name of the relevant object. For example, pets/dog.png.

Code samples

C++

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

The following sample sets an event-based hold on an object:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string object_name) {
  StatusOr<gcs::ObjectMetadata> original =
      client.GetObjectMetadata(bucket_name, object_name);

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

  StatusOr<gcs::ObjectMetadata> updated = client.PatchObject(
      bucket_name, object_name,
      gcs::ObjectMetadataPatchBuilder().SetEventBasedHold(false),
      gcs::IfMetagenerationMatch(original->metageneration()));

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

  std::cout << "The event hold for object " << updated->name()
            << " in bucket " << updated->bucket() << " is "
            << (updated->event_based_hold() ? "enabled" : "disabled") << "\n";
}

The following sample sets a temporary hold on an object:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string object_name) {
  StatusOr<gcs::ObjectMetadata> original =
      client.GetObjectMetadata(bucket_name, object_name);

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

  StatusOr<gcs::ObjectMetadata> updated = client.PatchObject(
      bucket_name, object_name,
      gcs::ObjectMetadataPatchBuilder().SetTemporaryHold(false),
      gcs::IfMetagenerationMatch(original->metageneration()));

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

  std::cout << "The temporary hold for object " << updated->name()
            << " in bucket " << updated->bucket() << " is "
            << (updated->temporary_hold() ? "enabled" : "disabled") << "\n";
}

C#

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

The following sample releases an event-based hold on an object:

private void ReleaseObjectEventBasedHold(string bucketName,
    string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    storageObject.EventBasedHold = false;
    storageObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration,
    });
}

The following sample releases a temporary hold on an object:

private void ReleaseObjectTemporaryHold(string bucketName,
    string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    storageObject.TemporaryHold = false;
    storageObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = storageObject.Metageneration,
    });
}

Go

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

The following sample releases an event-based hold on an object:

o := client.Bucket(bucket).Object(object)
objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
	EventBasedHold: false,
}
if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
	return err
}

The following sample releases a temporary hold on an object:

o := client.Bucket(bucket).Object(object)
objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
	TemporaryHold: false,
}
if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
	return err
}

Java

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

The following sample releases an event-based hold on an object:

// 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 name of a blob, e.g. "my-blob"
// String blobName = "my-blob";

BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage.update(BlobInfo.newBuilder(blobId).setEventBasedHold(false).build());

System.out.println("Event-based hold was released for " + blobName);

The following sample releases a temporary hold on an object:

// 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 name of a blob, e.g. "my-blob"
// String blobName = "my-blob";

BlobId blobId = BlobId.of(bucketName, blobName);
Blob blob = storage.update(BlobInfo.newBuilder(blobId).setTemporaryHold(false).build());

System.out.println("Temporary hold was released for " + blobName);

Node.js

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

The following sample releases an event-based hold on an object:

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

await storage
  .bucket(bucketName)
  .file(fileName)
  .setMetadata({
    eventBasedHold: false,
  });
console.log(`Event-based hold was released for ${fileName}.`);

The following sample releases a temporary hold on an object:

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

await storage
  .bucket(bucketName)
  .file(fileName)
  .setMetadata({
    temporaryHold: false,
  });
console.log(`Temporary hold was released for ${fileName}.`);

PHP

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

The following sample releases an event-based hold on an object:

use Google\Cloud\Storage\StorageClient;

/**
 * Releases an event-based hold for an object.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 */
function release_event_based_hold($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['eventBasedHold' => false]);
    printf('Event-based hold was released for %s' . PHP_EOL, $objectName);
}

The following sample releases a temporary hold on an object:

use Google\Cloud\Storage\StorageClient;

/**
 * Releases a temporary hold for an object.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 */
function release_temporary_hold($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['temporaryHold' => false]);
    printf('Temporary hold was released for %s' . PHP_EOL, $objectName);
}

Python

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

The following sample releases an event-based hold on an object:

# bucket_name = "my-bucket"
# blob_name = "my-blob"

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

blob.event_based_hold = False
blob.patch()

print('Event based hold was released for {}'.format(blob_name))

The following sample releases a temporary hold on an object:

# bucket_name = "my-bucket"
# blob_name = "my-blob"

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

blob.temporary_hold = False
blob.patch()

print("Temporary hold was release for #{blob_name}")

Ruby

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

The following sample releases an event-based hold on an object:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file in the Cloud Storage bucket"

require "google/cloud/storage"

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

file.release_event_based_hold!

puts "Event-based hold was released for #{file_name}."

The following sample releases a temporary hold on an object:

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of a file in the Cloud Storage bucket"

require "google/cloud/storage"

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

file.release_temporary_hold!

puts "Temporary hold was released for #{file_name}."

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:

    {
      "[HOLD_TYPE]": false
    }

    Where [HOLD_TYPE] is the type of hold you want to release from your object. For example, temporaryHold oreventBasedHold. See Object holds for more information about hold types.

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

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

    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.
    • [OBJECT_NAME] is the name of the relevant object. For example, pets/dog.png.

XML API

The XML API cannot be used to work with object holds. Use one of the other Cloud Storage tools, such as gsutil, instead.

What's next

หน้านี้มีประโยชน์ไหม โปรดแสดงความคิดเห็น

ส่งความคิดเห็นเกี่ยวกับ...

หากต้องการความช่วยเหลือ ให้ไปที่หน้าการสนับสนุน