Rimuovi criterio di conservazione

Mostra un esempio di come rimuovere un criterio di conservazione da un bucket. Il criterio di conservazione del bucket deve essere sbloccato per poter rimuovere un criterio.

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:

Esempio di codice

C++

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

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

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

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

  if (!patched->has_retention_policy()) {
    std::cout << "The bucket " << patched->name()
              << " does not have a retention policy set.\n";
    return;
  }

  std::cout << "The bucket " << patched->name()
            << " retention policy is set to " << patched->retention_policy()
            << ". This is unexpected, maybe a concurrent change by another"
            << " application?\n";
}

C#

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

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


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

public class RemoveRetentionPolicySample
{
    public void RemoveRetentionPolicy(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        if (bucket.RetentionPolicy != null)
        {
            bool isLocked = bucket.RetentionPolicy.IsLocked ?? false;
            if (isLocked)
            {
                throw new Exception("Retention Policy is locked.");
            }

            bucket.RetentionPolicy.RetentionPeriod = null;
            storage.UpdateBucket(bucket);

            Console.WriteLine($"Retention period for {bucketName} has been removed.");
        }
    }
}

Go

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

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

ctx := context.Background()
bucket := c.Bucket(bucketName)

attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}
if attrs.RetentionPolicy.IsLocked {
	return errors.New("retention policy is locked")
}

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

Java

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

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


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 RemoveRetentionPolicy {
  public static void removeRetentionPolicy(String projectId, String bucketName)
      throws StorageException, IllegalArgumentException {
    // 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.RETENTION_POLICY));
    if (bucket.retentionPolicyIsLocked() != null && bucket.retentionPolicyIsLocked()) {
      throw new IllegalArgumentException(
          "Unable to remove retention policy as retention policy is locked.");
    }

    bucket.toBuilder().setRetentionPeriod(null).build().update();

    System.out.println("Retention policy for " + bucketName + " has been removed");
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

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

async function removeRetentionPolicy() {
  const [metadata] = await storage.bucket(bucketName).getMetadata();
  if (metadata.retentionPolicy && metadata.retentionPolicy.isLocked) {
    console.log(
      'Unable to remove retention period as retention policy is locked.'
    );
    return null;
  } else {
    const results = await storage.bucket(bucketName).removeRetentionPeriod();
    console.log(`Removed bucket ${bucketName} retention policy.`);
    return results;
  }
}

removeRetentionPolicy().catch(console.error);

PHP

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

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

use Google\Cloud\Storage\StorageClient;

/**
 * Removes a bucket's retention policy.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function remove_retention_policy(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->reload();

    if (array_key_exists('isLocked', $bucket->info()['retentionPolicy']) &&
        $bucket->info()['retentionPolicy']['isLocked']) {
        printf('Unable to remove retention period as retention policy is locked.' . PHP_EOL);
        return;
    }

    $bucket->update([
        'retentionPolicy' => []
    ]);
    printf('Removed bucket %s retention policy' . PHP_EOL, $bucketName);
}

Python

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

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

from google.cloud import storage

def remove_retention_policy(bucket_name):
    """Removes the retention policy on a given bucket"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    bucket.reload()

    if bucket.retention_policy_locked:
        print(
            "Unable to remove retention period as retention policy is locked."
        )
        return

    bucket.retention_period = None
    bucket.patch()

    print(f"Removed bucket {bucket.name} retention policy")

Ruby

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

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

def remove_retention_policy 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.retention_policy_locked?
    bucket.retention_period = nil
    puts "Retention policy for #{bucket_name} has been removed."
  else
    puts "Policy is locked and retention policy can't be removed."
  end
end

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.