Etiqueta claves

Cloud Key Management Service proporciona la opción de agregar etiquetas a tus claves de Cloud KMS. Las etiquetas son pares clave-valor que puedes usar para agrupar las claves de Cloud KMS relacionadas y almacenar metadatos sobre una clave de Cloud KMS.

Las etiquetas se incluyen en tu factura, lo que te permite ver cómo se distribuyen los costos entre tus etiquetas.

Puedes agregar, actualizar y quitar etiquetas de claves con Google Cloud CLI y la API de REST de Cloud KMS.

Puedes usar etiquetas con otros recursos de Google Cloud, como los recursos de máquinas virtuales y los buckets de almacenamiento. Para obtener más información sobre cómo usar las etiquetas en Google Cloud, consulta Crea y administra etiquetas.

¿Qué son las etiquetas?

Una etiqueta es un par clave-valor que puedes asignar a las claves de Cloud KMS de Google Cloud. Te ayudan a organizar estos recursos y administrar los costos a gran escala, con el nivel de detalle que necesitas. Puedes adjuntar una etiqueta a cada recurso y, luego, usarlas para filtrarlos. La información sobre las etiquetas se envía al sistema de facturación que te permite desglosar los cargos facturados por etiqueta. Con los informes de facturación integrados, puedes filtrar y agrupar costos por etiquetas de recurso. También puedes usar etiquetas para consultar las exportaciones de datos de facturación.

Requisitos para las etiquetas

Las etiquetas que se aplican a un recurso deben cumplir los siguientes requisitos:

  • Cada recurso puede tener hasta 64 etiquetas.
  • Cada etiqueta debe ser un par clave-valor.
  • La longitud de las claves debe ser de entre 1 y 63 caracteres, y no pueden estar vacías. Los valores pueden estar vacíos y su longitud máxima es de 63 caracteres.
  • Las claves y los valores pueden contener solo letras en minúscula, caracteres numéricos, guiones bajos y guiones. Todos los caracteres deben usar la codificación UTF-8, además, se permiten los caracteres internacionales. Las claves deben comenzar con una letra en minúscula o un carácter internacional.
  • La porción de clave de una etiqueta debe ser única para un solo recurso. Sin embargo, puedes usar la misma clave en varios recursos.

Estos límites se aplican a la clave y al valor de cada etiqueta de clúster, y a los recursos individuales de Google Cloud que tienen etiquetas de clúster. No hay límite para la cantidad de etiquetas de clúster que puedes aplicar en todos los recursos de un proyecto.

Usos comunes de las etiquetas

Estos son algunos casos prácticos comunes de las etiquetas:

  • Etiquetas de equipo o centro de costos: agrega etiquetas según el equipo o centro de costos para distinguir las claves de Cloud KMS que pertenecen a equipos diferentes (por ejemplo, team:research y team:analytics). Puedes usar este tipo de etiquetas para la contabilidad de costos o la creación de presupuestos.

  • Etiquetas de componentes: por ejemplo, component:redis, component:frontend, component:ingest y component:dashboard.

  • Etiquetas de entorno o etapa: por ejemplo, environment:production y environment:test.

  • Etiquetas de estado: por ejemplo, state:active, state:readytodelete y state:archive.

  • Etiquetas de propiedad: Se usan para identificar a los equipos responsables de las operaciones, por ejemplo: team:shopping-cart.

No recomendamos crear grandes cantidades de etiquetas únicas, como marcas de tiempo o valores individuales para cada llamada a la API. El problema con este enfoque es que, cuando los valores cambian con frecuencia o con claves que sobrecargan el catálogo, esto dificulta el filtrado y la generación de informes eficaces para los recursos.

Etiquetas

Las etiquetas se pueden usar como anotaciones que se pueden consultar en los recursos, pero no se pueden usar para establecer condiciones en las políticas. Las etiquetas proporcionan una forma de permitir o rechazar políticas de manera condicional en función de si un recurso tiene una etiqueta específica, ya que proporciona un control detallado sobre las políticas. Para obtener más información, consulta la Descripción general de etiquetas.

Cómo crear una clave con etiquetas

