Quita una etiqueta del bucket

Quita una etiqueta de un bucket de Cloud Storage.

Explora más

Para obtener documentación detallada en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

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,
   std::string const& label_key) {
  StatusOr<gcs::BucketMetadata> updated = client.PatchBucket(
      bucket_name, gcs::BucketMetadataPatchBuilder().ResetLabel(label_key));
  if (!updated) throw std::move(updated).status();

  std::cout << "Successfully reset label " << label_key << " on bucket  "
            << updated->name() << ".";
  if (updated->labels().empty()) {
    std::cout << " The bucket now has no labels.\n";
    return;
  }
  std::cout << " The bucket labels are now:";
  for (auto const& kv : updated->labels()) {
    std::cout << "\n  " << kv.first << ": " << kv.second;
  }
  std::cout << "\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.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class BucketRemoveLabelSample
{
    public Bucket BucketRemoveLabel(string bucketName = "your-bucket-name", string labelKey = "label-key-to-remove")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        if (bucket.Labels != null && bucket.Labels.Keys.Contains(labelKey))
        {
            bucket.Labels.Remove(labelKey);
            bucket = storage.UpdateBucket(bucket);
            Console.WriteLine($"Removed label {labelKey} from bucket {bucketName}.");
        }
        else
        {
            Console.WriteLine($"No such label available on {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.

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

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

// removeBucketLabel removes a label on a bucket.
func removeBucketLabel(w io.Writer, bucketName, labelName string) error {
	// bucketName := "bucket-name"
	// labelName := "label-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()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{}
	bucketAttrsToUpdate.DeleteLabel(labelName)
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Removed label %q from bucket %v\n", labelName, bucketName)
	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.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.HashMap;
import java.util.Map;

public class RemoveBucketLabel {
  public static void removeBucketLabel(String projectId, String bucketName, String labelKey) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The key of the label to remove from the bucket
    // String labelKey = "label-key-to-remove";

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

    Map<String, String> labelsToRemove = new HashMap<>();
    labelsToRemove.put(labelKey, null);

    Bucket bucket = storage.get(bucketName);
    Map<String, String> labels;
    if (bucket.getLabels() == null) {
      labels = new HashMap<>();
    } else {
      labels = new HashMap(bucket.getLabels());
    }
    labels.putAll(labelsToRemove);
    bucket.toBuilder().setLabels(labels).build().update();

    System.out.println("Removed label " + labelKey + " from bucket " + 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';

// The key of the label to remove from the bucket
// const labelKey = 'label-key-to-remove';

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

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

async function removeBucketLabel() {
  const labels = {};
  // To remove a label set the value of the key to null.
  labels[labelKey] = null;
  await storage.bucket(bucketName).setMetadata({labels});
  console.log(`Removed labels from bucket ${bucketName}`);
}

removeBucketLabel().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;

/**
 * Removes a label from a bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $labelName The name of the label to remove.
 *        (e.g. 'label-key-to-remove')
 */
function remove_bucket_label(string $bucketName, string $labelName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $labels = [$labelName => null];
    $bucket->update(['labels' => $labels]);
    printf('Removed label %s from %s' . PHP_EOL, $labelName, $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.

import pprint

from google.cloud import storage


def remove_bucket_label(bucket_name):
    """Remove a label from a bucket."""
    # bucket_name = "your-bucket-name"

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

    labels = bucket.labels

    if "example" in labels:
        del labels["example"]

    bucket.labels = labels
    bucket.patch()

    print(f"Removed labels on {bucket.name}.")
    pprint.pprint(bucket.labels)

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 remove_bucket_label bucket_name:, label_key:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The key of the label to remove from the bucket
  # label_key = "label-key-to-remove"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.update do |bucket|
    bucket.labels[label_key] = nil
  end

  puts "Deleted label #{label_key} from #{bucket_name}"
end

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.