Usar conservaciones de objetos

Descripción general

En esta página, se describe cómo usar conservaciones de objetos, incluida la colocación predeterminada de conservaciones en objetos nuevos y en objetos individuales.

Permisos necesarios

Antes de usar esta función en Cloud Storage, debes tener permisos suficientes para ver y actualizar los buckets y objetos en Cloud Storage:

  • Si eres propietario del proyecto que contiene el bucket, es probable que tengas los permisos necesarios.

  • Si usas IAM, debes tener los permisos storage.buckets.update, storage.buckets.get, storage.objects.update y storage.objects.get en el bucket correspondiente. Consulta Usa permisos de Cloud IAM para obtener instrucciones sobre como recibir un rol con estos permisos, como el de Administrador de almacenamiento.

  • Si usas las LCA, debes tener permisos de PROPIETARIO en el bucket relevante y en los objetos que contiene. Consulta el documento Configura las LCA para obtener instrucciones sobre cómo hacerlo.

Usa la propiedad de retención predeterminada basada en eventos

En las siguientes tareas, se muestra cómo configurar y ver la propiedad de retención predeterminada basada en eventos en un bucket. Cuando se habilita esta propiedad, los objetos nuevos agregados al bucket obtienen de manera automática una retención basada en eventos.

Configura la propiedad de retención predeterminada basada en eventos

Sigue estos pasos para habilitar o inhabilitar la propiedad de retención predeterminada basada en eventos para un bucket:

Console

  1. En la consola de Google Cloud, ve a la página Buckets de Cloud Storage.

    Ir a Buckets

  2. En la lista de buckets, haz clic en el nombre del bucket en el que deseas establecer la propiedad de retención predeterminada basada en eventos.

  3. Selecciona la pestaña Protección cerca de la parte superior de la página.

    El estado actual del bucket aparece en la sección Opción de retención predeterminada basada en eventos.

  4. En la sección Opción de retención predeterminada basada en eventos, haz clic en el estado actual para cambiarla.

    El estado aparece como Habilitado o Inhabilitado.

Para obtener información sobre cómo ver detalles de errores acerca de operaciones fallidas de Cloud Storage en la consola de Google Cloud, consulta Solución de problemas.

Línea de comandos

Usa el comando gcloud storage buckets update con la marca adecuada:

gcloud storage buckets update gs://BUCKET_NAME FLAG

Donde:

  • BUCKET_NAME es el nombre del bucket correspondiente. Por ejemplo, my-bucket

  • FLAG es --default-event-based-hold para habilitar las conservaciones de objetos predeterminadas basadas en eventos o --no-default-event-based-hold para inhabilitarlas.

Bibliotecas cliente

C++

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C++.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilitan las retenciones predeterminadas basadas en eventos en 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";
}

En el siguiente ejemplo, se inhabilitan las retenciones predeterminadas basadas en eventos en 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#

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C#.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilitan las retenciones predeterminadas basadas en eventos en 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;
    }
}

En el siguiente ejemplo, se inhabilitan las retenciones predeterminadas basadas en eventos en 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Go.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilitan las retenciones predeterminadas basadas en eventos en 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
}

En el siguiente ejemplo, se inhabilitan las retenciones predeterminadas basadas en eventos en 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Java.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilitan las retenciones predeterminadas basadas en eventos en 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);
  }
}

En el siguiente ejemplo, se inhabilitan las retenciones predeterminadas basadas en eventos en 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Node.js.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilitan las retenciones predeterminadas basadas en eventos en 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);

En el siguiente ejemplo, se inhabilitan las retenciones predeterminadas basadas en eventos en 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage PHP.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilitan las retenciones predeterminadas basadas en eventos en 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);
}

En el siguiente ejemplo, se inhabilitan las retenciones predeterminadas basadas en eventos en 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Python.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilitan las retenciones predeterminadas basadas en eventos en 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}")

En el siguiente ejemplo, se inhabilitan las retenciones predeterminadas basadas en eventos en 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Ruby.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilitan las retenciones predeterminadas basadas en eventos en 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

En el siguiente ejemplo, se inhabilitan las retenciones predeterminadas basadas en eventos en 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

APIs de REST