Para agregar etiquetas cuando crees una clave, debes proporcionar uno o más pares clave-valor durante la operación de creación.

Console

  1. Ve a la página Administración de claves en la consola de Google Cloud.

    Ir a la página Administración de claves

  2. Haz clic en el nombre del llavero de claves para el que crearás la clave.

  3. Haz clic en Crear clave.

  4. En ¿Qué tipo de clave quieres crear?, elige Clave generada.

  5. Ingresa el nombre en el campo Nombre de la clave.

  6. Haz clic en el menú desplegable Nivel de protección y selecciona HSM.

  7. Haz clic en el menú desplegable Propósito y selecciona Encriptación/desencriptación simétrica.

  8. Acepta los valores predeterminados de Período de rotación y A partir del.

  9. Haz clic en el botón Agregar etiquetas.

  10. Agrega una etiqueta con la clave team y el valor alpha.

  11. Haz clic en Crear.

gcloud

Para usar Cloud KMS en la línea de comandos, primero instala o actualiza a la versión más reciente de Google Cloud CLI.

En este ejemplo, se muestra cómo crear una clave nueva y asignarle etiquetas. También puedes agregar etiquetas a una clave existente.

gcloud kms keys create key \
    --keyring key-ring \
    --location location \
    --purpose purpose \
    --labels "team=alpha,cost_center=cc1234"

Reemplaza key por un nombre para la clave. Reemplaza key-ring por el nombre del llavero de claves donde se ubicará la clave. Reemplaza location por la ubicación de Cloud KMS para el llavero de claves. Reemplaza purpose por un propósito válido para la clave. Proporciona una lista de etiquetas y valores separados por comas y comillas. Si se especifica una etiqueta varias veces con valores diferentes, cada valor nuevo reemplazará el valor anterior.

Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help.

C#

Para ejecutar este código, primero configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.


using Google.Cloud.Kms.V1;

public class CreateKeyLabelsSample
{
    public CryptoKey CreateKeyLabels(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-asymmetric-encrypt-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            }
        };

        key.Labels["team"] = "alpha";
        key.Labels["cost_center"] = "cc1234";

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return result;
    }
}

Go

Para ejecutar este código, primero configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para Cloud KMS.

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// createKeyLabels creates a new KMS key with labels.
func createKeyLabels(w io.Writer, parent, id string) error {
	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
	// id := "my-labeled-key"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.CreateCryptoKeyRequest{
		Parent:      parent,
		CryptoKeyId: id,
		CryptoKey: &kmspb.CryptoKey{
			Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT,
			VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
				Algorithm: kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,
			},

			Labels: map[string]string{
				"team":        "alpha",
				"cost_center": "cc1234",
			},
		},
	}

	// Call the API.
	result, err := client.CreateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key: %w", err)
	}
	fmt.Fprintf(w, "Created key: %s\n", result.Name)
	return nil
}

Java

Para ejecutar este código, primero configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para Cloud KMS.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import java.io.IOException;

public class CreateKeyLabels {

  public void createKeyLabels() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String id = "my-key";
    createKeyLabels(projectId, locationId, keyRingId, id);
  }

  // Create a new key with labels.
  public void createKeyLabels(String projectId, String locationId, String keyRingId, String id)
      throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project, location, and key ring.
      KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

      // Build the key to create with labels.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
              .setVersionTemplate(
                  CryptoKeyVersionTemplate.newBuilder()
                      .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
              .putLabels("team", "alpha")
              .putLabels("cost_center", "cc1234")
              .build();

      // Create the key.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created key with labels %s%n", createdKey.getName());
    }
  }
}

Node.js

Para ejecutar este código, primero configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para Cloud KMS.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const id = 'my-labeled-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);

async function createKeyLabels() {
  const [key] = await client.createCryptoKey({
    parent: keyRingName,
    cryptoKeyId: id,
    cryptoKey: {
      purpose: 'ENCRYPT_DECRYPT',
      versionTemplate: {
        algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
      },
      labels: {
        team: 'alpha',
        cost_center: 'cc1234',
      },
    },
  });

  console.log(`Created labeled key: ${key.name}`);
  return key;
}

return createKeyLabels();

