使用實體標記進行最佳化並行控制

Secret Manager 支援使用實體標記 (ETag) 進行最佳化的並行控制。

在某些情況下,兩個程序同時更新相同資源時可能會互相干擾,後者會覆寫前者的作業。

ETag 可讓程序在對資源採取行動前,先查看資源是否已修改,藉此提供最佳化的並行控制方式。

搭配使用 ETag 與 Secret Manager

下列資源修改要求支援 ETag:

secrets.patch 要求中,要求 ETag 會內嵌在 Secret 資料中。所有其他要求都會接受選用的 etag 參數。

如果提供 ETag,且與目前的資源 ETag 相符,要求就會成功;否則會失敗,並傳回 FAILED_PRECONDITION 錯誤和 HTTP 狀態碼 400。如果未提供 ETag,系統會繼續處理要求,而不檢查目前儲存的 ETag 值。

資源 ETag 會在建立資源時產生 (projects.secrets.createprojects.secrets.addVersion),並針對上述每個修改要求更新。修改要求只會更新所套用資源的 ETag。也就是說,更新密鑰版本不會影響密鑰 ETag,同樣地,更新 ETag 也不會影響密鑰版本。

即使更新不會變更資源的狀態,系統仍會更新資源 ETag。

請見如下範例:

  • 使用者 1 嘗試啟用 Secret 版本,但不知道該版本已啟用。系統會處理這項要求,但只會變更版本的 ETag,不會變更其他任何內容。

  • 使用者 2 嘗試使用舊 ETag 停用版本。

  • 這項作業會失敗,因為系統會辨識較新的 ETag,這表示最近有保留啟用版本的意圖。

即使是看似微小的更新,也會因為 ETag 變更而影響效能。這可確保資料一致性,特別是多位使用者或系統與同一資源互動時。

只要包含資源 (SecretSecretVersion),回應就會傳回 etag 資源。

使用 ETag 刪除密鑰

本節說明刪除密鑰時如何使用 ETag。如果密鑰已由其他程序修改,刪除作業就會失敗。

gcloud

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

  • SECRET_ID:密鑰的 ID 或密鑰的完整 ID。
  • LOCATION:密鑰的 Google Cloud 位置
  • ETAG:密碼的實體標記。ETag 必須包含前後引號。 舉例來說,如果 ETag 值為 "abc",經過 Shell 逸出處理的值就會是 "\"abc\""

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud secrets delete SECRET_ID --location=LOCATION \
    --etag "ETAG"

Windows (PowerShell)

