תוויות

שירות Cloud Key Management מספק אפשרות להוסיף תוויות למפתחות Cloud KMS. תוויות הן צמדי מפתח/ערך שבהם אפשר להשתמש כדי לקבץ מפתחות קשורים של Cloud KMS ולאחסן מטא-נתונים לגבי מפתח Cloud KMS.

התוויות נכללות בחיוב, כך שאפשר לראות את חלוקת העלויות לפי התוויות.

אפשר להוסיף, לעדכן ולהסיר תוויות של מפתחות באמצעות Google Cloud CLI ו-Cloud KMS API בארכיטקטורת REST.

אפשר להשתמש בתוויות עם משאבים אחרים של Cloud de Confiance by S3NS Google Cloud, כמו משאבי מכונות וירטואליות וקטגוריות אחסון. מידע נוסף על השימוש בתוויות ב- Cloud de Confianceזמין במאמר יצירה וניהול של תוויות.

מהן תוויות?

תווית היא צמד מפתח/ערך שאפשר להקצות ל Cloud de Confiance by S3NS מפתחות Cloud KMS. Cloud de Confiance by S3NS התוויות עוזרות לארגן את המשאבים האלה ולנהל את העלויות בהיקף גדול, ברמת הפירוט שאתם צריכים. אתם יכולים לצרף תווית לכל משאב ואז לסנן את המשאבים לפי התוויות שלהם. המידע על התוויות מועבר למערכת החיוב, שמאפשרת לכם לפרק את החיובים לפי תוויות. בעזרת דוחות חיוב מובנים, אתם יכולים לסנן ולקבץ את העלויות לפי תוויות משאבים.

הדרישות לגבי תוויות

התוויות שמוחלות על משאב צריכות לעמוד בדרישות הבאות:

  • אפשר להוסיף עד 64 תוויות לכל משאב.
  • כל תווית צריכה להיות צמד מפתח/ערך.
  • האורך המינימלי של מפתחות הוא תו אחד, והאורך המקסימלי הוא 63 תווים. המפתחות לא יכולים להיות ריקים. הערכים יכולים להיות ריקים, והאורך המקסימלי שלהם הוא 63 תווים.
  • המפתחות והערכים יכולים להכיל רק אותיות קטנות, ספרות, קווים תחתונים ומקפים. כל התווים צריכים להיות בקידוד UTF-8, ומותר להשתמש בתווים בינלאומיים. המפתחות צריכים להתחיל באות קטנה או בתו בינלאומי.
  • החלק של המפתח בתווית חייב להיות ייחודי בתוך משאב יחיד. עם זאת, אפשר להשתמש באותו מפתח עם כמה משאבים.

המגבלות האלה חלות על המפתח והערך של כל תווית, ועל כל אחד מ Cloud de Confiance המשאבים שיש להם תוויות. אין מגבלה על מספר התוויות שאפשר להחיל על כל המשאבים בפרויקט.

שימושים נפוצים בתוויות

ריכזנו כאן כמה תרחישי שימוש נפוצים בתוויות:

  • תוויות של צוות או מרכז עלויות: מוסיפים תוויות שמבוססות על צוות או על מרכז עלויות כדי להבחין בין מפתחות Cloud KMS שנמצאים בבעלות של צוותים שונים (לדוגמה, team:research ו-team:analytics). אפשר להשתמש בסוג הזה של תוויות לצורך הנהלת חשבונות או תקצוב.

  • תוויות רכיבים: לדוגמה, component:redis,‏ component:frontend,‏ component:ingest ו-component:dashboard.

  • תוויות של סביבה או שלב: לדוגמה, environment:production ו-environment:test.

  • תוויות של מדינות: לדוגמה, state:active,‏ state:readytodelete ו-state:archive.

  • תוויות בעלות: משמשות לזיהוי הצוותים שאחראים על הפעולות, לדוגמה: team:shopping-cart.

אנחנו לא ממליצים ליצור מספרים גדולים של תוויות ייחודיות, למשל עבור חותמות זמן או ערכים נפרדים לכל קריאה ל-API. הבעיה בגישה הזו היא שאם הערכים משתנים לעיתים קרובות או עם מפתחות שמכבידים על הקטלוג, קשה לסנן את המשאבים ולדווח עליהם בצורה יעילה.

תוויות ותגים

אפשר להשתמש בתוויות כהערות שאפשר להריץ עליהן שאילתות לגבי משאבים, אבל אי אפשר להשתמש בהן כדי להגדיר תנאים לכללי מדיניות. תגים מאפשרים להגדיר תנאי לאישור או לדחייה של כללי מדיניות אם תג ספציפי מצורף או לא מצורף למשאב, וכך מספקים שליטה פרטנית בכללי המדיניות. למידע נוסף, אפשר לעיין בסקירה הכללית על תגים.