PHP

Para ejecutar este código, primero obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para Cloud KMS.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;

function create_key_labels(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $id = 'my-key-with-labels'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the parent key ring name.
    $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Build the key.
    $key = (new CryptoKey())
        ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
        ->setVersionTemplate((new CryptoKeyVersionTemplate())
            ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION)
        )
        ->setLabels([
            'team' => 'alpha',
            'cost_center' => 'cc1234',
        ]);

    // Call the API.
    $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
        ->setParent($keyRingName)
        ->setCryptoKeyId($id)
        ->setCryptoKey($key);
    $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
    printf('Created labeled key: %s' . PHP_EOL, $createdKey->getName());

    return $createdKey;
}

Python

Para ejecutar este código, primero configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para Cloud KMS.


from google.cloud import kms

def create_key_labels(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Creates a new key in Cloud KMS with labels.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to create (e.g. 'my-labeled-key').

    Returns:
        CryptoKey: Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the parent key ring name.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Build the key.
    purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
    algorithm = (
        kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
    )
    key = {
        "purpose": purpose,
        "version_template": {
            "algorithm": algorithm,
        },
        "labels": {"team": "alpha", "cost_center": "cc1234"},
    }

    # Call the API.
    created_key = client.create_crypto_key(
        request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
    )
    print(f"Created labeled key: {created_key.name}")
    return created_key

Ruby

Para ejecutar este código, primero configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para Cloud KMS.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# id          = "my-key-with-labels"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Build the key.
key = {
  purpose:          :ENCRYPT_DECRYPT,
  version_template: {
    algorithm: :GOOGLE_SYMMETRIC_ENCRYPTION
  },
  labels:           {
    "team"        => "alpha",
    "cost_center" => "cc1234"
  }
}

# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created labeled key: #{created_key.name}"

API

Agrega etiquetas cuando crees una clave nueva con el método CryptoKeys.create e incluye la propiedad labels en el cuerpo de la solicitud. Por ejemplo:

{
  "purpose": "ENCRYPT_DECRYPT",
  "labels": [
    {
      "key": "team",
      "value": "alpha"
    },
    {
      "key": "cost_center",
      "value": "cc1234"
    }
  ]
}

Si proporcionas la misma clave de etiqueta dos veces, el último valor especificado anula los valores anteriores. En este ejemplo, team se configura como beta.

{
  "labels": [
    {
      "key": "team",
      "value": "alpha"
    },
    {
      "key": "team",
      "value": "beta"
    }
  ]
}

Cómo ver las etiquetas de una clave

Console

  1. Ve a la página Administración de claves en la consola de Google Cloud.

    Ir a la página Administración de claves

  2. Haz clic en el nombre del llavero de claves de la clave que quieres inspeccionar.

  3. En el encabezado, haz clic en Mostrar panel de información.

  4. En el panel, elige la pestaña Etiquetas.

gcloud

Para usar Cloud KMS en la línea de comandos, primero instala o actualiza a la versión más reciente de Google Cloud CLI.

gcloud kms keys describe key \
    --keyring key-ring \
    --location location

Reemplaza key por el nombre de la clave. Reemplaza key-ring por el nombre del llavero de claves en el que se encuentra la clave. Reemplaza location por la ubicación de Cloud KMS para el llavero de claves.

Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help.

C#

Para ejecutar este código, primero configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.


using Google.Cloud.Kms.V1;
using System;

public class GetKeyLabelsSample
{
    public CryptoKey GetKeyLabels(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // Call the API.
        CryptoKey result = client.GetCryptoKey(keyName);

        // Example of iterating over labels.
        foreach (var item in result.Labels)
        {
            String key = item.Key;
            String value = item.Value;
            // ...
        }

        // Return the ciphertext.
        return result;
    }
}

Go

Para ejecutar este código, primero configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para Cloud KMS.

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
)

// getKeyLabels fetches the labels on a KMS key.
func getKeyLabels(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.GetCryptoKeyRequest{
		Name: name,
	}

	// Call the API.
	result, err := client.GetCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get key: %w", err)
	}

	// Extract and print the labels.
	for k, v := range result.Labels {
		fmt.Fprintf(w, "%s=%s\n", k, v)
	}
	return nil
}

