Usar retenções de objeto

Visão geral

Nesta página, você verá como usar as retenções de objeto, incluindo a colocação de retenções por padrão em novos objetos e a colocação de retenções em objetos individuais.

Permissões necessárias

Antes de usar esse recurso no Cloud Storage, você precisa ter permissão suficiente para visualizar e atualizar buckets e objetos no Cloud Storage:

  • Se você é proprietário do projeto que contém o bucket, provavelmente já tem as permissões necessárias.

  • Para usar o IAM, é necessário ter as permissões storage.buckets.update, storage.buckets.get, storage.objects.update e storage.objects.get do bucket pertinente. Consulte Como usar permissões do IAM para instruções sobre como conseguir um papel, como Administrador do Storage, que tenha essas permissões.

  • Se você usar ACLs, precisará da permissão PROPRIETÁRIO no bucket em questão e nos objetos dentro dele. Consulte Como configurar ACLs para instruções sobre como fazer isso.

Ativar a propriedade de retenção baseada em evento padrão

As tarefas a seguir mostram como configurar e visualizar a propriedade de retenção baseada em eventos padrão em um bucket. Quando essa propriedade é ativada, novos objetos adicionados ao bucket recebem automaticamente uma retenção baseada em evento.

Configurar a propriedade de retenção baseada em evento padrão

Para ativar ou desativar a propriedade de retenção baseada em eventos padrão para um bucket, siga estas instruções:

Console

  1. No Console do Google Cloud, acesse a página Buckets do Cloud Storage.

    Acessar buckets

  2. Na lista de buckets, clique no nome daquele em que você quer definir a propriedade de retenção baseada em eventos padrão.

  3. Selecione a guia Proteção na parte superior da página.

    O status atual do bucket aparece na seção Opção de retenção baseada em evento padrão.

  4. Na seção Opção de retenção baseada em evento padrão, clique no status atual para alterá-lo.

    O status aparece como Ativado ou Desativado.

Para saber como acessar informações detalhadas de erro sobre operações do Cloud Storage com falha no console do Google Cloud, consulte Solução de problemas.

Linha de comando

Use o comando gcloud storage buckets update com a flag apropriada:

gcloud storage buckets update gs://BUCKET_NAME FLAG

Em que:

  • BUCKET_NAME é o nome do bucket pertinente. Por exemplo, my-bucket.

  • FLAG é --default-event-based-hold para ativar retenções de objeto padrão baseadas em eventos ou --no-default-event-based-hold para desativá-las.

Bibliotecas de cliente

C++

Para mais informações, consulte a documentação de referência da API Cloud Storage C++.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa retenções padrão baseadas em eventos em um 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";
}

O exemplo a seguir desativa as retenções padrão baseadas em eventos em um 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#

Para mais informações, consulte a documentação de referência da API Cloud Storage C#.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa retenções padrão baseadas em eventos em um 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;
    }
}

O exemplo a seguir desativa as retenções padrão baseadas em eventos em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Go.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa retenções padrão baseadas em eventos em um 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
}

O exemplo a seguir desativa as retenções padrão baseadas em eventos em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Java.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa retenções padrão baseadas em eventos em um 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);
  }
}

O exemplo a seguir desativa as retenções padrão baseadas em eventos em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Node.js.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa retenções padrão baseadas em eventos em um 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);

O exemplo a seguir desativa as retenções padrão baseadas em eventos em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage PHP.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa retenções padrão baseadas em eventos em um 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);
}

O exemplo a seguir desativa as retenções padrão baseadas em eventos em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Python.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa retenções padrão baseadas em eventos em um 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}")

O exemplo a seguir desativa as retenções padrão baseadas em eventos em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Ruby.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa retenções padrão baseadas em eventos em um 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

O exemplo a seguir desativa as retenções padrão baseadas em eventos em um 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 REST

