Use object holds

Overview

This page describes how to use object holds, including placing holds by default on new objects and placing holds on individual objects.

Required permissions

Before using this feature in Cloud Storage, you must 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 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.

Use the default event-based hold property

The following tasks show you how to set and view 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.

Set the default event-based hold property

To enable or disable the default event-based hold property for a bucket:

Console

  1. In the Google Cloud console, go to the Cloud Storage Buckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket that you want to set the default event-based hold property for.

  3. Select the Protectiontab near the top of the page.

    The current status for the bucket appears in the Default event-based hold optionsection.

  4. In the Default event-based hold optionsection, click the current status to change it.

    The status appears as either Enabledor Disabled.

To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, see Troubleshooting .

Command line

Use the gcloud storage buckets update command with the appropriate flag:

gcloud storage buckets update gs:// BUCKET_NAME 
 FLAG 

Where:

  • BUCKET_NAME is the name of the relevant bucket. For example, my-bucket .

  • FLAG is either --default-event-based-hold to enable default event-based object holds or --no-default-event-based-hold to disable them.

Client libraries

C++

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

The following sample enables default event-based holds on a bucket:

 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::move(original).status();

  StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetDefaultEventBasedHold(true),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!patched) throw std::move(patched).status();

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

The following sample disables default event-based holds on a bucket:

 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::move(original).status();
  StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetDefaultEventBasedHold(false),
      gcs::IfMetagenerationMatch(original->metageneration()));
  if (!patched) throw std::move(patched).status();

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

C#

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

The following sample enables default event-based holds on a bucket:

 using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class EnableBucketDefaultEventBasedHoldSample
{
    public Bucket EnableBucketDefaultEventBasedHold(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.DefaultEventBasedHold = true;
        bucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Default event-based hold was enabled for {bucketName}");
        return bucket;
    }
} 

The following sample disables default event-based holds on a bucket:

 using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class DisableDefaultEventBasedHoldSample
{
    public Bucket DisableDefaultEventBasedHold(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.DefaultEventBasedHold = false;
        bucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Default event-based hold was disabled for {bucketName}");
        return bucket;
    }
} 

Go

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

The following sample enables default event-based holds on a bucket:

 import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// enableDefaultEventBasedHold sets event-based hold to true.
func enableDefaultEventBasedHold(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		DefaultEventBasedHold: true,
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Default event-based hold was enabled for %v\n", bucketName)
	return nil
} 

The following sample disables default event-based holds on a bucket:

 import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// disableDefaultEventBasedHold sets event-based hold to false.
func disableDefaultEventBasedHold(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		DefaultEventBasedHold: false,
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Default event-based hold was disabled for %v\n", bucketName)
	return nil
} 

Java

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

The following sample enables default event-based holds on a bucket:

 import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.BucketTargetOption;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

public class EnableDefaultEventBasedHold {
  public static void enableDefaultEventBasedHold(String projectId, String bucketName)
      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";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    // first look up the bucket, so we will have its metageneration
    Bucket bucket = storage.get(bucketName);
    storage.update(
        bucket.toBuilder().setDefaultEventBasedHold(true).build(),
        BucketTargetOption.metagenerationMatch());

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

The following sample disables default event-based holds on a bucket:

 import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.Storage.BucketTargetOption;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

public class DisableDefaultEventBasedHold {
  public static void disableDefaultEventBasedHold(String projectId, String bucketName)
      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";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    // first look up the bucket, so we will have its metageneration
    Bucket bucket = storage.get(bucketName);
    storage.update(
        bucket.toBuilder().setDefaultEventBasedHold(false).build(),
        BucketTargetOption.metagenerationMatch());

    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 .

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

The following sample enables default event-based holds on a bucket:

 /**
 * 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 enableDefaultEventBasedHold() {
  // 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}.`);
}

enableDefaultEventBasedHold().catch(console.error); 

The following sample disables default event-based holds on a bucket:

 /**
 * 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 disableDefaultEventBasedHold() {
  // 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}.`);
}

disableDefaultEventBasedHold().catch(console.error); 

PHP

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

The following sample enables default event-based holds on a bucket:

 use Google\Cloud\Storage\StorageClient;

/**
 * Enables a default event-based hold for a bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function enable_default_event_based_hold(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update(['defaultEventBasedHold' => true]);
    printf('Default event-based hold was enabled for %s' . PHP_EOL, $bucketName);
} 

The following sample disables default event-based holds on a bucket:

 use Google\Cloud\Storage\StorageClient;

/**
 * Disables a default event-based hold for a bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function disable_default_event_based_hold(string $bucketName): void
{
    $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 .

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

The following sample enables default event-based holds on a bucket:

 from google.cloud import storage


def enable_default_event_based_hold(bucket_name):
    """Enables the default event based hold on a given bucket"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    bucket.default_event_based_hold = True
    bucket.patch()

    print(f"Default event based hold was enabled for {bucket_name}") 

The following sample disables default event-based holds on a bucket:

 from google.cloud import storage


def disable_default_event_based_hold(bucket_name):
    """Disables the default event based hold on a given bucket"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.default_event_based_hold = False
    bucket.patch()

    print(f"Default event based hold was disabled for {bucket_name}") 

Ruby

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

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

The following sample enables default event-based holds on a bucket:

 def enable_default_event_based_hold 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

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

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

The following sample disables default event-based holds on a bucket:

 def disable_default_event_based_hold 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

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

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