Java

Para ejecutar este código, primero configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para Cloud KMS.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import java.io.IOException;

public class GetKeyLabels {

  public void getKeyLabels() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    getKeyLabels(projectId, locationId, keyRingId, keyId);
  }

  // Get the labels associated with a key.
  public void getKeyLabels(String projectId, String locationId, String keyRingId, String keyId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the name from the project, location, key ring, and keyId.
      CryptoKeyName keyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Get the key.
      CryptoKey key = client.getCryptoKey(keyName);

      // Print out each label.
      key.getLabelsMap().forEach((k, v) -> System.out.printf("%s=%s%n", k, v));
    }
  }
}

Node.js

Para ejecutar este código, primero configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para Cloud KMS.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function getKeyLabels() {
  const [key] = await client.getCryptoKey({
    name: keyName,
  });

  for (const k in key.labels) {
    console.log(`${k}: ${key.labels[k]}`);
  }

  return key;
}

return getKeyLabels();

PHP

Para ejecutar este código, primero obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para Cloud KMS.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\GetCryptoKeyRequest;

function get_key_labels(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key'
) {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the key name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Call the API.
    $getCryptoKeyRequest = (new GetCryptoKeyRequest())
        ->setName($keyName);
    $key = $client->getCryptoKey($getCryptoKeyRequest);

    // Example of iterating over labels.
    foreach ($key->getLabels() as $k => $v) {
        printf('%s = %s' . PHP_EOL, $k, $v);
    }

    return $key;
}

Python

Para ejecutar este código, primero configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para Cloud KMS.

from google.cloud import kms

def get_key_labels(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Get a key and its labels.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').

    Returns:
        CryptoKey: Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    # Call the API.
    key = client.get_crypto_key(request={"name": key_name})

    # Example of iterating over labels.
    for k, v in key.labels.items():
        print(f"{k} = {v}")

    return key

Ruby

Para ejecutar este código, primero configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para Cloud KMS.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Call the API.
key = client.get_crypto_key name: key_name

# Example of iterating over labels.
key.labels.each do |k, v|
  puts "#{k} = #{v}"
end

API

En estos ejemplos, se usa curl como un cliente HTTP para demostrar el uso de la API. Para obtener más información sobre el control de acceso, consulta Accede a la API de Cloud KMS.

Para ver las etiquetas que se aplicaron a una clave, usa el método CryptoKeys.get:

curl "https://cloudkms.googleapis.com/v1/projects/project-id/locations/location/keyRings/key-ring-name/cryptoKeys/key-name" \
    --request "GET" \
    --header "authorization: Bearer token" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id"

Agregar o actualizar etiquetas

Console

  1. Ve a la página Administración de claves en la consola de Google Cloud.

    Ir a la página Administración de claves

  2. Haz clic en el nombre del llavero de claves de la clave que quieres inspeccionar.

  3. En el encabezado, haz clic en Mostrar panel de información.

  4. En el panel, elige la pestaña Etiquetas.

  5. Edita el valor de una etiqueta directamente en el campo de texto correspondiente.

  6. Para editar la clave de una etiqueta, agrega una etiqueta nueva con el nombre de clave que desees y borra la etiqueta antigua haciendo clic en Borrar junto a la etiqueta que deseas borrar.

  7. Haz clic en Guardar.

gcloud

Para usar Cloud KMS en la línea de comandos, primero instala o actualiza a la versión más reciente de Google Cloud CLI.

gcloud kms keys update key \
    --keyring key-ring \
    --location location \
    --update-labels "cost_center=cc5678"

Reemplaza key por el nombre de la clave. Reemplaza key-ring por el nombre del llavero de claves en el que se encuentra la clave. Reemplaza location por la ubicación de Cloud KMS para el llavero de claves. Para --update-labels, proporciona una lista de etiquetas entrecomilladas y separadas por comas y sus valores que se actualizarán. Si omites el valor nuevo de una etiqueta, ocurrirá lo siguiente:

Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help.

C#

Para ejecutar este código, primero configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.



using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;

public class UpdateKeyUpdateLabelsSample
{
    public CryptoKey UpdateKeyUpdateLabels(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        //
        // Step 1 - get the current set of labels on the key
        //

        // Get the current key.
        CryptoKey key = client.GetCryptoKey(keyName);

        //
        // Step 2 - add a label to the list of labels
        //

        // Add a new label
        key.Labels["new_label"] = "new_value";

        // Build the update mask.
        FieldMask fieldMask = new FieldMask
        {
            Paths = { "labels" }
        };

        // Call the API.
        CryptoKey result = client.UpdateCryptoKey(key, fieldMask);

        // Return the updated key.
        return result;
    }
}

Go

Para ejecutar este código, primero configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para Cloud KMS.

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	fieldmask "google.golang.org/genproto/protobuf/field_mask"
)

