為密鑰版本指派別名

您可以為密鑰版本指派別名,方便存取。指派別名後,您可以使用別名存取密鑰版本,就像使用版本號碼存取密鑰版本一樣。

必要的角色

如要取得為密鑰版本指派別名所需的權限,請要求管理員在密鑰、專案、資料夾或機構中,授予您 Secret Manager 管理員 (roles/secretmanager.admin) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

為密鑰版本指派別名

如要為密鑰版本指派別名,請使用下列其中一種方法:

控制台

  1. 前往 Google Cloud 控制台的「Secret Manager」頁面。

    前往 Secret Manager

  2. 如要編輯密鑰,請使用下列其中一種做法:

    • 按一下要編輯的密鑰的「動作」,然後按一下「編輯」

    • 按一下密鑰名稱,前往密鑰詳細資料頁面。在密鑰詳細資料頁面中,按一下「編輯密鑰」

  3. 在「Edit secret」(編輯密鑰) 頁面中,前往「Version aliases」(版本別名),然後按一下「Add alias」(新增別名)

  4. 請執行下列步驟:

    1. 指定別名。

    2. 選取要指派這個別名的密鑰版本。

  5. 按一下「更新密鑰」

gcloud

使用下方的任何指令資料之前,請先替換以下項目:

  • SECRET_ID:密鑰的 ID 或密鑰的完整 ID。
  • KEY:版本別名
  • VALUE:密鑰版本號碼

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud secrets update SECRET_ID \
  --update-version-aliases=KEY=VALUE

Windows (PowerShell)

gcloud secrets update SECRET_ID `
  --update-version-aliases=KEY=VALUE

Windows (cmd.exe)

gcloud secrets update SECRET_ID ^
  --update-version-aliases=KEY=VALUE

回應包含更新後的密鑰。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:專案 ID Google Cloud
  • SECRET_ID:密鑰的 ID 或密鑰的完整 ID
  • KEY:版本別名
  • VALUE:密鑰版本號碼

HTTP 方法和網址:

PATCH https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID?updateMask=version_aliases

JSON 要求主體:

{'version_aliases': {'KEY': 'VALUE'}}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID?updateMask=version_aliases"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID?updateMask=version_aliases" | Select-Object -Expand Content

您應該會收到如下的 JSON 回應:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-09-04T06:34:32.995517Z",
  "etag": "\"16214584d1479c\"",
  "versionAliases": {
    "nonprod": "1"
  }
}

C#

如要執行這段程式碼,請先設定 C# 開發環境,然後安裝 Secret Manager C# SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證


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

public class UpdateSecretWithAliasSample
{
    public Secret UpdateSecret(string projectId = "my-project", string secretId = "my-secret")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the secret with updated fields.
        Secret secret = new Secret
        {
            SecretName = new SecretName(projectId, secretId),
            VersionAliases = { ["test"] = 1}
        };

        // Build the field mask.
        FieldMask fieldMask = FieldMask.FromString("version_aliases");

        // Call the API.
        Secret updatedSecret = client.UpdateSecret(secret, fieldMask);
        return updatedSecret;
    }
}

Go

如要執行這段程式碼,請先設定 Go 開發環境,並安裝 Secret Manager Go SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
	"google.golang.org/genproto/protobuf/field_mask"
)

// updateSecret updates the alias map on an existing secret.
func updateSecretWithAlias(w io.Writer, name string) error {
	// name := "projects/my-project/secrets/my-secret"

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

	// Build the request.
	req := &secretmanagerpb.UpdateSecretRequest{
		Secret: &secretmanagerpb.Secret{
			Name: name,
			VersionAliases: map[string]int64{
				"test": 1,
			},
		},
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"version_aliases"},
		},
	}

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

Java

如要執行這段程式碼,請先設定 Java 開發環境,並安裝 Secret Manager Java SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class UpdateSecretWithAlias {

  public static void updateSecret() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String secretId = "your-secret-id";
    updateSecret(projectId, secretId);
  }

  // Update an existing secret.
  public static void updateSecret(String projectId, String secretId) 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 (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
      // Build the name.
      SecretName secretName = SecretName.of(projectId, secretId);

      // Build the updated secret.
      Secret.Builder secret =
          Secret.newBuilder()
              .setName(secretName.toString());
      secret.getMutableVersionAliases().put("test", 1L);      

      // Build the field mask.
      FieldMask fieldMask = FieldMaskUtil.fromString("version_aliases");

      // Update the secret.
      Secret updatedSecret = client.updateSecret(secret.build(), fieldMask);
      System.out.printf("Updated alias map: %s\n", updatedSecret.getVersionAliasesMap().toString());
    }
  }
}

Node.js

如要執行這段程式碼,請先設定 Node.js 開發環境,並安裝 Secret Manager Node.js SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const name = 'projects/my-project/secrets/my-secret';

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

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

async function updateSecret() {
  const [secret] = await client.updateSecret({
    secret: {
      name: name,
      versionAliases: {
        test: 1,
      },
    },
    updateMask: {
      paths: ['version_aliases'],
    },
  });

  console.info(`Updated secret ${secret.name}`);
}

updateSecret();

PHP

如要執行這段程式碼,請先瞭解如何在 Google Cloud 上使用 PHP,並安裝 Secret Manager PHP SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\Secret;
use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient;
use Google\Cloud\SecretManager\V1\UpdateSecretRequest;
use Google\Protobuf\FieldMask;

/**
 * @param string $projectId Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId  Your secret ID (e.g. 'my-secret')
 */
function update_secret_with_alias(string $projectId, string $secretId): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

    // Build the resource name of the secret.
    $name = $client->secretName($projectId, $secretId);

    // Update the secret.
    $secret = (new Secret())
      ->setName($name)
      ->setVersionAliases(['test' => '1']);

    $updateMask = (new FieldMask())
      ->setPaths(['version_aliases']);

    // Build the request.
    $request = UpdateSecretRequest::build($secret, $updateMask);

    $response = $client->updateSecret($request);

    // Print the upated secret.
    printf('Updated secret: %s', $response->getName());
}

Python

如要執行這段程式碼,請先設定 Python 開發環境,然後安裝 Secret Manager Python SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

def update_secret_with_alias(
    project_id: str, secret_id: str
) -> secretmanager.UpdateSecretRequest:
    """
    Update the metadata about an existing secret.
    """

    # Import the Secret Manager client library.
    from google.cloud import secretmanager

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the secret.
    name = client.secret_path(project_id, secret_id)

    # Update the secret.
    secret = {"name": name, "version_aliases": {"test": 1}}
    update_mask = {"paths": ["version_aliases"]}
    response = client.update_secret(
        request={"secret": secret, "update_mask": update_mask}
    )

    # Print the new secret name.
    print(f"Updated secret: {response.name}")

Ruby

如要執行這段程式碼,請先設定 Ruby 開發環境,然後安裝 Secret Manager Ruby SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

# project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# secret_id  = "YOUR-SECRET-ID"             # (e.g. "my-secret")

# Require the Secret Manager client library.
require "google/cloud/secret_manager"

# Create a Secret Manager client.
client = Google::Cloud::SecretManager.secret_manager_service

# Build the resource name of the secret.
name = client.secret_path project: project_id, secret: secret_id

# Create the secret.
secret = client.update_secret(
  secret: {
    name: name,
    version_aliases: {
      test: 1
    }
  },
  update_mask: {
    paths: ["version_aliases"]
  }
)

# Print the updated secret name.
puts "Updated secret: #{secret.name}"

後續步驟