יצירת מפתח עם תוויות

כשיוצרים מפתח, אפשר להוסיף תוויות על ידי ציון צמד אחד או יותר של מפתח/ערך כתוויות כשיוצרים את המפתח.

המסוף

  1. נכנסים לדף Key Management במסוף Cloud de Confiance .

    כניסה אל Key Management

  2. לוחצים על השם של אוסף המפתחות שרוצים ליצור לו מפתח.

  3. לוחצים על Create key.

  4. בשדה Key name (שם המפתח), מזינים שם למפתח.

  5. מגדירים את המפתח לפי הצרכים שלכם.

  6. לוחצים על הגדרות נוספות.

  7. לכל תווית שרוצים להוסיף, לוחצים על הוספת תווית ואז מזינים את המפתח ואת הערך.

  8. לוחצים על יצירה.

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

בדוגמה הזו מוצג איך ליצור מפתח חדש ולהקצות לו תוויות. אפשר גם להוסיף תוויות למפתח קיים.

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose PURPOSE \
    --labels "LABEL_LIST"

מחליפים את מה שכתוב בשדות הבאים:

  • KEY_NAME: השם של המפתח.
  • KEY_RING: מחזיק המפתחות שבו רוצים ליצור את המפתח.
  • LOCATION: המיקום של אוסף המפתחות, לדוגמה global.
  • PURPOSE: ייעוד המפתח, לדוגמה encryption.
  • LABEL_LIST: רשימה מופרדת בפסיקים של זוגות של מפתח/ערך, כאשר כל זוג מעוצב כ-LABEL_KEY=LABEL_VALUE. לדוגמה: env=prod,team=research. אפשר להשתמש בכל מפתח תווית רק פעם אחת במפתח של Cloud Key Management Service. אם מפתח תווית מצוין כמה פעמים עם ערכים שונים, כל ערך חדש מחליף את הערך הקודם.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

C#

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את ה-SDK של Cloud KMS C# ‎.


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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Cloud KMS Go SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Cloud KMS Java SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Cloud KMS Node.js SDK.

//
// 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

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב- Cloud de Confiance ולהתקין את Cloud KMS PHP SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Cloud KMS Python SDK.


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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Ruby ולהתקין את Cloud KMS Ruby SDK.

# 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

כדי להוסיף תוויות כשיוצרים מפתח חדש, משתמשים בשיטה CryptoKeys.create וכוללים את המאפיין labels בגוף הבקשה. לדוגמה:

{
  "purpose": "ENCRYPT_DECRYPT",
  "labels": [
    {
      "key": "LABEL_KEY",
      "value": "LABEL_VALUE"
    }
  ]
}

מחליפים את מה שכתוב בשדות הבאים:

  • LABEL_KEY: המפתח של התווית, לדוגמה env.
  • LABEL_VALUE: הערך של התווית – לדוגמה, prod.

אפשר להוסיף כמה מפתחות של תוויות, כל אחד עם ערך משלו. אפשר להשתמש בכל מפתח תווית רק פעם אחת במפתח של Cloud Key Management Service. אם מציינים מפתח של תווית כמה פעמים עם ערכים שונים, כל ערך חדש מחליף את הערך הקודם.

הצגת תוויות במקש

המסוף

  1. נכנסים לדף Key Management במסוף Cloud de Confiance .

    כניסה אל Key Management

  2. לוחצים על השם של אוסף המפתחות של המפתח שרוצים לבדוק.

  3. בכותרת, לוחצים על הצגת חלונית המידע.

  4. בחלונית, בוחרים בכרטיסייה תוויות.

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

gcloud kms keys describe KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION

מחליפים את מה שכתוב בשדות הבאים:

  • KEY_NAME: השם של המפתח שרוצים להציג את התוויות שלו.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום של אוסף המפתחות.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

C#

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את ה-SDK של Cloud KMS C# ‎.


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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Cloud KMS Go SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Cloud KMS Java SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Cloud KMS Node.js SDK.

//
// 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

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב- Cloud de Confiance ולהתקין את Cloud KMS PHP SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Cloud KMS Python SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Ruby ולהתקין את Cloud KMS Ruby SDK.

# 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

בדוגמאות האלה נעשה שימוש ב-curl כלקוח HTTP כדי להדגים את השימוש ב-API. מידע נוסף על בקרת גישה זמין במאמר גישה ל-Cloud KMS API.

כדי לראות את התוויות שחלות על המפתח, משתמשים ב-method‏ CryptoKeys.get:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME" \
    --request "GET" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: PROJECT_ID"

מחליפים את מה שכתוב בשדות הבאים:

  • PROJECT_ID: מזהה הפרויקט שמכיל את מחזיק המפתחות.
  • KEY_NAME: השם של המפתח שרוצים להציג את התוויות שלו.
  • KEY_RING: השם של אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום של אוסף המפתחות.