// updateKeyUpdateLabels updates an existing KMS key, adding a new label.
func updateKeyUpdateLabels(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	//
	// Step 1 - get the current set of labels on the key
	//

	// Build the request.
	getReq := &kmspb.GetCryptoKeyRequest{
		Name: name,
	}

	// Call the API.
	result, err := client.GetCryptoKey(ctx, getReq)
	if err != nil {
		return fmt.Errorf("failed to get key: %w", err)
	}

	//
	// Step 2 - add a label to the list of labels
	//

	labels := result.Labels
	labels["new_label"] = "new_value"

	// Build the request.
	updateReq := &kmspb.UpdateCryptoKeyRequest{
		CryptoKey: &kmspb.CryptoKey{
			Name:   name,
			Labels: labels,
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"labels"},
		},
	}

	// Call the API.
	result, err = client.UpdateCryptoKey(ctx, updateReq)
	if err != nil {
		return fmt.Errorf("failed to update key: %w", err)
	}

	// Print the labels.
	for k, v := range result.Labels {
		fmt.Fprintf(w, "%s=%s\n", k, v)
	}
	return nil
}

Java

Para ejecutar este código, primero configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para Cloud KMS.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class UpdateKeyUpdateLabels {

  public void updateKeyUpdateLabels() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    updateKeyUpdateLabels(projectId, locationId, keyRingId, keyId);
  }

  // Create a new key that is used for symmetric encryption and decryption.
  public void updateKeyUpdateLabels(
      String projectId, String locationId, String keyRingId, String keyId) throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project, location, and key ring.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      //
      // Step 1 - get the current set of labels on the key
      //

      // Get the current key.
      CryptoKey key = client.getCryptoKey(cryptoKeyName);

      //
      // Step 2 - add a label to the list of labels
      //

      // Add a new label.
      key = key.toBuilder().putLabels("new_label", "new_value").build();

      // Construct the field mask.
      FieldMask fieldMask = FieldMaskUtil.fromString("labels");

      // Update the key.
      CryptoKey updatedKey = client.updateCryptoKey(key, fieldMask);
      System.out.printf("Updated key %s%n", updatedKey.getName());
    }
  }
}

Node.js

Para ejecutar este código, primero configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para Cloud KMS.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';
// const versionId = '123';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function updateKeyUpdateLabels() {
  const [key] = await client.updateCryptoKey({
    cryptoKey: {
      name: keyName,
      labels: {
        new_label: 'new_value',
      },
    },
    updateMask: {
      paths: ['labels'],
    },
  });

  console.log(`Updated labels for: ${key.name}`);
  return key;
}

return updateKeyUpdateLabels();

PHP

Para ejecutar este código, primero obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para Cloud KMS.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\UpdateCryptoKeyRequest;
use Google\Protobuf\FieldMask;

function update_key_update_labels(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the key name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Build the key.
    $key = (new CryptoKey())
        ->setName($keyName)
        ->setLabels(['new_label' => 'new_value']);

    // Create the field mask.
    $updateMask = (new FieldMask())
        ->setPaths(['labels']);

    // Call the API.
    $updateCryptoKeyRequest = (new UpdateCryptoKeyRequest())
        ->setCryptoKey($key)
        ->setUpdateMask($updateMask);
    $updatedKey = $client->updateCryptoKey($updateCryptoKeyRequest);
    printf('Updated key: %s' . PHP_EOL, $updatedKey->getName());

    return $updatedKey;
}