gcloud secrets delete SECRET_ID --location=LOCATION `
    --etag "ETAG"

Windows (cmd.exe)

gcloud secrets delete SECRET_ID --location=LOCATION ^
    --etag "ETAG"

REST

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

  • LOCATION:密鑰的 Google Cloud 位置
  • PROJECT_ID:專案 ID。 Google Cloud
  • SECRET_ID:密鑰的 ID 或密鑰的完整 ID。
  • ETAG:密碼的實體標記。ETag 會指定為網址查詢字串的一部分,且必須經過網址編碼。舉例來說,如果 ETag 值為 "abc",網址編碼值會是 %22abc%22,因為引號字元會編碼為 %22

HTTP 方法和網址:

DELETE https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID?etag=ETAG

JSON 要求主體:

{}

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

curl

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

curl -X DELETE \
-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?etag=ETAG"

PowerShell

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

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

Invoke-WebRequest `
-Method DELETE `
-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?etag=ETAG" | Select-Object -Expand Content

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

{}

Go

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

import (
	"context"
	"fmt"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
	"google.golang.org/api/option"
)

// deleteSecretWithEtag deletes the secret with the given name and all of its versions.
func DeleteRegionalSecretWithEtag(projectId, locationId, secretId, etag string) error {
	// name := "projects/my-project/locations/my-location/secrets/my-secret"
	// etag := `"123"`

	// 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 secretmanager client: %w", err)
	}
	defer client.Close()

	//Endpoint to send the request to regional server
	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s", projectId, locationId, secretId)

	// Build the request.
	req := &secretmanagerpb.DeleteSecretRequest{
		Name: name,
		Etag: etag,
	}

	// Call the API.
	if err := client.DeleteSecret(ctx, req); err != nil {
		return fmt.Errorf("failed to delete regional secret: %w", err)
	}
	return nil
}

Java

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

import com.google.cloud.secretmanager.v1.DeleteSecretRequest;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretName;
import java.io.IOException;

public class DeleteRegionalSecretWithEtag {

  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 delete.
    String secretId = "your-secret-id";
    // Etag associated with the secret. Quotes should be included as part of the string.
    String etag = "\"1234\"";
    deleteRegionalSecretWithEtag(projectId, locationId, secretId, etag);
  }

  // Delete an existing secret with the given name and etag.
  public static void deleteRegionalSecretWithEtag(
      String projectId, String locationId, String secretId, String etag)
      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 secret name.
      SecretName secretName = SecretName.ofProjectLocationSecretName(
          projectId, locationId, secretId);

      // Construct the request.
      DeleteSecretRequest request =
          DeleteSecretRequest.newBuilder()
              .setName(secretName.toString())
              .setEtag(etag)
              .build();

      // Delete the secret.
      client.deleteSecret(request);
      System.out.printf("Deleted regional secret %s\n", secretId);
    }
  }
}

Python

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

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


def delete_regional_secret_with_etag(
    project_id: str,
    location_id: str,
    secret_id: str,
    etag: str,
) -> None:
    """
    Deletes the regional secret with the given name, etag, and all of its versions.
    """

    # 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}"

    # Build the request
    request = secretmanager_v1.types.service.DeleteSecretRequest(
        name=name,
        etag=etag,
    )

    # Delete the secret.
    client.delete_secret(request=request)

使用 ETag 更新密鑰

本節說明更新密鑰時如何使用 ETag。如果密鑰已由其他程序修改,更新作業就會失敗。

gcloud

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

  • SECRET_ID:密鑰的 ID 或密鑰的完整 ID。
  • LOCATION:密鑰的 Google Cloud 位置
  • KEY:標籤名稱。
  • VALUE:對應的標籤值。
  • ETAG:密碼的實體標記。ETag 必須包含前後引號。 舉例來說,如果 ETag 值為 "abc",經過 Shell 逸出處理的值就會是 "\"abc\""

執行下列指令:

Linux、macOS 或 Cloud Shell

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

Windows (PowerShell)

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

Windows (cmd.exe)

gcloud secrets update SECRET_ID --location=LOCATION ^
    --update-labels "KEY=VALUE" ^
    --etag "ETAG"

回應會傳回密鑰。

REST

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

  • LOCATION:密鑰的 Google Cloud 位置
  • PROJECT_ID:專案 ID。 Google Cloud
  • SECRET_ID:密鑰的 ID 或密鑰的完整 ID。
  • ETAG:密碼的實體標記。ETag 會指定為「Secret」的欄位,且必須加上引號。舉例來說,如果 ETag 值為 "abc",經過 JSON 逸出處理的值就會是 {"etag":"\"abc\""}
  • KEY:標籤名稱。
  • VALUE:對應的標籤值。

HTTP 方法和網址:

PATCH https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID?updateMask=labels

JSON 要求主體:

{"etag":"ETAG", "labels":{"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=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-04T04:06:00.660420Z",
  "labels": {
    "KEY": "VALUE"
  },
  "etag": "\"162145a4f894d5\""
}

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"
)

// updateSecretWithEtag updates the metadata about an existing secret.
func UpdateRegionalSecretWithEtag(w io.Writer, projectId, locationId, secretId, etag string) error {
	// name := "projects/my-project/locations/my-location/secrets/my-secret"
	// etag := `"123"`

	// 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,
			Etag: etag,
			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 UpdateRegionalSecretWithEtag {

  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";
    // Etag associated with the secret. Quotes should be included as part of the string.
    String etag = "\"1234\"";
    updateRegionalSecretWithEtag(projectId, locationId, secretId, etag);
  }

  // Update an existing secret with etag.
  public static Secret updateRegionalSecretWithEtag(
      String projectId, String locationId, String secretId, String etag)
      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())
              .setEtag(etag)
              .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;
    }
  }
}

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_with_etag(
    project_id: str,
    location_id: str,
    secret_id: str,
    etag: str,
) -> secretmanager_v1.UpdateSecretRequest:
    """
    Update the metadata about an existing secret, using etag.
    """

    # 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"}, "etag": etag}
    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

使用 ETag 更新密鑰版本

本節說明更新密鑰版本時如何使用 ETag。如果密鑰版本已由其他程序修改,更新作業就會失敗。

以下程式碼範例說明如何使用 ETag 停用密鑰版本。您也可以在其他密鑰變更作業期間指定 ETag,例如啟用已停用的版本或刪除密鑰版本。請參閱 Secret Manager 的程式碼範例

gcloud

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

  • VERSION_ID:密鑰版本的 ID。
  • SECRET_ID:密鑰的 ID 或密鑰的完整 ID。
  • LOCATION:密鑰的 Google Cloud 位置
  • ETAG:實體標記。ETag 必須包含前後引號。 舉例來說,如果 ETag 值為 "abc",經過 Shell 逸出處理的值就會是 "\"abc\""

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud secrets versions disable VERSION_ID \
  --secret SECRET_ID \
  --location=LOCATION \
  --etag "ETAG"

Windows (PowerShell)

gcloud secrets versions disable VERSION_ID `
  --secret SECRET_ID `
  --location=LOCATION `
  --etag "ETAG"