API de JSON

  1. Obtén un token de autorización de acceso de OAuth 2.0 Playground. Configura Playground para usar tus credenciales de OAuth. Para obtener instrucciones, consulta Autenticación de la API.
  2. Crea un archivo JSON que contenga la siguiente información:

    {
      "defaultEventBasedHold": STATE
    }

    En el que STATE es true o false.

  3. Usa cURL para llamar a la API de JSON con una solicitud de bucket PATCH:

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

    Donde:

    • JSON_FILE_NAME es la ruta de acceso del archivo que creaste en el paso 2.
    • OAUTH2_TOKEN es el token de acceso que generaste en el paso 1.
    • BUCKET_NAME es el nombre del bucket correspondiente. Por ejemplo, my-bucket

API de XML

La API de XML no se puede usar para trabajar con conservaciones de objetos. En su lugar, usa una de las otras herramientas de Cloud Storage, como la CLI de gcloud.

Obtén el estado de retención predeterminado de un bucket

Sigue los pasos a continuación para ver si un bucket coloca retenciones basadas en eventos en objetos nuevos de forma predeterminada:

Console

  1. En la consola de Google Cloud, ve a la página Buckets de Cloud Storage.

    Ir a Buckets

  2. En la lista de buckets, haz clic en el nombre del bucket del que quieras verificar el estado predeterminado basado en eventos.

  3. Selecciona la pestaña Protección cerca de la parte superior de la página.

  4. El estado aparece en la sección Opción de retención basada en eventos de forma predeterminada.

Para obtener información sobre cómo ver detalles de errores acerca de operaciones fallidas de Cloud Storage en la consola de Google Cloud, consulta Solución de problemas.

Línea de comandos

Usa el comando gcloud storage buckets describe con la marca --format:

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

En el ejemplo anterior, BUCKET_NAME es el nombre del bucket cuyo estado deseas ver. Por ejemplo, my-bucket.

Si se realiza de forma correcta, la respuesta se verá como el ejemplo siguiente:

default_event_based_hold: true

Bibliotecas cliente

C++

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C++.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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#

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C#.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Go.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Java.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Node.js.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

