Utilizzare blocchi degli oggetti

Overview

In questa pagina viene descritto come utilizzare i blocchi degli oggetti, inclusi i blocchi per impostazione predefinita su nuovi oggetti e i singoli oggetti.

Autorizzazioni obbligatorie

Prima di utilizzare questa funzionalità in Cloud Storage, devi disporre di autorizzazioni sufficienti per visualizzare e aggiornare bucket e oggetti in Cloud Storage:

  • Se sei il proprietario del progetto che contiene il bucket, molto probabilmente disponi delle autorizzazioni necessarie.

  • Se utilizzi IAM, devi disporre delle autorizzazioni storage.buckets.update, storage.buckets.get, storage.objects.update e storage.objects.get nel bucket pertinente. Per istruzioni su come ottenere un ruolo, ad esempio Amministratore archiviazione, che dispone di queste autorizzazioni, consulta Utilizzo delle autorizzazioni IAM.

  • Se utilizzi ACL, devi disporre dell'autorizzazione OWNER per il bucket pertinente e per gli oggetti al suo interno. Per istruzioni su come eseguire questa operazione, consulta Impostazione degli ACL.

Utilizza la proprietà di blocco basata su eventi predefinita

Le attività seguenti mostrano come impostare e visualizzare la proprietà di blocco predefinita basata su eventi in un bucket. Quando questa proprietà è abilitata, i nuovi oggetti aggiunti al bucket ricevono automaticamente un blocco basato su eventi.

Impostare la proprietà di blocco basata su eventi predefinita

Per abilitare o disabilitare la proprietà di blocco basata su eventi predefinita per un bucket:

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket per cui vuoi impostare la proprietà di blocco basata su eventi predefinita.

  3. Seleziona la scheda Protezione nella parte superiore della pagina.

    Lo stato attuale del bucket viene visualizzato nella sezione Opzione di blocco basato su eventi predefinita.

  4. Nella sezione Opzione di blocco basato su eventi predefinita, fai clic sullo stato attuale per modificarlo.

    Lo stato visualizzato sarà Attivato o Disattivato.

Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni di Cloud Storage non riuscite nella console Google Cloud, consulta Risoluzione dei problemi.

Riga di comando

Utilizza il comando gcloud storage buckets update con il flag appropriato:

gcloud storage buckets update gs://BUCKET_NAME FLAG

Dove:

  • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

  • FLAG è --default-event-based-hold per abilitare i blocchi di oggetti predefiniti basati su eventi o --no-default-event-based-hold per disabilitarli.

Librerie client

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i blocchi predefiniti basati su eventi in un 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";
}

Il seguente esempio disabilita i blocchi predefiniti basati su eventi in un 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#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i blocchi predefiniti basati su eventi in un 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;
    }
}

Il seguente esempio disabilita i blocchi predefiniti basati su eventi in un 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i blocchi predefiniti basati su eventi in un bucket:

ctx := context.Background()

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	DefaultEventBasedHold: true,
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Il seguente esempio disabilita i blocchi predefiniti basati su eventi in un bucket:

ctx := context.Background()

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	DefaultEventBasedHold: false,
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Java

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i blocchi predefiniti basati su eventi in un 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);
  }
}

Il seguente esempio disabilita i blocchi predefiniti basati su eventi in un 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i blocchi predefiniti basati su eventi in un 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);

Il seguente esempio disabilita i blocchi predefiniti basati su eventi in un 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i blocchi predefiniti basati su eventi in un 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);
}

Il seguente esempio disabilita i blocchi predefiniti basati su eventi in un 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i blocchi predefiniti basati su eventi in un 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}")

Il seguente esempio disabilita i blocchi predefiniti basati su eventi in un 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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Il seguente esempio abilita i blocchi predefiniti basati su eventi in un 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

Il seguente esempio disabilita i blocchi predefiniti basati su eventi in un 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

API REST

API JSON

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file JSON contenente le seguenti informazioni:

    {
      "defaultEventBasedHold": STATE
    }

    Dove STATE è true o false.

  3. Utilizza cURL per chiamare l'API JSON con una richiesta di bucket PATCH:

    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"

    Dove:

    • JSON_FILE_NAME è il percorso del file creato nel passaggio 2.
    • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

API XML

L'API XML non può essere utilizzata per gestire blocchi di oggetti. Utilizza invece uno degli altri strumenti di Cloud Storage, come gcloud CLI.

Recuperare lo stato di conservazione predefinito di un bucket

Per vedere se un bucket applica blocchi basati su eventi sui nuovi oggetti per impostazione predefinita:

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket di cui vuoi controllare lo stato predefinito basato su eventi.

  3. Seleziona la scheda Protezione nella parte superiore della pagina.

  4. Lo stato viene visualizzato nella sezione Opzione di blocco predefinito basato su eventi.

Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni di Cloud Storage non riuscite nella console Google Cloud, consulta Risoluzione dei problemi.