Ruby

Para ejecutar este código, primero configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para Cloud KMS.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Build the key.
key = {
  name:   key_name,
  labels: {
    "new_label" => "new_value"
  }
}

# Build the field mask.
update_mask = { paths: ["labels"] }

# Call the API.
updated_key = client.update_crypto_key crypto_key: key, update_mask: update_mask
puts "Updated key: #{updated_key.name}"

Python

Para ejecutar este código, primero configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para Cloud KMS.

from google.cloud import kms

def update_key_update_labels(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Update labels on an existing key.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').

    Returns:
        CryptoKey: Updated Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    key = {"name": key_name, "labels": {"new_label": "new_value"}}

    # Build the update mask.
    update_mask = {"paths": ["labels"]}

    # Call the API.
    updated_key = client.update_crypto_key(
        request={"crypto_key": key, "update_mask": update_mask}
    )
    print(f"Updated key: {updated_key.name}")
    return updated_key

API

En estos ejemplos, se usa curl como un cliente HTTP para demostrar el uso de la API. Para obtener más información sobre el control de acceso, consulta Accede a la API de Cloud KMS.

Para agregar o actualizar etiquetas de una clave existente, usa el método CryptoKeys.patch y agrega la propiedad labels en el cuerpo de la solicitud. Por ejemplo:

{
  "labels": [
    {
      "key": "team",
      "value": "alpha"
    },
    {
      "key": "cost_center",
      "value": "cc5678"
    }
  ]
}

Instrucciones para quitar las etiquetas

Console

  1. Ve a la página Administración de claves en la consola de Google Cloud.

    Ir a la página Administración de claves

  2. Haz clic en el nombre del llavero de claves de la clave que quieres inspeccionar.

  3. En el encabezado, haz clic en Mostrar panel de información.

  4. En el panel, elige la pestaña Etiquetas.

  5. Haz clic en el ícono Borrar junto a las etiquetas que deseas borrar.

  6. Haz clic en Guardar.

gcloud

Para usar Cloud KMS en la línea de comandos, primero instala o actualiza a la versión más reciente de Google Cloud CLI.

gcloud kms keys update key \
    --keyring key-ring \
    --location location \
    --remove-labels "team,cost_center"

Reemplaza key por el nombre de la clave. Reemplaza key-ring por el nombre del llavero de claves en el que se encuentra la clave. Reemplaza location por la ubicación de Cloud KMS para el llavero de claves. Para --remove-labels, proporciona una lista de etiquetas que se deben quitar, entrecomilladas y separadas por comas. No proporciones valores para las etiquetas.

Para obtener información sobre todas las marcas y los valores posibles, ejecuta el comando con la marca --help.

C#

Para ejecutar este código, primero configura un entorno de desarrollo de C# e instala el SDK de C# para Cloud KMS.


using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;

public class UpdateKeyRemoveLabelsSample
{
    public CryptoKey UpdateKeyRemoveLabels(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            CryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId),
        };

        // Build the update mask.
        FieldMask fieldMask = new FieldMask
        {
            Paths = { "labels" },
        };

        // Call the API.
        CryptoKey result = client.UpdateCryptoKey(key, fieldMask);

        // Return the updated key.
        return result;
    }
}

Go

Para ejecutar este código, primero configura un entorno de desarrollo de Go y, luego, instala el SDK de Go para Cloud KMS.

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
	"cloud.google.com/go/kms/apiv1/kmspb"
	fieldmask "google.golang.org/genproto/protobuf/field_mask"
)

// updateKeyRemoveLabels removes all labels from an existing Cloud KMS key.
func updateKeyRemoveLabels(w io.Writer, name string) error {
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.UpdateCryptoKeyRequest{
		CryptoKey: &kmspb.CryptoKey{
			Name:   name,
			Labels: nil,
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"labels"},
		},
	}

	// Call the API.
	result, err := client.UpdateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update key: %w", err)
	}
	fmt.Fprintf(w, "Updated key: %s\n", result.Name)
	return nil
}

Java

