編輯區域性密鑰

本頁說明如何編輯密碼的中繼資料。您可以更新密碼的許多屬性,例如加密類型、輪替政策、到期日、標籤和事件通知。您也可以為密鑰版本新增註解和設定別名。您無法編輯密鑰名稱或值。 如要為密鑰新增值,請建立新的密鑰版本

必要的角色

如要取得更新密鑰中繼資料所需的權限,請要求管理員為您授予密鑰或專案的 Secret Manager 管理員 (roles/secretmanager.admin) 身分與存取權管理角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

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

編輯密鑰

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

控制台

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

    前往 Secret Manager

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

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

    • 在清單中找出密鑰,然後點選與該密鑰相關的「動作」選單。在「動作」選單中,按一下「編輯」

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

  4. 在「編輯密鑰」頁面中,視需要更新密鑰的屬性,然後按一下「更新密鑰」

gcloud

請確認您已設定 Secret Manager 使用區域端點,以便管理區域密鑰。

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

  • SECRET_ID:密鑰的 ID 或密鑰的完整 ID
  • LOCATION:密鑰的 Google Cloud 位置
  • KEY:標籤鍵
  • VALUE:標籤的對應值

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud secrets update SECRET_ID --location=LOCATION \
    --update-labels=KEY=VALUE

Windows (PowerShell)

gcloud secrets update SECRET_ID --location=LOCATION `
    --update-labels=KEY=VALUE

Windows (cmd.exe)

gcloud secrets update SECRET_ID --location=LOCATION ^
    --update-labels=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=labels

JSON 要求主體:

{'labels': {'KEY': 'VAL'}}

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

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=labels"

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=labels" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-09-02T07:14:00.281541Z",
  "labels": {
    "key": "value"
  },
  "etag": "\"16211dc7d040b1\""
}

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 metadata about an existing secret.
func UpdateRegionalSecret(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,
			Labels: map[string]string{
				"secretmanager": "rocks",
			},
		},
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"labels"},
		},
	}

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

  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";
    updateRegionalSecret(projectId, locationId, secretId);
  }

  // Update an existing secret.
  public static Secret updateRegionalSecret(
      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 secret =
          Secret.newBuilder()
              .setName(secretName.toString())
              .putLabels("secretmanager", "rocks")
              .build();

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

      // Update the secret.
      Secret updatedSecret = client.updateSecret(secret, fieldMask);
      System.out.printf("Updated regional secret %s\n", updatedSecret.getName());

      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,
      labels: {
        secretmanager: 'rocks',
      },
    },
    updateMask: {
      paths: ['labels'],
    },
  });

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

updateRegionalSecret();

Python

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

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


def update_regional_secret(
    project_id: str, location_id: str, secret_id: str
) -> secretmanager_v1.UpdateSecretRequest:
    """
    Updates the metadata about an existing secret.
    """

    # Endpoint to call the regional secret manager sever
    api_endpoint = f"secretmanager.{location_id}.rep.googleapis.com"

    # Create the Secret Manager client.
    client = secretmanager_v1.SecretManagerServiceClient(
        client_options={"api_endpoint": api_endpoint},
    )

    # Build the resource name of the secret.
    name = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}"

    # Update the secret.
    secret = {"name": name, "labels": {"secretmanager": "rocks"}}
    update_mask = {"paths": ["labels"]}
    response = client.update_secret(
        request={"secret": secret, "update_mask": update_mask}
    )

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

    return response

編輯多個密鑰的權限和標籤

您可以使用 Google Cloud 控制台編輯多個密鑰的權限和標籤。

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

    前往 Secret Manager

  2. 在「Secret Manager」頁面中,按一下「Regional secrets」分頁標籤,然後選取要編輯權限和標籤的密鑰。

  3. 如果「資訊面板」已關閉,請按一下「顯示資訊面板」

  4. 所有密鑰的權限和標籤都會顯示在對應分頁的「資訊面板」中。前往個別分頁,視需要更新值。

  5. 完成後,請按一下「儲存」

後續步驟