Ajouter un libellé à un bucket

Permet d'ajouter un libellé à un bucket Cloud Storage.

En savoir plus

Pour obtenir une documentation détaillée incluant cet exemple de code, consultez la page suivante :

Exemple de code

C++

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage C++.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

  std::cout << "Successfully set label " << label_key << " to " << label_value
            << " on bucket  " << updated->name() << ".";
  std::cout << " The bucket labels are now:";
  for (auto const& kv : updated->labels()) {
    std::cout << "\n  " << kv.first << ": " << kv.second;
  }
  std::cout << "\n";
}

C#

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage C#.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class BucketAddLabelSample
{
    public Bucket BucketAddLabel(
        string bucketName = "your-bucket-name",
        string labelKey = "label-key-to-add",
        string labelValue = "label-value-to-add")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        if (bucket.Labels == null)
        {
            bucket.Labels = new Dictionary<string, string>();
        }
        bucket.Labels.Add(labelKey, labelValue);

        bucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Added label {labelKey} with value {labelValue} to bucket {bucketName}.");
        return bucket;
    }
}

Go

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Go.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

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

// addBucketLabel adds a label on a bucket.
func addBucketLabel(w io.Writer, bucketName, labelName, labelValue string) error {
	// bucketName := "bucket-name"
	// labelName := "label-name"
	// labelValue := "label-value"
	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.SetLabel(labelName, labelValue)
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Added label %q with value %q to bucket %v\n", labelName, labelValue, bucketName)
	return nil
}

Java

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Java.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement 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 AddBucketLabel {
  public static void addBucketLabel(
      String projectId, String bucketName, String labelKey, String labelValue) {
    // 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 add
    // String labelKey = "label-key-to-add";

    // The value of the label to add
    // String labelValue = "label-value-to-add";

    Map<String, String> newLabels = new HashMap<>();
    newLabels.put(labelKey, labelValue);

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    Map<String, String> labels = bucket.getLabels();
    if (labels != null) {
      newLabels.putAll(labels);
    }
    bucket.toBuilder().setLabels(newLabels).build().update();

    System.out.println(
        "Added label " + labelKey + " with value " + labelValue + " to bucket " + bucketName + ".");
  }
}

Node.js

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Node.js.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement 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 add
// const labelKey = 'label-key-to-add';

// The value of the label to add
// const labelValue = 'label-value-to-add';

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

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

const labels = {
  [labelKey]: labelValue,
};

async function addBucketLabel() {
  await storage.bucket(bucketName).setMetadata({labels});
  console.log(`Added label to bucket ${bucketName}`);
}

addBucketLabel().catch(console.error);

PHP

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage PHP.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

use Google\Cloud\Storage\StorageClient;

/**
 * Adds or updates a bucket label.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $labelName The name of the label to add.
 *        (e.g. 'label-key-to-add')
 * @param string $labelValue The value of the label to add.
 *        (e.g. 'label-value-to-add')
 */
function add_bucket_label(string $bucketName, string $labelName, string $labelValue): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $newLabels = [$labelName => $labelValue];
    $bucket->update(['labels' => $newLabels]);
    printf('Added label %s (%s) to %s' . PHP_EOL, $labelName, $labelValue, $bucketName);
}

Python

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Python.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

import pprint

from google.cloud import storage


def add_bucket_label(bucket_name):
    """Add a label to a bucket."""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    labels = bucket.labels
    labels["example"] = "label"
    bucket.labels = labels
    bucket.patch()

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

Ruby

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Ruby.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

def add_bucket_label bucket_name:, label_key:, label_value:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The key of the label to add
  # label_key = "label-key-to-add"

  # The value of the label to add
  # label_value = "label-value-to-add"

  require "google/cloud/storage"

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

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

  puts "Added label #{label_key} with value #{label_value} to #{bucket_name}"
end

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'explorateur d'exemples Google Cloud.