Riga di comando

Utilizza il comando gcloud storage buckets describe con il flag --format:

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

Dove BUCKET_NAME è il nome del bucket di cui vuoi visualizzare lo stato, Ad esempio, my-bucket.

In caso di esito positivo, la risposta sarà simile al seguente esempio:

default_event_based_hold: true

Librerie client

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> bucket_metadata =
      client.GetBucketMetadata(bucket_name);
  if (!bucket_metadata) throw std::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#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


using Google.Cloud.Storage.V1;
using System;

public class GetDefaultEventBasedHoldSample
{
    public bool GetDefaultEventBasedHold(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bool defaultEventBasedHold = bucket.DefaultEventBasedHold ?? false;
        Console.WriteLine($"Default event-based hold: {defaultEventBasedHold}");
        return defaultEventBasedHold;
    }
}

Go

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

public class GetDefaultEventBasedHold {
  public static void getDefaultEventBasedHold(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();
    Bucket bucket =
        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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

/**
 * 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 getDefaultEventBasedHold() {
  const [metadata] = await storage.bucket(bucketName).getMetadata();
  console.log(`Default event-based hold: ${metadata.defaultEventBasedHold}.`);
}

getDefaultEventBasedHold().catch(console.error);

PHP

Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

from google.cloud import storage

def get_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)

    if bucket.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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

  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
end

API REST

API JSON

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Utilizza cURL per chiamare l'API JSON con una richiesta bucket GET che include il valore fields desiderato:

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

    Dove BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

    Se nel bucket è abilitato un blocco basato su eventi predefinito, la risposta sarà simile al seguente esempio:

    {
      "defaultEventBasedHold": true
    }

API XML

L'API XML non può essere utilizzata per gestire blocchi di oggetti. Utilizza invece uno degli altri strumenti di Cloud Storage, come gcloud CLI.

Gestire singole archiviazioni a fini legali

Le attività seguenti mostrano come modificare e visualizzare i blocchi sui singoli oggetti.

Posizionare o rilasciare un blocco oggetto

Per posizionare o rilasciare un blocco su un oggetto nel bucket:

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket che contiene gli oggetti per cui vuoi applicare o rimuovere le archiviazioni a fini legali.

  3. Seleziona la casella di controllo accanto ai nomi degli oggetti che vuoi applicare o rimuovere le archiviazioni a fini legali.

  4. Fai clic sul pulsante Gestisci archiviazioni a fini legali.

    Viene visualizzata la finestra Gestisci archiviazioni a fini legali.

  5. Attiva/disattiva le caselle di controllo per ciascun tipo di blocco come preferisci.

  6. Fai clic su Salva impostazioni di archiviazione a fini legali.

Per scoprire come ottenere informazioni dettagliate sugli errori relativi alle operazioni di Cloud Storage non riuscite nella console Google Cloud, consulta Risoluzione dei problemi.

Riga di comando

Utilizza il comando gcloud storage objects update con il flag appropriato:

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME FLAG

Dove:

  • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.
  • OBJECT_NAME è il nome dell'oggetto pertinente. Ad esempio, pets/dog.png.
  • FLAG è uno dei seguenti:

    • --event-based-hold per attivare un blocco basato su evento sull'oggetto.
    • --no-event-based-hold per disabilitare qualsiasi blocco basato su eventi sull'oggetto.
    • --temporary-hold per attivare un blocco temporaneo dell'oggetto.
    • --no-temporary-hold per disattivare l'eventuale blocco temporaneo dell'oggetto.

Per saperne di più sui tipi di archiviazione a fini legali, consulta Archiviazioni a fini legali degli oggetti.

Librerie client

C++

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C++ di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Nell'esempio seguente viene impostato un blocco basato su eventi su un oggetto:

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

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

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

L'esempio seguente rilascia un blocco basato su eventi su un oggetto:

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

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

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

Nell'esempio seguente viene impostato un blocco temporaneo su un oggetto:

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

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

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

L'esempio seguente rilascia un blocco temporaneo su un oggetto:

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

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

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

C#

Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Nell'esempio seguente viene impostato un blocco basato su eventi su un oggetto:


using Google.Cloud.Storage.V1;
using System;

public class SetEventBasedHoldSample
{
    public void SetEventBasedHold(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName);
        storageObject.EventBasedHold = true;
        storage.UpdateObject(storageObject);
        Console.WriteLine($"Event-based hold was set for {objectName}.");
    }
}

L'esempio seguente rilascia un blocco basato su eventi su un oggetto:


using Google.Cloud.Storage.V1;
using System;

public class ReleaseEventBasedHoldSample
{
    public void ReleaseEventBasedHold(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName);
        storageObject.EventBasedHold = false;
        storage.UpdateObject(storageObject);
        Console.WriteLine($"Event-based hold was released for {objectName}.");
    }
}

Nell'esempio seguente viene impostato un blocco temporaneo su un oggetto:


using Google.Cloud.Storage.V1;

public class SetTemporaryHoldSample
{
    public void SetTemporaryHold(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName);
        storageObject.TemporaryHold = true;
        storage.UpdateObject(storageObject);
        System.Console.WriteLine($"Temporary hold was set for {objectName}.");
    }
}

L'esempio seguente rilascia un blocco temporaneo su un oggetto:


using Google.Cloud.Storage.V1;
using System;

public class ReleaseTemporaryHoldSample
{
    public void ReleaseTemporaryHold(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName);
        storageObject.TemporaryHold = false;
        storage.UpdateObject(storageObject);
        Console.WriteLine($"Temporary hold was released for {objectName}.");
    }
}

Go

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Nell'esempio seguente viene impostato un blocco basato su eventi su un oggetto:

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

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

// setEventBasedHold sets EventBasedHold flag of an object to true.
func setEventBasedHold(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-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()

	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)
	if err != nil {
		return fmt.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 {
		return fmt.Errorf("Object(%q).Update: %w", object, err)
	}
	fmt.Fprintf(w, "Default event based hold was enabled for %v.\n", object)
	return nil
}

L'esempio seguente rilascia un blocco basato su eventi su un oggetto:

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

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

// releaseEventBasedHold releases an object with event-based hold.
func releaseEventBasedHold(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-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()

	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)
	if err != nil {
		return fmt.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 {
		return fmt.Errorf("Object(%q).Update: %w", object, err)
	}
	fmt.Fprintf(w, "Event based hold was released for %v.\n", object)
	return nil
}

Nell'esempio seguente viene impostato un blocco temporaneo su un oggetto:

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

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

// setTemporaryHold sets TemporaryHold flag of an object to true.
func setTemporaryHold(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-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()

	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)
	if err != nil {
		return fmt.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 {
		return fmt.Errorf("Object(%q).Update: %w", object, err)
	}
	fmt.Fprintf(w, "Temporary hold was enabled for %v.\n", object)
	return nil
}

L'esempio seguente rilascia un blocco temporaneo su un oggetto:

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

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

// releaseTemporaryHold releases an object with temporary hold.
func releaseTemporaryHold(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-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()

	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)
	if err != nil {
		return fmt.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 {
		return fmt.Errorf("Object(%q).Update: %w", object, err)
	}
	fmt.Fprintf(w, "Temporary hold was released for %v.\n", object)
	return nil
}

Java

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Nell'esempio seguente viene impostato un blocco basato su eventi su un oggetto:


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

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

    // The ID of your GCS object
    // String objectName = "your-object-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    Blob blob = 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.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();

    blob.toBuilder().setEventBasedHold(true).build().update(precondition);

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

L'esempio seguente rilascia un blocco basato su eventi su un oggetto:


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

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

    // The ID of your GCS object
    // String objectName = "your-object-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    Blob blob = 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.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();

    blob.toBuilder().setEventBasedHold(false).build().update(precondition);

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

Nell'esempio seguente viene impostato un blocco temporaneo su un oggetto:


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

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

    // The ID of your GCS object
    // String objectName = "your-object-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    Blob blob = 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.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();

    blob.toBuilder().setTemporaryHold(true).build().update(precondition);

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

L'esempio seguente rilascia un blocco temporaneo su un oggetto:


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

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

    // The ID of your GCS object
    // String objectName = "your-object-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    BlobId blobId = BlobId.of(bucketName, objectName);
    Blob blob = 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.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();

    blob.toBuilder().setTemporaryHold(false).build().update(precondition);

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

Node.js

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Node.js di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Nell'esempio seguente viene impostato un blocco basato su eventi su un oggetto:

/**
 * 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 library
const {Storage} = require('@google-cloud/storage');

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

async function setEventBasedHold() {
  // 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.
  const options = {
    ifMetagenerationMatch: metagenerationMatchPrecondition,
  };

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

setEventBasedHold().catch(console.error);

L'esempio seguente rilascia un blocco basato su eventi su un oggetto:

/**
 * 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 library
const {Storage} = require('@google-cloud/storage');

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

async function releaseEventBasedHold() {
  // 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.
  const options = {
    ifMetagenerationMatch: metagenerationMatchPrecondition,
  };

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

releaseEventBasedHold().catch(console.error);

Nell'esempio seguente viene impostato un blocco temporaneo su un oggetto:

/**
 * 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 library
const {Storage} = require('@google-cloud/storage');

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

async function setTemporaryHold() {
  // 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.
  const options = {
    ifMetagenerationMatch: metagenerationMatchPrecondition,
  };

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

setTemporaryHold().catch(console.error);

L'esempio seguente rilascia un blocco temporaneo su un oggetto:

/**
 * 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 library
const {Storage} = require('@google-cloud/storage');

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

async function releaseTemporaryHold() {
  // 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.
  const options = {
    ifMetagenerationMatch: metagenerationMatchPrecondition,
  };

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

releaseTemporaryHold().catch(console.error);

PHP

Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Nell'esempio seguente viene impostato un blocco basato su eventi su un oggetto:

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

L'esempio seguente rilascia un blocco basato su eventi su un oggetto:

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

Nell'esempio seguente viene impostato un blocco temporaneo su un oggetto:

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

L'esempio seguente rilascia un blocco temporaneo su un oggetto:

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

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Nell'esempio seguente viene impostato un blocco basato su eventi su un oggetto:

from google.cloud import storage

def set_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.metageneration

    blob.event_based_hold = True
    blob.patch(if_metageneration_match=metageneration_match_precondition)

    print(f"Event based hold was set for {blob_name}")

L'esempio seguente rilascia un blocco basato su eventi su un oggetto:

from google.cloud import storage

def release_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.metageneration

    blob.event_based_hold = False
    blob.patch(if_metageneration_match=metageneration_match_precondition)

    print(f"Event based hold was released for {blob_name}")

Nell'esempio seguente viene impostato un blocco temporaneo su un oggetto:

from google.cloud import storage

def set_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.metageneration

    blob.temporary_hold = True
    blob.patch(if_metageneration_match=metageneration_match_precondition)

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

L'esempio seguente rilascia un blocco temporaneo su un oggetto:

from google.cloud import storage

def release_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.metageneration

    blob.temporary_hold = False
    blob.patch(if_metageneration_match=metageneration_match_precondition)

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

Ruby

Per maggiori informazioni, consulta la documentazione di riferimento dell'API Ruby di Cloud Storage.

Per eseguire l'autenticazione in Cloud Storage, configura Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

Nell'esempio seguente viene impostato un blocco basato su eventi su un oggetto:

def set_event_based_hold bucket_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.new
  bucket  = storage.bucket bucket_name, skip_lookup: true
  file    = bucket.file file_name

  file.set_event_based_hold!

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

L'esempio seguente rilascia un blocco basato su eventi su un oggetto:

def release_event_based_hold bucket_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.new
  bucket  = storage.bucket bucket_name, skip_lookup: true
  file    = bucket.file file_name

  file.release_event_based_hold!

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

Nell'esempio seguente viene impostato un blocco temporaneo su un oggetto:

def set_temporary_hold bucket_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.new
  bucket  = storage.bucket bucket_name, skip_lookup: true
  file    = bucket.file file_name

  file.set_temporary_hold!

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

L'esempio seguente rilascia un blocco temporaneo su un oggetto:

def release_temporary_hold bucket_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.new
  bucket  = storage.bucket bucket_name, skip_lookup: true
  file    = bucket.file file_name

  file.release_temporary_hold!

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

API REST

API JSON

  1. Assicurati che gcloud CLI sia installato e inizializzatoper generare un token di accesso per l'intestazione Authorization.

    In alternativa, puoi creare un token di accesso utilizzando OAuth 2.0 Playground e includerlo nell'intestazione Authorization.

  2. Crea un file JSON contenente le seguenti informazioni:

    {
      "HOLD_TYPE": STATE
    }

    Dove:

    • HOLD_TYPE è il tipo di blocco che vuoi impostare o rilasciare sull'oggetto. Ad esempio, temporaryHold o eventBasedHold. Per ulteriori informazioni sui tipi di blocco, consulta Archiviazioni a fini legali degli oggetti.
    • STATE è true per applicare il blocco o false per rilasciarlo.
  3. Utilizza cURL per chiamare l'API JSON con una richiesta Oggetto PATCH:

    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"

    Dove:

    • JSON_FILE_NAME è il percorso del file creato nel passaggio 2.
    • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.
    • OBJECT_NAME è il nome con codifica URL dell'oggetto pertinente. Ad esempio, pets/dog.png, con codifica URL come pets%2Fdog.png.

API XML

L'API XML non può essere utilizzata per gestire blocchi di oggetti. Utilizza invece uno degli altri strumenti di Cloud Storage, come gcloud CLI.

Conoscere lo stato di un blocco per un oggetto

Per visualizzare gli eventuali blocchi presenti su un oggetto, segui le istruzioni generali per la visualizzazione dei metadati degli oggetti.

Passaggi successivi