/**
 * 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage PHP.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Python.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Ruby.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

APIs de REST

API de JSON

  1. Obtén un token de autorización de acceso de OAuth 2.0 Playground. Configura Playground para usar tus credenciales de OAuth. Para obtener instrucciones, consulta Autenticación de la API.
  2. Usa cURL para llamar a la API de JSON con una solicitud de bucket GET que incluya los fields deseados:

    curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" \
    "https://storage./storage/v1/b/BUCKET_NAME?fields=defaultEventBasedHold"

    En la que

    • OAUTH2_TOKEN es el token de acceso que generaste en el paso 1.
    • BUCKET_NAME es el nombre del bucket correspondiente. Por ejemplo, my-bucket

    Si el bucket tiene habilitada una conservación predeterminada basada en eventos, la respuesta se parece al siguiente ejemplo:

    {
      "defaultEventBasedHold": true
    }

API de XML

La API de XML no se puede usar para trabajar con conservaciones de objetos. En su lugar, usa una de las otras herramientas de Cloud Storage, como la CLI de gcloud.

Administra conservaciones de objetos individuales

En las siguientes tareas, se muestra cómo modificar y ver conservaciones en los objetos individuales.

Coloca o libera una conservación de objeto

Sigue los pasos a continuación para colocar o liberar una conservación en un objeto en tu bucket:

Console

  1. En la consola de Google Cloud, ve a la página Buckets de Cloud Storage.

    Ir a Buckets

  2. En la lista de buckets, haz clic en el nombre del bucket que contiene los objetos en los que deseas colocar o liberar conservaciones.

  3. Selecciona la casilla de verificación junto a los nombres de los objetos en los que deseas colocar o liberar conservaciones.

  4. Haz clic en el botón Administrar retenciones.

    Aparecerá la ventana Administrar retenciones.

  5. Activa o desactiva las casillas de verificación de cada tipo de conservación como desees.

  6. Haz clic en Guardar configuración de conservación.

Para obtener información sobre cómo ver detalles de errores acerca de operaciones fallidas de Cloud Storage en la consola de Google Cloud, consulta Solución de problemas.

Línea de comandos

Usa el comando gcloud storage objects update con la marca adecuada:

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

Aquí:

  • BUCKET_NAME es el nombre del bucket correspondiente. Por ejemplo, my-bucket
  • OBJECT_NAME es el nombre del objeto pertinente. Por ejemplo, pets/dog.png
  • FLAG es una de las siguientes opciones:

    • --event-based-hold para habilitar una conservación basada en eventos en el objeto
    • --no-event-based-hold para inhabilitar cualquier conservación basada en eventos en el objeto
    • --temporary-hold para habilitar una conservación temporal en el objeto.
    • --no-temporary-hold para inhabilitar cualquier conservación temporal en el objeto

Consulta Conservaciones de objetos para obtener más información sobre los tipos de conservación.

Bibliotecas cliente

C++

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C++.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

El siguiente ejemplo configura una retención basada en eventos en un objeto:

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

El siguiente ejemplo libera una retención basada en eventos en un objeto:

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

El siguiente ejemplo configura una retención temporal en un objeto:

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

El siguiente ejemplo libera una retención temporal en un objeto:

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#

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C#.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

El siguiente ejemplo configura una retención basada en eventos en un objeto:


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

El siguiente ejemplo libera una retención basada en eventos en un objeto:


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

El siguiente ejemplo configura una retención temporal en un objeto:


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

El siguiente ejemplo libera una retención temporal en un objeto:


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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Go.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

El siguiente ejemplo configura una retención basada en eventos en un objeto:

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
}

El siguiente ejemplo libera una retención basada en eventos en un objeto:

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
}

El siguiente ejemplo configura una retención temporal en un objeto:

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
}

El siguiente ejemplo libera una retención temporal en un objeto:

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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Java.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

El siguiente ejemplo configura una retención basada en eventos en un objeto:


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

El siguiente ejemplo libera una retención basada en eventos en un objeto:


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

El siguiente ejemplo configura una retención temporal en un objeto:


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

El siguiente ejemplo libera una retención temporal en un objeto:


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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Node.js.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

El siguiente ejemplo configura una retención basada en eventos en un objeto:

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

El siguiente ejemplo libera una retención basada en eventos en un objeto:

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

El siguiente ejemplo configura una retención temporal en un objeto:

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

El siguiente ejemplo libera una retención temporal en un objeto:

/**
 * 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage PHP.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

El siguiente ejemplo configura una retención basada en eventos en un objeto:

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

El siguiente ejemplo libera una retención basada en eventos en un objeto:

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

El siguiente ejemplo configura una retención temporal en un objeto:

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

El siguiente ejemplo libera una retención temporal en un objeto:

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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Python.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

El siguiente ejemplo configura una retención basada en eventos en un objeto:

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

El siguiente ejemplo libera una retención basada en eventos en un objeto:

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

El siguiente ejemplo configura una retención temporal en un objeto:

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

El siguiente ejemplo libera una retención temporal en un objeto:

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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Ruby.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

El siguiente ejemplo configura una retención basada en eventos en un objeto:

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

El siguiente ejemplo libera una retención basada en eventos en un objeto:

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

El siguiente ejemplo configura una retención temporal en un objeto:

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

El siguiente ejemplo libera una retención temporal en un objeto:

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

APIs de REST

API de JSON

  1. Obtén un token de autorización de acceso de OAuth 2.0 Playground. Configura Playground para usar tus credenciales de OAuth. Para obtener instrucciones, consulta Autenticación de la API.
  2. Crea un archivo JSON que contenga la siguiente información:

    {
      "HOLD_TYPE": STATE
    }

    Aquí:

    • HOLD_TYPE es el tipo de conservación que quieres establecer o liberar en tu objeto. Por ejemplo, temporaryHold o eventBasedHold. Consulta Conservaciones de objetos para obtener más información sobre los tipos de conservación.
    • STATE es true para colocar la conservación o false para liberar la conservación.
  3. Usa cURL para llamar a la API de JSON con una solicitud de objeto PATCH:

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

    Aquí:

    • JSON_FILE_NAME es la ruta de acceso del archivo que creaste en el paso 2.
    • OAUTH2_TOKEN es el token de acceso que generaste en el paso 1.
    • BUCKET_NAME es el nombre del bucket correspondiente. Por ejemplo, my-bucket
    • OBJECT_NAME es el nombre codificado en URL del objeto relevante. Por ejemplo, pets/dog.png, codificado en URL como pets%2Fdog.png.

API de XML

La API de XML no se puede usar para trabajar con conservaciones de objetos. En su lugar, usa una de las otras herramientas de Cloud Storage, como la CLI de gcloud.

Obtén el estado de conservación de un objeto

A fin de ver si alguna retención existe en un objeto, sigue las instrucciones generales para ver metadatos de objeto.

¿Qué sigue?