為區域性密鑰版本指派別名

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

必要的角色

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

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

為密鑰版本指派別名

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

控制台

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

    前往 Secret Manager

  2. 在「Secret Manager」頁面中,按一下「區域性密鑰」分頁標籤。

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

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

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

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

  5. 請執行下列步驟:

    1. 指定別名。

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

  6. 按一下「更新密鑰」

gcloud

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

  • SECRET_ID:密鑰的 ID 或密鑰的完整 ID。
  • LOCATION:密鑰的 Google Cloud 位置
  • KEY:版本別名
  • VALUE:密鑰版本號碼

執行下列指令:

Linux、macOS 或 Cloud Shell

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

Windows (PowerShell)

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

Windows (cmd.exe)

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

回應包含更新後的密鑰。

REST

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

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

HTTP 方法和網址:

PATCH https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/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.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/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.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/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"
  }
}

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/api/option"
	"google.golang.org/genproto/protobuf/field_mask"
)

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

	// Create the client.
	ctx := context.Background()
	//Endpoint to send the request to regional server
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationId)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))

	if err != nil {
		return fmt.Errorf("failed to create regional secretmanager client: %w", err)
	}
	defer client.Close()

	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s", projectId, locationId, secretId)

	// 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 regional secret: %w", err)
	}
	fmt.Fprintf(w, "Updated regional 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.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class UpdateRegionalSecretWithAlias {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Your GCP project ID.
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // Resource ID of the secret to update.
    String secretId = "your-secret-id";
    updateRegionalSecretWithAlias(projectId, locationId, secretId);
  }

  // Update an existing secret using an alias.
  public static Secret updateRegionalSecretWithAlias(
      String projectId, String locationId, String secretId) 
      throws IOException {

    // Endpoint to call the regional secret manager sever
    String apiEndpoint = String.format("secretmanager.%s.rep.googleapis.com:443", locationId);
    SecretManagerServiceSettings secretManagerServiceSettings =
        SecretManagerServiceSettings.newBuilder().setEndpoint(apiEndpoint).build();

    // Initialize the client that will be used to send requests. This client only needs to be
    // created once, and can be reused for multiple requests.
    try (SecretManagerServiceClient client = 
        SecretManagerServiceClient.create(secretManagerServiceSettings)) {
      // Build the name.
      SecretName secretName = 
          SecretName.ofProjectLocationSecretName(projectId, locationId, 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());

      return updatedSecret;
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'my-location';
// const secretId = 'my-secret';

const name = `projects/${projectId}/locations/${locationId}/secrets/${secretId}`;

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

// Adding the endpoint to call the regional secret manager sever
const options = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;

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

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

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

updateRegionalSecret();

後續步驟