Windows (cmd.exe)

gcloud secrets versions disable VERSION_ID ^
  --secret SECRET_ID ^
  --location=LOCATION ^
  --etag "ETAG"

回應會傳回密鑰。

REST

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

  • LOCATION:密鑰的 Google Cloud 位置
  • PROJECT_ID:專案 ID Google Cloud
  • SECRET_ID:密鑰的 ID 或密鑰的完整 ID
  • VERSION_ID:密鑰版本的 ID
  • ETAG:密鑰版本的實體標記。ETag 會指定為 SecretVersion 的欄位,且必須加上引號。舉例來說,如果 ETag 值為 "abc",經過 JSON 逸出處理的值就會是 {"etag":"\"abc\""}

HTTP 方法和網址:

POST https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID:disable

JSON 要求主體:

{"etag":"ETAG"}

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

curl

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

curl -X POST \
-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/versions/VERSION_ID:disable"

PowerShell

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

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

Invoke-WebRequest `
-Method POST `
-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/versions/VERSION_ID:disable" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID",
  "createTime": "2024-09-04T06:41:57.859674Z",
  "state": "DISABLED",
  "etag": "\"1621457b3c1459\""
}

Go

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

import (
	"context"
	"fmt"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
	"google.golang.org/api/option"
)

// disableSecretVersionWithEtag disables the given secret version. Future requests will
// throw an error until the secret version is enabled. Other secrets versions
// are unaffected.
func DisableRegionalSecretVersionWithEtag(projectId, locationId, secretId, versionId, etag string) error {
	// name := "projects/my-project/locations/my-location/secrets/my-secret/versions/5"
	// etag := `"123"`

	// 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/versions/%s", projectId, locationId, secretId, versionId)
	// Build the request.
	req := &secretmanagerpb.DisableSecretVersionRequest{
		Name: name,
		Etag: etag,
	}

	// Call the API.
	if _, err := client.DisableSecretVersion(ctx, req); err != nil {
		return fmt.Errorf("failed to disable regional secret version: %w", err)
	}
	return nil
}

Java

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

import com.google.cloud.secretmanager.v1.DisableSecretVersionRequest;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.cloud.secretmanager.v1.SecretVersionName;
import java.io.IOException;

public class DisableRegionalSecretVersionWithEtag {

  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.
    String secretId = "your-secret-id";
    // Version of the Secret ID you want to disable.
    String versionId = "your-version-id";
    // Etag associated with the secret. Quotes should be included as part of the string.
    String etag = "\"1234\"";
    disableRegionalSecretVersionWithEtag(projectId, locationId, secretId, versionId, etag);
  }

  // Disable an existing secret version.
  public static SecretVersion disableRegionalSecretVersionWithEtag(
      String projectId, String locationId, String secretId, String versionId, String etag)
      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 from the version.
      SecretVersionName secretVersionName 
            = SecretVersionName.ofProjectLocationSecretSecretVersionName(
            projectId, locationId, secretId, versionId);

      // Build the request.
      DisableSecretVersionRequest request =
          DisableSecretVersionRequest.newBuilder()
              .setName(secretVersionName.toString())
              .setEtag(etag)
              .build();

      // Disable the secret version.
      SecretVersion version = client.disableSecretVersion(request);
      System.out.printf("Disabled regional secret version %s\n", version.getName());

      return version;
    }
  }
}

Python

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

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


def disable_regional_secret_version_with_etag(
    project_id: str,
    location_id: str,
    secret_id: str,
    version_id: str,
    etag: str,
) -> secretmanager_v1.DisableSecretVersionRequest:
    """
    Disables the given secret version. Future requests will throw an error until
    the secret version is enabled. Other secrets versions are unaffected.
    """

    # 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 version.
    name = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}/versions/{version_id}"

    # Build the request.
    request = secretmanager_v1.types.service.DisableSecretVersionRequest(
        name=name,
        etag=etag,
    )

    # Disable the secret version.
    response = client.disable_secret_version(request=request)

    print(f"Disabled secret version: {response.name}")

    return response

後續步驟