API JSON

  1. Receba um token de acesso de autorização do OAuth 2.0 Playground. Configure o Playground para usar suas credenciais do OAuth. Para ver instruções, consulte Autenticação de APIs.
  2. Crie um arquivo JSON com as informações a seguir:

    {
      "defaultEventBasedHold": STATE
    }

    Em que STATE é true ou false.

  3. Use cURL para chamar a API JSON com uma solicitação de PATCHbucket:

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

    Em que:

    • JSON_FILE_NAME é o caminho para o arquivo criado na Etapa 2.
    • OAUTH2_TOKEN é o token de acesso gerado na Etapa 1.
    • BUCKET_NAME é o nome do bucket pertinente. Por exemplo, my-bucket.

API XML

A API XML não pode ser usada para trabalhar com retenções de objeto. Use uma das outras ferramentas do Cloud Storage, como a CLI gcloud, em vez disso.

Conseguir o status de retenção padrão de um bucket

Para ver se um bucket coloca as retenções baseadas em eventos em novos objetos por padrão:

Console

  1. No Console do Google Cloud, acesse a página Buckets do Cloud Storage.

    Acessar buckets

  2. Na lista de buckets, clique no nome daquele em que você quer verificar o status padrão baseado em eventos.

  3. Selecione a guia Proteção na parte superior da página.

  4. O status aparece na seção Opção de retenção baseada em evento padrão.

Para saber como acessar informações detalhadas de erro sobre operações do Cloud Storage com falha no console do Google Cloud, consulte Solução de problemas.

Linha de comando

Use o comando gcloud storage buckets describe com a flag --format:

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

Em que BUCKET_NAME é o nome do bucket com o status que você quer visualizar. Por exemplo, my-bucket.

Se a operação for bem-sucedida, a resposta será semelhante a esta:

default_event_based_hold: true

Bibliotecas de cliente

C++

Para mais informações, consulte a documentação de referência da API Cloud Storage C++.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento 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#

Para mais informações, consulte a documentação de referência da API Cloud Storage C#.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Go.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Java.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Node.js.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento 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

Para mais informações, consulte a documentação de referência da API Cloud Storage PHP.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Python.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Ruby.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento 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 REST

API JSON

  1. Receba um token de acesso de autorização do OAuth 2.0 Playground. Configure o Playground para usar suas credenciais do OAuth. Para ver instruções, consulte Autenticação de APIs.
  2. Use cURL para chamar a API JSON com uma solicitação de bucket GET que inclui o fields desejado:

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

    Em que:

    • OAUTH2_TOKEN é o token de acesso gerado na etapa 1;
    • BUCKET_NAME é o nome do bucket pertinente. Por exemplo, my-bucket.

    Se o bucket tiver uma retenção baseada em evento padrão ativada para ele, a resposta será semelhante ao exemplo a seguir:

    {
      "defaultEventBasedHold": true
    }

API XML

A API XML não pode ser usada para trabalhar com retenções de objeto. Use uma das outras ferramentas do Cloud Storage, como a CLI gcloud, em vez disso.

Gerenciar retenções de objetos individuais

As tarefas a seguir mostram como alterar e visualizar retenções em objetos individuais.

Colocar ou remover a retenção em um objeto

Para colocar ou remover a retenção em um objeto no bucket:

Console

  1. No Console do Google Cloud, acesse a página Buckets do Cloud Storage.

    Acessar buckets

  2. Na lista de buckets, clique no nome daquele que contém os objetos em que você quer colocar ou remover retenções.

  3. Marque a caixa de seleção ao lado dos nomes dos objetos em que você quer colocar ou remover retenções.

  4. Clique no botão Gerenciar retenções.

    A janela Gerenciar retenções é exibida.

  5. Marque as caixas de seleção para cada tipo de retenção que você quer.

  6. Clique em Salvar configurações de retenção.

Para saber como acessar informações detalhadas de erro sobre operações do Cloud Storage com falha no console do Google Cloud, consulte Solução de problemas.

Linha de comando

Use o comando gcloud storage objects update com a sinalização apropriada:

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

Em que:

  • BUCKET_NAME é o nome do bucket pertinente. Por exemplo, my-bucket.
  • OBJECT_NAME é o nome do objeto relevante. Por exemplo, pets/dog.png.
  • FLAG é um destes:

    • --event-based-hold para ativar uma retenção baseada em eventos no objeto.
    • --no-event-based-hold para desativar qualquer retenção baseada em eventos no objeto.
    • --temporary-hold para ativar uma retenção temporária no objeto.
    • --no-temporary-hold para desativar qualquer retenção temporária no objeto.

