키 라벨 지정

Cloud Key Management Service는 Cloud KMS 키에 라벨을 추가하는 옵션을 제공합니다. 라벨은 관련성이 높은 Cloud KMS 키를 그룹화하고 Cloud KMS 키에 대한 메타데이터를 저장하는 데 사용할 수 있는 키-값 쌍입니다.

라벨이 청구서에 포함되므로 라벨에 따른 비용 분포를 확인할 수 있습니다.

Google Cloud CLI 및 Cloud KMS REST API를 사용하여 키 라벨을 추가, 업데이트, 삭제할 수 있습니다.

라벨은 가상 머신 리소스, 스토리지 버킷 같은 다른 Google Cloud 리소스와 함께 사용할 수 있습니다. Google Cloud에서 라벨을 사용하는 방법에 대한 자세한 내용은 라벨 만들기 및 관리를 참조하세요.

라벨이란 무엇인가요?

라벨은 Google Cloud KMS 키에 할당할 수 있는 키-값 쌍입니다. 이러한 리소스를 구성하고 필요한 세부사항으로 규모에 맞게 비용을 관리하는 데 도움이 됩니다. 각 리소스에 라벨을 연결한 후 이 라벨을 기준으로 리소스를 필터링할 수 있습니다. 라벨에 대한 정보는 청구 요금을 라벨별로 분류할 수 있는 결제 시스템으로 전달됩니다. 기본 제공되는 결제 보고서를 통해 리소스 라벨별로 비용을 필터링하고 그룹화할 수 있습니다. 라벨을 사용하여 결제 데이터 내보내기를 쿼리할 수도 있습니다.

라벨 요구사항

리소스에 적용된 라벨은 다음 요구사항을 충족해야 합니다.

  • 각 리소스에 라벨을 최대 64개까지 사용할 수 있습니다.
  • 각 라벨은 키-값 쌍이어야 합니다.
  • 키는 비워 둘 수 없으며 최소 길이는 1자(영문 기준)이고 최대 길이는 63자(영문 기준)입니다. 값은 비워 둘 수 있으며 최대 길이는 63자(영문 기준)입니다.
  • 키와 값에는 소문자, 숫자, 밑줄, 대시만 사용할 수 있습니다. 모든 문자는 UTF-8 인코딩을 사용해야 하며 국제 문자가 허용됩니다. 키는 소문자나 국제 문자로 시작해야 합니다.
  • 라벨의 키 부분은 단일 리소스에서 고유해야 합니다. 그러나 여러 리소스에 같은 키를 사용할 수 있습니다.

이러한 한도는 각 라벨의 키와 값 및 라벨이 있는 개별 Google Cloud 리소스에 적용됩니다. 한 프로젝트의 모든 리소스에 적용할 수 있는 라벨 수에는 제한이 없습니다.

라벨의 일반적인 사용 사례

다음은 라벨의 몇 가지 일반적인 사용 사례입니다.

  • 팀 또는 비용 센터 라벨: 팀 또는 비용 센터를 기준으로 라벨을 추가하여 다른 팀(예: team:researchteam:analytics)에서 소유한 Cloud KMS 키를 구분할 수 있습니다. 비용 계산이나 예산 책정에 이 유형의 라벨을 사용할 수 있습니다.

  • 구성요소 라벨: component:redis, component:frontend, component:ingest, component:dashboard를 예로 들 수 있습니다.

  • 환경 또는 단계 라벨: environment:productionenvironment:test를 예로 들 수 있습니다.

  • 상태 라벨: state:active , state:readytodelete, state:archive를 예로 들 수 있습니다.

  • 소유권 라벨: 작업을 담당하는 팀을 식별하는 데 사용됩니다(예: team:shopping-cart).

모든 API 호출의 타임스탬프 또는 개별 값과 같은 대량의 고유 라벨은 만들지 않는 것이 좋습니다. 이 접근 방식의 문제는 값이 자주 변경되거나 카탈로그를 복잡하게 하는 키로 인해 리소스를 효과적으로 필터링하고 보고하기 어렵다는 것입니다.

라벨 및 태그

라벨은 리소스에 대해 쿼리 가능한 주석으로 사용될 수 있지만 정책에 조건을 설정하는 데는 사용할 수 없습니다. 태그를 사용하면 정책을 세밀하게 제어하여 리소스에 특정 태그가 있는지 여부에 따라 정책을 조건부로 허용하거나 거부할 수 있습니다. 자세한 내용은 태그 개요를 참조하세요.

라벨이 있는 키 만들기

키를 만들 때 하나 이상의 키 값 쌍을 라벨로 제공하여 라벨을 추가할 수 있습니다.

콘솔

  1. Google Cloud 콘솔에서 키 관리 페이지로 이동합니다.

    키 관리 페이지로 이동

  2. 키를 만들 키링의 이름을 클릭합니다.

  3. 키 만들기를 클릭합니다.

  4. 어떤 유형의 키를 만드시겠어요?에서 생성된 키를 선택합니다.

  5. 키 이름 필드에 키 이름을 입력합니다.

  6. 보호 수준 드롭다운을 클릭하고 HSM을 선택합니다.

  7. 용도 드롭다운을 클릭하고 대칭 암호화/복호화를 선택합니다.

  8. 순환 주기시작일의 기본값을 그대로 사용합니다.

  9. 라벨 추가 버튼을 클릭합니다.

  10. team 키와 alpha 값으로 라벨을 추가합니다.

  11. 만들기를 클릭합니다.

gcloud

