Use object holds

Overview

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

Required permissions

Before using this feature in Cloud Storage, you must have sufficientpermission to view and update buckets and objects in Cloud Storage:

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

  • If you use IAM, you should havestorage.buckets.update,storage.buckets.get,storage.objects.update, andstorage.objects.getpermissions on the relevant bucket. SeeUsing IAM Permissions forinstructions on how to get a role, such asStorage Admin, that has thesepermissions.

  • If you use ACLs, you should have OWNER permission on the relevant bucket andon the objects within it. SeeSetting ACLs for instructions on how to dothis.

Use the default event-based hold property

The following tasks show you how to set and view thedefault event-based hold property on a bucket. When this property isenabled, new objects added to the bucket automatically get an event-based holdplaced 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 StorageBuckets page.

    Go to Buckets

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

  3. Select theProtection tab near the top of the page.

    The current status for the bucket appears in theDefault event-basedhold option section.

  4. In theDefault event-based hold option section, click the currentstatus to change it.

    The status appears as eitherEnabled orDisabled.

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

Command line

Use thegcloud storage buckets update command with theappropriate flag:

gcloud storage buckets update gs://BUCKET_NAMEFLAG

Where:

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

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

Client libraries

C++

For more information, see theCloud StorageC++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name){StatusOr<gcs::BucketMetadata>original=client.GetBucketMetadata(bucket_name);if(!original)throwstd::move(original).status();StatusOr<gcs::BucketMetadata>patched=client.PatchBucket(bucket_name,gcs::BucketMetadataPatchBuilder().SetDefaultEventBasedHold(true),gcs::IfMetagenerationMatch(original->metageneration()));if(!patched)throwstd::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:

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name){StatusOr<gcs::BucketMetadata>original=client.GetBucketMetadata(bucket_name);if(!original)throwstd::move(original).status();StatusOr<gcs::BucketMetadata>patched=client.PatchBucket(bucket_name,gcs::BucketMetadataPatchBuilder().SetDefaultEventBasedHold(false),gcs::IfMetagenerationMatch(original->metageneration()));if(!patched)throwstd::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 theCloud StorageC# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassEnableBucketDefaultEventBasedHoldSample{publicBucketEnableBucketDefaultEventBasedHold(stringbucketName="your-unique-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName);bucket.DefaultEventBasedHold=true;bucket=storage.UpdateBucket(bucket);Console.WriteLine($"Default event-based hold was enabled for {bucketName}");returnbucket;}}

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

usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassDisableDefaultEventBasedHoldSample{publicBucketDisableDefaultEventBasedHold(stringbucketName="your-unique-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName);bucket.DefaultEventBasedHold=false;bucket=storage.UpdateBucket(bucket);Console.WriteLine($"Default event-based hold was disabled for {bucketName}");returnbucket;}}

Go

For more information, see theCloud StorageGo API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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.funcenableDefaultEventBasedHold(wio.Writer,bucketNamestring)error{// bucketName := "bucket-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()bucket:=client.Bucket(bucketName)bucketAttrsToUpdate:=storage.BucketAttrsToUpdate{DefaultEventBasedHold:true,}if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)}fmt.Fprintf(w,"Default event-based hold was enabled for %v\n",bucketName)returnnil}

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.funcdisableDefaultEventBasedHold(wio.Writer,bucketNamestring)error{// bucketName := "bucket-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()bucket:=client.Bucket(bucketName)bucketAttrsToUpdate:=storage.BucketAttrsToUpdate{DefaultEventBasedHold:false,}if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)}fmt.Fprintf(w,"Default event-based hold was disabled for %v\n",bucketName)returnnil}

Java

For more information, see theCloud StorageJava API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.Storage.BucketTargetOption;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassEnableDefaultEventBasedHold{publicstaticvoidenableDefaultEventBasedHold(StringprojectId,StringbucketName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();// first look up the bucket, so we will have its metagenerationBucketbucket=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:

importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.Storage.BucketTargetOption;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassDisableDefaultEventBasedHold{publicstaticvoiddisableDefaultEventBasedHold(StringprojectId,StringbucketName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();// first look up the bucket, so we will have its metagenerationBucketbucket=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 theCloud StorageNode.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionenableDefaultEventBasedHold(){// Enables a default event-based hold for the bucket.awaitstorage.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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiondisableDefaultEventBasedHold(){// Disables a default event-based hold for a bucket.awaitstorage.bucket(bucketName).setMetadata({defaultEventBasedHold:false,});console.log(`Default event-based hold was disabled for${bucketName}.`);}disableDefaultEventBasedHold().catch(console.error);

PHP

For more information, see theCloud StoragePHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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 theCloud StoragePython API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

fromgoogle.cloudimportstoragedefenable_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=Truebucket.patch()print(f"Default event based hold was enabled for{bucket_name}")

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

fromgoogle.cloudimportstoragedefdisable_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=Falsebucket.patch()print(f"Default event based hold was disabled for{bucket_name}")

Ruby

For more information, see theCloud StorageRuby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

defenable_default_event_based_holdbucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.updatedo|b|b.default_event_based_hold=trueendputs"Default event-based hold was enabled for#{bucket_name}."end

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

defdisable_default_event_based_holdbucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.updatedo|b|b.default_event_based_hold=falseendputs"Default event-based hold was disabled for#{bucket_name}."end

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. Create a JSON file that contains the following information:

    {"defaultEventBasedHold":STATE}

    WhereSTATE is eithertrue orfalse.

  3. UsecURL to call the JSON API with aPATCH Bucketrequest:

    curl -X PATCH --data-binary @JSON_FILE_NAME \-H "Authorization: Bearer $(gcloud auth print-access-token)" \-H "Content-Type: application/json" \"https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=defaultEventBasedHold"

    Where:

    • JSON_FILE_NAME is the path for the filethat you created in Step 2.
    • BUCKET_NAME is the name of the relevantbucket. For example,my-bucket.

XML API

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

Get the default hold status of a bucket

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

Console

  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket that you want tocheck the default event-based status for.

  3. Select theProtection tab near the top of the page.

  4. The status appears in theDefault event-based hold option section.

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

Command line

Use thegcloud storage buckets describe command with the--format flag:

gcloud storage buckets describe gs://BUCKET_NAME --format="default(default_event_based_hold)"

WhereBUCKET_NAME is the name of the bucketwhose status you want to view. For example,my-bucket.

If successful, the response looks similar to the following example:

default_event_based_hold:true

Client libraries

C++

For more information, see theCloud StorageC++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name){StatusOr<gcs::BucketMetadata>bucket_metadata=client.GetBucketMetadata(bucket_name);if(!bucket_metadata)throwstd::move(bucket_metadata).status();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 theCloud StorageC# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

usingGoogle.Cloud.Storage.V1;usingSystem;publicclassGetDefaultEventBasedHoldSample{publicboolGetDefaultEventBasedHold(stringbucketName="your-unique-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName);booldefaultEventBasedHold=bucket.DefaultEventBasedHold??false;Console.WriteLine($"Default event-based hold: {defaultEventBasedHold}");returndefaultEventBasedHold;}}

Go

For more information, see theCloud StorageGo API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

import("context""fmt""io""time""cloud.google.com/go/storage")// getDefaultEventBasedHold gets default event-based hold state.funcgetDefaultEventBasedHold(wio.Writer,bucketNamestring)(*storage.BucketAttrs,error){// bucketName := "bucket-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnnil,fmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()attrs,err:=client.Bucket(bucketName).Attrs(ctx)iferr!=nil{returnnil,fmt.Errorf("Bucket(%q).Attrs: %w",bucketName,err)}fmt.Fprintf(w,"Default event-based hold enabled? %t\n",attrs.DefaultEventBasedHold)returnattrs,nil}

Java

For more information, see theCloud StorageJava API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassGetDefaultEventBasedHold{publicstaticvoidgetDefaultEventBasedHold(StringprojectId,StringbucketName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Bucketbucket=storage.get(bucketName,Storage.BucketGetOption.fields(Storage.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 theCloud StorageNode.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

/** * 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiongetDefaultEventBasedHold(){const[metadata]=awaitstorage.bucket(bucketName).getMetadata();console.log(`Default event-based hold:${metadata.defaultEventBasedHold}.`);}getDefaultEventBasedHold().catch(console.error);

PHP

For more information, see theCloud StoragePHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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 get_default_event_based_hold(string $bucketName): void{    $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 theCloud StoragePython API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

fromgoogle.cloudimportstoragedefget_default_event_based_hold(bucket_name):"""Gets the default event based hold on a given bucket"""# bucket_name = "my-bucket"storage_client=storage.Client()bucket=storage_client.get_bucket(bucket_name)ifbucket.default_event_based_hold:print(f"Default event-based hold is enabled for{bucket_name}")else:print(f"Default event-based hold is not enabled for{bucket_name}")

Ruby

For more information, see theCloud StorageRuby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

defget_default_event_based_holdbucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_nameifbucket.default_event_based_hold?puts"Default event-based hold is enabled for#{bucket_name}."elseputs"Default event-based hold is not enabled for#{bucket_name}."endend

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. UsecURL to call the JSON API with aGET Bucketrequest that includes the desiredfields:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \"https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=defaultEventBasedHold"

    WhereBUCKET_NAME is the name of therelevant bucket. For example,my-bucket.

    If the bucket has a default event-based hold enabled for it, theresponse looks like the following example:

    {  "defaultEventBasedHold": true}

XML API

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

Manage individual object holds

The following tasks show you how to modify and viewholds on individualobjects.

Place or release an object hold

To place or release a hold on an object in your bucket:

Console

  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket that has theobjects you want to place or remove holds on.

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

  4. Click theManage holds button.

    TheManage holds window appears.

  5. Toggle the checkboxes for each hold type as desired.

  6. ClickSave hold settings.

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

Command line

Use thegcloud storage objects update command with theappropriate flag::

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAMEFLAG

Where:

  • BUCKET_NAME is the name of the relevantbucket. For example,my-bucket.
  • OBJECT_NAME is the name of the relevantobject. For example,pets/dog.png.
  • FLAG is one of the following:

    • --event-based-hold to enable an event based hold on the object.
    • --no-event-based-hold to disable any event based hold on theobject.
    • --temporary-hold to enable a temporary hold on the object.
    • --no-temporary-hold to disable any temporary hold on the object.

SeeObject holds for more information about hold types.

Client libraries

C++

For more information, see theCloud StorageC++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name){StatusOr<gcs::ObjectMetadata>original=client.GetObjectMetadata(bucket_name,object_name);if(!original)throwstd::move(original).status();StatusOr<gcs::ObjectMetadata>updated=client.PatchObject(bucket_name,object_name,gcs::ObjectMetadataPatchBuilder().SetEventBasedHold(true),gcs::IfMetagenerationMatch(original->metageneration()));if(!updated)throwstd::move(updated).status();std::cout <<"The event hold for object " <<updated->name()            <<" in bucket " <<updated->bucket() <<" is "            <<(updated->event_based_hold()?"enabled":"disabled") <<"\n";}

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

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name){StatusOr<gcs::ObjectMetadata>original=client.GetObjectMetadata(bucket_name,object_name);if(!original)throwstd::move(original).status();StatusOr<gcs::ObjectMetadata>updated=client.PatchObject(bucket_name,object_name,gcs::ObjectMetadataPatchBuilder().SetEventBasedHold(false),gcs::IfMetagenerationMatch(original->metageneration()));if(!updated)throwstd::move(updated).status();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:

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name){StatusOr<gcs::ObjectMetadata>original=client.GetObjectMetadata(bucket_name,object_name);if(!original)throwstd::move(original).status();StatusOr<gcs::ObjectMetadata>updated=client.PatchObject(bucket_name,object_name,gcs::ObjectMetadataPatchBuilder().SetTemporaryHold(true),gcs::IfMetagenerationMatch(original->metageneration()));if(!updated)throwstd::move(updated).status();std::cout <<"The temporary hold for object " <<updated->name()            <<" in bucket " <<updated->bucket() <<" is "            <<(updated->temporary_hold()?"enabled":"disabled") <<"\n";}

The following sample releases a temporary hold on an object:

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name){StatusOr<gcs::ObjectMetadata>original=client.GetObjectMetadata(bucket_name,object_name);if(!original)throwstd::move(original).status();StatusOr<gcs::ObjectMetadata>updated=client.PatchObject(bucket_name,object_name,gcs::ObjectMetadataPatchBuilder().SetTemporaryHold(false),gcs::IfMetagenerationMatch(original->metageneration()));if(!updated)throwstd::move(updated).status();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 theCloud StorageC# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

usingGoogle.Cloud.Storage.V1;usingSystem;publicclassSetEventBasedHoldSample{publicvoidSetEventBasedHold(stringbucketName="your-unique-bucket-name",stringobjectName="your-object-name"){varstorage=StorageClient.Create();varstorageObject=storage.GetObject(bucketName,objectName);storageObject.EventBasedHold=true;storage.UpdateObject(storageObject);Console.WriteLine($"Event-based hold was set for {objectName}.");}}

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

usingGoogle.Cloud.Storage.V1;usingSystem;publicclassReleaseEventBasedHoldSample{publicvoidReleaseEventBasedHold(stringbucketName="your-unique-bucket-name",stringobjectName="your-object-name"){varstorage=StorageClient.Create();varstorageObject=storage.GetObject(bucketName,objectName);storageObject.EventBasedHold=false;storage.UpdateObject(storageObject);Console.WriteLine($"Event-based hold was released for {objectName}.");}}

The following sample sets a temporary hold on an object:

usingGoogle.Cloud.Storage.V1;publicclassSetTemporaryHoldSample{publicvoidSetTemporaryHold(stringbucketName="your-unique-bucket-name",stringobjectName="your-object-name"){varstorage=StorageClient.Create();varstorageObject=storage.GetObject(bucketName,objectName);storageObject.TemporaryHold=true;storage.UpdateObject(storageObject);System.Console.WriteLine($"Temporary hold was set for {objectName}.");}}

The following sample releases a temporary hold on an object:

usingGoogle.Cloud.Storage.V1;usingSystem;publicclassReleaseTemporaryHoldSample{publicvoidReleaseTemporaryHold(stringbucketName="your-unique-bucket-name",stringobjectName="your-object-name"){varstorage=StorageClient.Create();varstorageObject=storage.GetObject(bucketName,objectName);storageObject.TemporaryHold=false;storage.UpdateObject(storageObject);Console.WriteLine($"Temporary hold was released for {objectName}.");}}

Go

For more information, see theCloud StorageGo API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

import("context""fmt""io""time""cloud.google.com/go/storage")// setEventBasedHold sets EventBasedHold flag of an object to true.funcsetEventBasedHold(wio.Writer,bucket,objectstring)error{// bucket := "bucket-name"// object := "object-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()o:=client.Bucket(bucket).Object(object)// Optional: set a metageneration-match precondition to avoid potential race// conditions and data corruptions. The request to update is aborted if the// object's metageneration does not match your precondition.attrs,err:=o.Attrs(ctx)iferr!=nil{returnfmt.Errorf("object.Attrs: %w",err)}o=o.If(storage.Conditions{MetagenerationMatch:attrs.Metageneration})// Update the object to add the object hold.objectAttrsToUpdate:=storage.ObjectAttrsToUpdate{EventBasedHold:true,}if_,err:=o.Update(ctx,objectAttrsToUpdate);err!=nil{returnfmt.Errorf("Object(%q).Update: %w",object,err)}fmt.Fprintf(w,"Default event based hold was enabled for %v.\n",object)returnnil}

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

import("context""fmt""io""time""cloud.google.com/go/storage")// releaseEventBasedHold releases an object with event-based hold.funcreleaseEventBasedHold(wio.Writer,bucket,objectstring)error{// bucket := "bucket-name"// object := "object-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()o:=client.Bucket(bucket).Object(object)// Optional: set a metageneration-match precondition to avoid potential race// conditions and data corruptions. The request to update is aborted if the// object's metageneration does not match your precondition.attrs,err:=o.Attrs(ctx)iferr!=nil{returnfmt.Errorf("object.Attrs: %w",err)}o=o.If(storage.Conditions{MetagenerationMatch:attrs.Metageneration})// Update the object to release the object hold.objectAttrsToUpdate:=storage.ObjectAttrsToUpdate{EventBasedHold:false,}if_,err:=o.Update(ctx,objectAttrsToUpdate);err!=nil{returnfmt.Errorf("Object(%q).Update: %w",object,err)}fmt.Fprintf(w,"Event based hold was released for %v.\n",object)returnnil}

The following sample sets a temporary hold on an object:

import("context""fmt""io""time""cloud.google.com/go/storage")// setTemporaryHold sets TemporaryHold flag of an object to true.funcsetTemporaryHold(wio.Writer,bucket,objectstring)error{// bucket := "bucket-name"// object := "object-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()o:=client.Bucket(bucket).Object(object)// Optional: set a metageneration-match precondition to avoid potential race// conditions and data corruptions. The request to update is aborted if the// object's metageneration does not match your precondition.attrs,err:=o.Attrs(ctx)iferr!=nil{returnfmt.Errorf("object.Attrs: %w",err)}o=o.If(storage.Conditions{MetagenerationMatch:attrs.Metageneration})// Update the object to set the object hold.objectAttrsToUpdate:=storage.ObjectAttrsToUpdate{TemporaryHold:true,}if_,err:=o.Update(ctx,objectAttrsToUpdate);err!=nil{returnfmt.Errorf("Object(%q).Update: %w",object,err)}fmt.Fprintf(w,"Temporary hold was enabled for %v.\n",object)returnnil}

The following sample releases a temporary hold on an object:

import("context""fmt""io""time""cloud.google.com/go/storage")// releaseTemporaryHold releases an object with temporary hold.funcreleaseTemporaryHold(wio.Writer,bucket,objectstring)error{// bucket := "bucket-name"// object := "object-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()o:=client.Bucket(bucket).Object(object)// Optional: set a metageneration-match precondition to avoid potential race// conditions and data corruptions. The request to update is aborted if the// object's metageneration does not match your precondition.attrs,err:=o.Attrs(ctx)iferr!=nil{returnfmt.Errorf("object.Attrs: %w",err)}o=o.If(storage.Conditions{MetagenerationMatch:attrs.Metageneration})// Update the object to release the hold.objectAttrsToUpdate:=storage.ObjectAttrsToUpdate{TemporaryHold:false,}if_,err:=o.Update(ctx,objectAttrsToUpdate);err!=nil{returnfmt.Errorf("Object(%q).Update: %w",object,err)}fmt.Fprintf(w,"Temporary hold was released for %v.\n",object)returnnil}

Java

For more information, see theCloud StorageJava API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassSetEventBasedHold{publicstaticvoidsetEventBasedHold(StringprojectId,StringbucketName,StringobjectName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The ID of your GCS object// String objectName = "your-object-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();BlobIdblobId=BlobId.of(bucketName,objectName);Blobblob=storage.get(blobId);if(blob==null){System.out.println("The object "+objectName+" was not found in "+bucketName);return;}// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request to upload returns a 412 error if// the object's generation number does not match your precondition.Storage.BlobTargetOptionprecondition=Storage.BlobTargetOption.generationMatch();blob.toBuilder().setEventBasedHold(true).build().update(precondition);System.out.println("Event-based hold was set for "+objectName);}}

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

importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassReleaseEventBasedHold{publicstaticvoidreleaseEventBasedHold(StringprojectId,StringbucketName,StringobjectName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The ID of your GCS object// String objectName = "your-object-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();BlobIdblobId=BlobId.of(bucketName,objectName);Blobblob=storage.get(blobId);if(blob==null){System.out.println("The object "+objectName+" was not found in "+bucketName);return;}// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request to upload returns a 412 error if// the object's generation number does not match your precondition.Storage.BlobTargetOptionprecondition=Storage.BlobTargetOption.generationMatch();blob.toBuilder().setEventBasedHold(false).build().update(precondition);System.out.println("Event-based hold was released for "+objectName);}}

The following sample sets a temporary hold on an object:

importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassSetTemporaryHold{publicstaticvoidsetTemporaryHold(StringprojectId,StringbucketName,StringobjectName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The ID of your GCS object// String objectName = "your-object-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();BlobIdblobId=BlobId.of(bucketName,objectName);Blobblob=storage.get(blobId);if(blob==null){System.out.println("The object "+objectName+" was not found in "+bucketName);return;}// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request to upload returns a 412 error if// the object's generation number does not match your precondition.Storage.BlobTargetOptionprecondition=Storage.BlobTargetOption.generationMatch();blob.toBuilder().setTemporaryHold(true).build().update(precondition);System.out.println("Temporary hold was set for "+objectName);}}

The following sample releases a temporary hold on an object:

importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassReleaseTemporaryHold{publicstaticvoidreleaseTemporaryHold(StringprojectId,StringbucketName,StringobjectName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The ID of your GCS object// String objectName = "your-object-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();BlobIdblobId=BlobId.of(bucketName,objectName);Blobblob=storage.get(blobId);if(blob==null){System.out.println("The object "+objectName+" was not found in "+bucketName);return;}// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request to upload returns a 412 error if// the object's generation number does not match your precondition.Storage.BlobTargetOptionprecondition=Storage.BlobTargetOption.generationMatch();blob.toBuilder().setTemporaryHold(false).build().update(precondition);System.out.println("Temporary hold was released for "+objectName);}}

Node.js

For more information, see theCloud StorageNode.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of your GCS file// const fileName = 'your-file-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionsetEventBasedHold(){// Optional: set a meta-generation-match precondition to avoid potential race// conditions and data corruptions. The request to set metadata is aborted if the// object's metageneration number does not match your precondition.constoptions={ifMetagenerationMatch:metagenerationMatchPrecondition,};// Set event-based holdawaitstorage.bucket(bucketName).file(fileName).setMetadata({eventBasedHold:true,},options);console.log(`Event-based hold was set for${fileName}.`);}setEventBasedHold().catch(console.error);

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

/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of your GCS file// const fileName = 'your-file-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionreleaseEventBasedHold(){// Optional: set a meta-generation-match precondition to avoid potential race// conditions and data corruptions. The request to set metadata is aborted if the// object's metageneration number does not match your precondition.constoptions={ifMetagenerationMatch:metagenerationMatchPrecondition,};awaitstorage.bucket(bucketName).file(fileName).setMetadata({eventBasedHold:false,},options);console.log(`Event-based hold was released for${fileName}.`);}releaseEventBasedHold().catch(console.error);

The following sample sets a temporary hold on an object:

/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of your GCS file// const fileName = 'your-file-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionsetTemporaryHold(){// Optional: set a meta-generation-match precondition to avoid potential race// conditions and data corruptions. The request to set metadata is aborted if the// object's metageneration number does not match your precondition.constoptions={ifMetagenerationMatch:metagenerationMatchPrecondition,};awaitstorage.bucket(bucketName).file(fileName).setMetadata({temporaryHold:true,},options);console.log(`Temporary hold was set for${fileName}.`);}setTemporaryHold().catch(console.error);

The following sample releases a temporary hold on an object:

/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of your GCS file// const fileName = 'your-file-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionreleaseTemporaryHold(){// Optional: set a meta-generation-match precondition to avoid potential race// conditions and data corruptions. The request to set metadata is aborted if the// object's metageneration number does not match your precondition.constoptions={ifMetagenerationMatch:metagenerationMatchPrecondition,};awaitstorage.bucket(bucketName).file(fileName).setMetadata({temporaryHold:false,},options);console.log(`Temporary hold was released for${fileName}.`);}releaseTemporaryHold().catch(console.error);

PHP

For more information, see theCloud StoragePHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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. *        (e.g. 'my-bucket') * @param string $objectName The name of your Cloud Storage object. *        (e.g. 'my-object') */function set_event_based_hold(string $bucketName, string $objectName): void{    $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 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. *        (e.g. 'my-bucket') * @param string $objectName The name of your Cloud Storage object. *        (e.g. 'my-object') */function release_event_based_hold(string $bucketName, string $objectName): void{    $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 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. *        (e.g. 'my-bucket') * @param string $objectName The name of your Cloud Storage object. *        (e.g. 'my-object') */function set_temporary_hold(string $bucketName, string $objectName): void{    $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);}

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. *        (e.g. 'my-bucket') * @param string $objectName The name of your Cloud Storage object. *        (e.g. 'my-object') */function release_temporary_hold(string $bucketName, string $objectName): void{    $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 theCloud StoragePython API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

fromgoogle.cloudimportstoragedefset_event_based_hold(bucket_name,blob_name):"""Sets a event based hold on a given blob"""# bucket_name = "my-bucket"# blob_name = "my-blob"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.blob(blob_name)metageneration_match_precondition=None# Optional: set a metageneration-match precondition to avoid potential race# conditions and data corruptions. The request to patch is aborted if the# object's metageneration does not match your precondition.blob.reload()# Fetch blob metadata to use in metageneration_match_precondition.metageneration_match_precondition=blob.metagenerationblob.event_based_hold=Trueblob.patch(if_metageneration_match=metageneration_match_precondition)print(f"Event based hold was set for{blob_name}")

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

fromgoogle.cloudimportstoragedefrelease_event_based_hold(bucket_name,blob_name):"""Releases the event based hold on a given blob"""# bucket_name = "my-bucket"# blob_name = "my-blob"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.blob(blob_name)metageneration_match_precondition=None# Optional: set a metageneration-match precondition to avoid potential race# conditions and data corruptions. The request to patch is aborted if the# object's metageneration does not match your precondition.blob.reload()# Fetch blob metadata to use in metageneration_match_precondition.metageneration_match_precondition=blob.metagenerationblob.event_based_hold=Falseblob.patch(if_metageneration_match=metageneration_match_precondition)print(f"Event based hold was released for{blob_name}")

The following sample sets a temporary hold on an object:

fromgoogle.cloudimportstoragedefset_temporary_hold(bucket_name,blob_name):"""Sets a temporary hold on a given blob"""# bucket_name = "my-bucket"# blob_name = "my-blob"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.blob(blob_name)metageneration_match_precondition=None# Optional: set a metageneration-match precondition to avoid potential race# conditions and data corruptions. The request to patch is aborted if the# object's metageneration does not match your precondition.blob.reload()# Fetch blob metadata to use in metageneration_match_precondition.metageneration_match_precondition=blob.metagenerationblob.temporary_hold=Trueblob.patch(if_metageneration_match=metageneration_match_precondition)print("Temporary hold was set for #{blob_name}")

The following sample releases a temporary hold on an object:

fromgoogle.cloudimportstoragedefrelease_temporary_hold(bucket_name,blob_name):"""Releases the temporary hold on a given blob"""# bucket_name = "my-bucket"# blob_name = "my-blob"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.blob(blob_name)metageneration_match_precondition=None# Optional: set a metageneration-match precondition to avoid potential race# conditions and data corruptions. The request to patch is aborted if the# object's metageneration does not match your precondition.blob.reload()# Fetch blob metadata to use in metageneration_match_precondition.metageneration_match_precondition=blob.metagenerationblob.temporary_hold=Falseblob.patch(if_metageneration_match=metageneration_match_precondition)print("Temporary hold was release for #{blob_name}")

Ruby

For more information, see theCloud StorageRuby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

defset_event_based_holdbucket_name:,file_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your GCS object# file_name = "your-file-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_name,skip_lookup:truefile=bucket.filefile_namefile.set_event_based_hold!puts"Event-based hold was set for#{file_name}."end

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

defrelease_event_based_holdbucket_name:,file_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your GCS object# file_name = "your-file-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_name,skip_lookup:truefile=bucket.filefile_namefile.release_event_based_hold!puts"Event-based hold was released for#{file_name}."end

The following sample sets a temporary hold on an object:

defset_temporary_holdbucket_name:,file_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your GCS object# file_name = "your-file-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_name,skip_lookup:truefile=bucket.filefile_namefile.set_temporary_hold!puts"Temporary hold was set for#{file_name}."end

The following sample releases a temporary hold on an object:

defrelease_temporary_holdbucket_name:,file_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your GCS object# file_name = "your-file-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_name,skip_lookup:truefile=bucket.filefile_namefile.release_temporary_hold!puts"Temporary hold was released for#{file_name}."end

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. Create a JSON file that contains the following information:

    {"HOLD_TYPE":STATE}

    Where:

  3. UsecURL to call the JSON API with aPATCH Object request:

    curl -X PATCH --data-binary @JSON_FILE_NAME \-H "Authorization: Bearer $(gcloud auth print-access-token)" \-H "Content-Type: application/json" \"https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME"

    Where:

    • JSON_FILE_NAME is the path for the filethat you created in Step 2.
    • BUCKET_NAME is the name of the relevantbucket. For example,my-bucket.
    • OBJECT_NAME is the URL-encoded name of therelevant object. For example,pets/dog.png, URL-encoded aspets%2Fdog.png.

XML API

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

Get the hold status for an object

Note: You cannot view object holds using the XML API. Use one of the otherCloud Storage tools, such as the gcloud CLI, instead.

To view what, if any, holds exist on an object, follow the general instructionsforviewing object metadata.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-19 UTC.