Para ejecutar este código, primero configura un entorno de desarrollo de Java y, luego, instala el SDK de Java para Cloud KMS.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class UpdateKeyRemoveLabels {

  public void updateKeyRemoveLabels() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    updateKeyRemoveLabels(projectId, locationId, keyRingId, keyId);
  }

  // Update a key to remove all labels.
  public void updateKeyRemoveLabels(
      String projectId, String locationId, String keyRingId, String keyId) throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the name from the project, location, key ring, and keyId.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Build an empty key with no labels.
      CryptoKey key = CryptoKey.newBuilder().setName(cryptoKeyName.toString()).build();

      // Construct the field mask.
      FieldMask fieldMask = FieldMaskUtil.fromString("labels");

      // Create the key.
      CryptoKey createdKey = client.updateCryptoKey(key, fieldMask);
      System.out.printf("Updated key %s%n", createdKey.getName());
    }
  }
}

Node.js

Para ejecutar este código, primero configura un entorno de desarrollo de Node.js y, luego, instala el SDK de Node.js para Cloud KMS.

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';
// const versionId = '123';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function updateKeyRemoveLabels() {
  const [key] = await client.updateCryptoKey({
    cryptoKey: {
      name: keyName,
      labels: null,
    },
    updateMask: {
      paths: ['labels'],
    },
  });

  console.log(`Removed labels from: ${key.name}`);
  return key;
}

return updateKeyRemoveLabels();

PHP

Para ejecutar este código, primero obtén información sobre cómo usar PHP en Google Cloud y, luego, instala el SDK de PHP para Cloud KMS.

use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\UpdateCryptoKeyRequest;
use Google\Protobuf\FieldMask;

function update_key_remove_labels(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key'
): CryptoKey {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the key name.
    $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // Build the key.
    $key = (new CryptoKey())
        ->setName($keyName)
        ->setLabels([]);

    // Create the field mask.
    $updateMask = (new FieldMask())
        ->setPaths(['labels']);

    // Call the API.
    $updateCryptoKeyRequest = (new UpdateCryptoKeyRequest())
        ->setCryptoKey($key)
        ->setUpdateMask($updateMask);
    $updatedKey = $client->updateCryptoKey($updateCryptoKeyRequest);
    printf('Updated key: %s' . PHP_EOL, $updatedKey->getName());

    return $updatedKey;
}

Python

Para ejecutar este código, primero configura un entorno de desarrollo de Python y, luego, instala el SDK de Python para Cloud KMS.

from google.cloud import kms

def update_key_remove_labels(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
    """
    Remove labels from an existing key.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').

    Returns:
        CryptoKey: Updated Cloud KMS key.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key name.
    key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    key = {
        "name": key_name,
        "labels": [],
    }

    # Build the update mask.
    update_mask = {"paths": ["labels"]}

    # Call the API.
    updated_key = client.update_crypto_key(
        request={"crypto_key": key, "update_mask": update_mask}
    )
    print(f"Updated key: {updated_key.name}")
    return updated_key

Ruby

Para ejecutar este código, primero configura un entorno de desarrollo de Ruby y, luego, instala el SDK de Ruby para Cloud KMS.

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the parent key name.
key_name = client.crypto_key_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Build the key.
key = {
  name:   key_name,
  labels: {}
}

# Build the field mask.
update_mask = { paths: ["labels"] }

# Call the API.
updated_key = client.update_crypto_key crypto_key: key, update_mask: update_mask
puts "Updated key: #{updated_key.name}"

API

En estos ejemplos, se usa curl como un cliente HTTP para demostrar el uso de la API. Para obtener más información sobre el control de acceso, consulta Accede a la API de Cloud KMS.

Para quitar etiquetas de una clave existente, usa el método CryptoKeys.patch y agrega la propiedad labels como un arreglo vacío en el cuerpo de tu solicitud. Por ejemplo:

{
  "labels": []
}

Registro de auditoría

Los registros de auditoría de Cloud para Cloud KMS se pueden usar para registrar información de etiquetas cuando se crean o actualizan las claves. Tanto la creación como la actualización de claves son actividades de administrador, por lo que estos cambios se anotan en el registro de actividades del administrador.