명령줄에서 Cloud KMS를 사용하려면 먼저 최신 버전의 Google Cloud CLI로 설치 또는 업그레이드하세요.

이 예시에서는 새 키를 만들고 키에 라벨을 할당하는 방법을 보여줍니다. 기존 키에 라벨을 추가할 수도 있습니다.

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

key를 키 이름으로 바꿉니다. key-ring을 키를 배치할 키링의 이름으로 바꿉니다. location을 키링의 Cloud KMS 위치로 바꿉니다. purpose를 키에 유효한 용도로 바꿉니다. 따옴표로 묶고, 쉼표로 구분한 라벨 및 값 목록을 제공합니다. 다른 값을 사용해서 라벨을 여러 번 지정한 경우, 항상 새 값이 이전 값을 덮어씁니다.

모든 플래그 및 가능한 값에 대한 정보를 보려면 --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

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 Cloud KMS 자바 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\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
use Google\Cloud\Kms\V1\KeyManagementServiceClient;

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.
    $createdKey = $client->createCryptoKey($keyRingName, $id, $key);
    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": "team",
      "value": "alpha"
    },
    {
      "key": "cost_center",
      "value": "cc1234"
    }
  ]
}

동일한 라벨 키를 두 번 입력하면 마지막으로 지정된 값이 이전 값을 재정의합니다. 이 예시에서 teambeta로 설정됩니다.

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

키의 라벨 보기

콘솔

  1. Google Cloud 콘솔에서 키 관리 페이지로 이동합니다.

    키 관리 페이지로 이동

  2. 검사하려는 키의 키링 이름을 클릭합니다.

  3. 헤더에서 정보 패널 표시를 클릭합니다.

  4. 패널에서 라벨 탭을 선택합니다.

gcloud

명령줄에서 Cloud KMS를 사용하려면 먼저 최신 버전의 Google Cloud CLI로 설치 또는 업그레이드하세요.

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

key를 키 이름으로 바꿉니다. key-ring을 키가 배치된 키링의 이름으로 바꿉니다. location을 키링의 Cloud KMS 위치로 바꿉니다.

모든 플래그 및 가능한 값에 대한 정보를 보려면 --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

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 Cloud KMS 자바 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\KeyManagementServiceClient;

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.
    $key = $client->getCryptoKey($keyName);

    // 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-name/cryptoKeys/key-name" \
    --request "GET" \
    --header "authorization: Bearer token" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id"

라벨 추가 또는 업데이트

콘솔

  1. Google Cloud 콘솔에서 키 관리 페이지로 이동합니다.

    키 관리 페이지로 이동

  2. 검사하려는 키의 키링 이름을 클릭합니다.

  3. 헤더에서 정보 패널 표시를 클릭합니다.

  4. 패널에서 라벨 탭을 선택합니다.

  5. 해당 텍스트 필드에서 직접 라벨 값을 수정합니다.

  6. 원하는 키 이름으로 새 라벨을 추가하여 라벨의 키를 수정하고 삭제하려는 라벨 옆에 있는 삭제를 클릭하여 오래된 라벨을 삭제합니다.

  7. 저장을 클릭합니다.

gcloud

명령줄에서 Cloud KMS를 사용하려면 먼저 최신 버전의 Google Cloud CLI로 설치 또는 업그레이드하세요.

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

key를 키 이름으로 바꿉니다. key-ring을 키가 배치된 키링의 이름으로 바꿉니다. location을 키링의 Cloud KMS 위치로 바꿉니다. --update-labels의 경우, 따옴표로 묶고, 쉼표로 구분한 업데이트할 라벨 및 해당 값 목록을 제공합니다. 라벨의 새 값을 생략하면 발생합니다.

모든 플래그 및 가능한 값에 대한 정보를 보려면 --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

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 Cloud KMS 자바 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\CryptoKey;
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
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.
    $updatedKey = $client->updateCryptoKey($key, $updateMask);
    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": "team",
      "value": "alpha"
    },
    {
      "key": "cost_center",
      "value": "cc5678"
    }
  ]
}

라벨 삭제

콘솔

  1. Google Cloud 콘솔에서 키 관리 페이지로 이동합니다.

    키 관리 페이지로 이동

  2. 검사하려는 키의 키링 이름을 클릭합니다.

  3. 헤더에서 정보 패널 표시를 클릭합니다.

  4. 패널에서 라벨 탭을 선택합니다.

  5. 삭제하려는 라벨 옆에 있는 삭제 아이콘을 클릭합니다.

  6. 저장을 클릭합니다.

gcloud

명령줄에서 Cloud KMS를 사용하려면 먼저 최신 버전의 Google Cloud CLI로 설치 또는 업그레이드하세요.

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

key를 키 이름으로 바꿉니다. key-ring을 키가 배치된 키링의 이름으로 바꿉니다. location을 키링의 Cloud KMS 위치로 바꿉니다. --remove-labels의 경우 따옴표로 묶고, 쉼표로 구분한 삭제할 라벨 목록을 제공합니다. 라벨에 값을 제공하지 마세요.

모든 플래그 및 가능한 값에 대한 정보를 보려면 --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

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 Cloud KMS 자바 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\CryptoKey;
use Google\Cloud\Kms\V1\KeyManagementServiceClient;
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.
    $updatedKey = $client->updateCryptoKey($key, $updateMask);
    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 감사 로그는 키를 생성하거나 업데이트할 때 라벨 정보를 로깅하는 데 사용할 수 있습니다. 키 생성 및 업데이트는 모두 관리자 활동이며, 라벨 변경사항은 관리자 활동 로그에 기록됩니다.