為金鑰加上標籤

Cloud Key Management Service 提供為 Cloud KMS 金鑰新增標籤的選項。標籤為鍵/值組合,可用於將相關的 Cloud KMS 金鑰分組,並儲存 Cloud KMS 金鑰的中繼資料。

標籤會在帳單中顯示,方便您瞭解每個標籤的成本分布情形。

您可以使用 Google Cloud CLI 和 Cloud KMS REST API 新增、更新及移除金鑰標籤。

您可以將標籤與其他 Google Cloud 資源搭配使用,例如虛擬機器資源儲存空間值區。如要進一步瞭解如何在 Google Cloud中使用標籤,請參閱「建立及管理標籤」一文。

什麼是標籤?

標籤是鍵/值組合,可指派給 Google Cloud Cloud KMS 金鑰。這些標籤可協助您整理這些資源,並以所需精細度大規模管理費用。您可以為每項資源加上標籤,並根據標籤篩選資源。標籤的相關資訊會轉送至帳單系統,方便您依據標籤查看帳單費用明細。您可以使用內建的帳單報表,依資源標籤篩選及分組費用。您也可以使用標籤查詢帳單資料匯出內容

標籤需求

套用於資源的標籤必須符合下列需求條件:

  • 每項資源最多可有 64 個標籤。
  • 每個標籤都必須是鍵/值組合。
  • 鍵的長度必須至少為 1 個字元,最多 63 個字元,且不能空白。值可以空白,長度上限為 63 個字元。
  • 鍵和值只能使用小寫字母、數字字元、底線和連字號。所有字元都必須使用 UTF-8 編碼,且可使用國際字元。鍵的開頭必須是小寫字母或國際字元。
  • 標籤中的鍵部分不得重複。但可讓多個資源使用相同的鍵。

這些限制適用於每個標籤的鍵和值,以及具有標籤的個別 Google Cloud 資源。您可以在專案內的所有資源中套用任意數量的標籤。

標籤的常見用法

以下是一些常見的標籤用途:

  • 團隊或成本中心標籤:依據團隊或成本中心來新增標籤,藉此區別不同團隊 (例如 team:researchteam:analytics) 擁有的 Cloud KMS 金鑰。這個類型的標籤可用於成本會計或預算編列作業。

  • 元件標籤:例如 component:rediscomponent:frontendcomponent:ingestcomponent:dashboard

  • 環境或階段標籤:例如 environment:productionenvironment:test

  • 狀態標籤:例如 state:activestate:readytodeletestate:archive

  • 擁有權標籤:用於識別負責作業的團隊,例如 team:shopping-cart

我們不建議您建立大量的不重複標籤,例如為時間戳記或每個 API 呼叫的個別值建立標籤。這種做法的問題是,如果值經常變更,或鍵會使目錄變得雜亂,就很難有效篩選及回報資源。

標籤

標籤可用於資源的可查詢註解,但無法用於設定政策條件。您可將資源是否具備特定標記設為條件,並按照這項條件允許或拒絕政策。詳情請參閱「標記總覽」。

建立具有標籤的金鑰

建立金鑰時,您可以提供一或多個鍵/值組合做為標籤來為金鑰加上標籤。

控制台

  1. 前往 Google Cloud 控制台的「Key Management」頁面。

    前往「金鑰管理」

  2. 找出您要在哪個金鑰環中建立金鑰,然後按一下該金鑰環名稱。

  3. 按一下 [Create key] (建立金鑰)

  4. 在「Key name」中輸入金鑰的名稱。

  5. 根據您的需求設定鍵。

  6. 按一下「其他設定」

  7. 針對要新增的每個標籤,按一下「Add label」,然後輸入「Key」和「Value」

  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# 開發環境,然後安裝 Cloud KMS C# SDK


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

如要執行這段程式碼,請先瞭解如何在 Google Cloud上使用 PHP,並安裝 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. 前往 Google Cloud 控制台的「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# 開發環境,然後安裝 Cloud KMS C# SDK


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

如要執行這段程式碼,請先瞭解如何在 Google Cloud上使用 PHP,並安裝 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」。

如要查看套用至金鑰的標籤,請使用 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:包含金鑰環的專案 ID。
  • KEY_NAME:您要查看標籤的鍵名稱。
  • KEY_RING:金鑰所屬金鑰環的名稱。
  • LOCATION:金鑰環的位置。

新增或更新標籤

控制台

  1. 前往 Google Cloud 控制台的「Key Management」頁面。

    前往「金鑰管理」

  2. 按一下要檢查的金鑰所屬的金鑰環名稱。

  3. 按一下頁首中的「顯示資訊面板」

  4. 在面板中,選擇「標籤」分頁標籤。

  5. 直接在對應的文字欄位中編輯標籤值。

  6. 如要編輯標籤的鍵,請新增一個含有所需鍵名稱的新標籤,然後按一下要刪除的標籤旁的「刪除」圖示

  7. 按一下 [儲存]

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# 開發環境,然後安裝 Cloud KMS C# SDK



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

如要執行這段程式碼,請先瞭解如何在 Google Cloud上使用 PHP,並安裝 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. 前往 Google Cloud 控制台的「Key Management」頁面。

    前往「金鑰管理」

  2. 按一下要檢查的金鑰所屬的金鑰環名稱。

  3. 按一下頁首中的「顯示資訊面板」

  4. 在面板中,選擇「標籤」分頁標籤。

  5. 找出要刪除的標籤,然後按一下旁邊的「刪除」 圖示。

  6. 按一下 [儲存]

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# 開發環境,然後安裝 Cloud KMS C# SDK


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

如要執行這段程式碼,請先瞭解如何在 Google Cloud上使用 PHP,並安裝 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 KMS 的 Cloud 稽核記錄來記錄標籤資訊。金鑰建立與更新均為管理員活動,而對標籤的變更會記錄在管理員活動記錄中。