Saiba mais sobre os tipos de retenção em Retenções de objetos.

Bibliotecas de cliente

C++

Para mais informações, consulte a documentação de referência da API Cloud Storage C++.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir define uma retenção baseada em evento em um 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";
}

A amostra a seguir libera uma retenção baseada em evento em um 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";
}

A amostra a seguir define uma retenção temporária em um 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";
}

O exemplo a seguir libera uma retenção temporária em um 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#

Para mais informações, consulte a documentação de referência da API Cloud Storage C#.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir define uma retenção baseada em evento em um 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}.");
    }
}

A amostra a seguir libera uma retenção baseada em evento em um 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}.");
    }
}

A amostra a seguir define uma retenção temporária em um 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}.");
    }
}

O exemplo a seguir libera uma retenção temporária em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Go.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir define uma retenção baseada em evento em um 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
}

A amostra a seguir libera uma retenção baseada em evento em um 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
}

A amostra a seguir define uma retenção temporária em um 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
}

O exemplo a seguir libera uma retenção temporária em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Java.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir define uma retenção baseada em evento em um 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);
  }
}

A amostra a seguir libera uma retenção baseada em evento em um 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);
  }
}

A amostra a seguir define uma retenção temporária em um 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);
  }
}

O exemplo a seguir libera uma retenção temporária em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Node.js.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir define uma retenção baseada em evento em um 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);

A amostra a seguir libera uma retenção baseada em evento em um 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);

A amostra a seguir define uma retenção temporária em um 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);

O exemplo a seguir libera uma retenção temporária em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage PHP.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir define uma retenção baseada em evento em um 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);
}

A amostra a seguir libera uma retenção baseada em evento em um 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);
}

A amostra a seguir define uma retenção temporária em um 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);
}

O exemplo a seguir libera uma retenção temporária em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Python.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir define uma retenção baseada em evento em um 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}")

A amostra a seguir libera uma retenção baseada em evento em um 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}")

A amostra a seguir define uma retenção temporária em um 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}")

O exemplo a seguir libera uma retenção temporária em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Ruby.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

A amostra a seguir define uma retenção baseada em evento em um 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

A amostra a seguir libera uma retenção baseada em evento em um 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

A amostra a seguir define uma retenção temporária em um 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

O exemplo a seguir libera uma retenção temporária em um 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 REST

API JSON

  1. Receba um token de acesso de autorização do OAuth 2.0 Playground. Configure o Playground para usar suas credenciais do OAuth. Para ver instruções, consulte Autenticação de APIs.
  2. Crie um arquivo JSON com as informações a seguir:

    {
      "HOLD_TYPE": STATE
    }

    Em que:

    • HOLD_TYPE é o tipo de retenção que você quer colocar ou retirar no objeto. Por exemplo, temporaryHold ou eventBasedHold. Saiba mais sobre os tipos de retenção em Retenções de objetos.
    • STATE precisa ser true para colocar a retenção ou false para retirar a retenção.
  3. Use cURL para chamar a API JSON com uma solicitação de Objeto PATCH:

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

    Em que:

    • JSON_FILE_NAME é o caminho para o arquivo criado na Etapa 2.
    • OAUTH2_TOKEN é o token de acesso gerado na Etapa 1.
    • BUCKET_NAME é o nome do bucket pertinente. Por exemplo, my-bucket.
    • OBJECT_NAME é o nome codificado por URL do objeto relevante. Por exemplo, pets/dog.png, codificado em URL como pets%2Fdog.png.

API XML

A API XML não pode ser usada para trabalhar com retenções de objeto. Use uma das outras ferramentas do Cloud Storage, como a CLI gcloud, em vez disso.

Conseguir o status de retenção de um objeto

Para ver quais retenções existem em um objeto, se houver alguma, siga as instruções gerais sobre Como ver metadados de objeto.

A seguir