הוספה או עדכון של תוויות

המסוף

  1. נכנסים לדף Key Management במסוף Cloud de Confiance .

    כניסה אל Key Management

  2. לוחצים על השם של אוסף המפתחות של המפתח שרוצים לבדוק.

  3. בכותרת, לוחצים על הצגת חלונית המידע.

  4. בחלונית, בוחרים בכרטיסייה תוויות.

  5. עורכים את הערך של התווית ישירות בשדה הטקסט המתאים.

  6. כדי לערוך את המפתח של תווית, מוסיפים תווית חדשה עם שם המפתח הרצוי ומוחקים את התווית הישנה על ידי לחיצה על מחיקה לצד התווית שרוצים למחוק.

  7. לוחצים על Save.

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

gcloud kms keys update KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --update-labels "LABEL_LIST"
  • KEY_NAME: השם של המפתח.
  • KEY_RING: אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום של אוסף המפתחות.
  • LABEL_LIST: רשימה מופרדת בפסיקים של זוגות של מפתח/ערך, כאשר כל זוג מעוצב כ-LABEL_KEY=LABEL_VALUE. לדוגמה: env=prod,team=research. אפשר להשתמש בכל מפתח תווית רק פעם אחת במפתח של Cloud Key Management Service. אם מציינים מפתח של תווית כמה פעמים עם ערכים שונים, כל ערך חדש מחליף את הערך הקודם.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

C#

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את ה-SDK של Cloud KMS C# ‎.



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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Cloud KMS Go SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Cloud KMS Java SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Cloud KMS Node.js SDK.

//
// 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

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב- Cloud de Confiance ולהתקין את Cloud KMS PHP SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Ruby ולהתקין את Cloud KMS Ruby SDK.

# 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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Cloud KMS Python SDK.

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

בדוגמאות האלה נעשה שימוש ב-curl כלקוח HTTP כדי להדגים את השימוש ב-API. מידע נוסף על בקרת גישה זמין במאמר גישה ל-Cloud KMS API.

כדי להוסיף או לעדכן תוויות במפתח קיים, משתמשים בשיטה CryptoKeys.patch וכוללים את המאפיין labels בגוף הבקשה. לדוגמה:

{
  "labels": [
    {
      "key": "LABEL_KEY",
      "value": "LABEL_VALUE"
    }
  ]
}

מסיר את התוויות

המסוף

  1. נכנסים לדף Key Management במסוף Cloud de Confiance .

    כניסה אל Key Management

  2. לוחצים על השם של אוסף המפתחות של המפתח שרוצים לבדוק.

  3. בכותרת, לוחצים על הצגת חלונית המידע.

  4. בחלונית, בוחרים בכרטיסייה תוויות.

  5. לוחצים על סמל המחיקה לצד התוויות שרוצים למחוק.

  6. לוחצים על Save.

gcloud

כדי להשתמש ב-Cloud KMS בשורת הפקודה, קודם צריך להתקין את הגרסה האחרונה של Google Cloud CLI או לשדרג אליה.

gcloud kms keys update KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --remove-labels "LABEL_KEYS"
  • KEY_NAME: השם של המפתח.
  • KEY_RING: אוסף המפתחות שמכיל את המפתח.
  • LOCATION: המיקום של אוסף המפתחות.
  • LABEL_LIST: רשימה מופרדת בפסיקים של מפתחות תוויות שרוצים להסיר מהמפתח, לדוגמה, env,team.

כדי לקבל מידע על כל הדגלים והערכים האפשריים, מריצים את הפקודה עם הדגל --help.

C#

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת C# ‎ ולהתקין את ה-SDK של Cloud KMS C# ‎.


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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Go ולהתקין את Cloud KMS Go SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Cloud KMS Java SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Cloud KMS Node.js SDK.

//
// 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

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב- Cloud de Confiance ולהתקין את Cloud KMS PHP SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Python ולהתקין את Cloud KMS Python SDK.

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

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Ruby ולהתקין את Cloud KMS Ruby SDK.

# 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

בדוגמאות האלה נעשה שימוש ב-curl כלקוח HTTP כדי להדגים את השימוש ב-API. מידע נוסף על בקרת גישה זמין במאמר גישה ל-Cloud KMS API.

כדי להסיר תוויות ממפתח קיים, משתמשים בשיטה CryptoKeys.patch וכוללים את המאפיין labels כמערך ריק בגוף הבקשה. לדוגמה:

{
  "labels": []
}

רישום ביומן ביקורת

אפשר להשתמש ביומני הביקורת של Cloud עבור Cloud KMS כדי לרשום מידע על תוויות כשמפתחות נוצרים או מתעדכנים. יצירה ועדכון של מפתחות הן פעולות אדמין, ושינויים בתוויות מצוינים ביומן פעילות האדמין.