使用实体标记实现乐观并发控制

Secret Manager 支持使用实体标记 (ETag) 用于乐观并发控制。

在某些情况下,并行更新同一资源的两个进程可能会相互干扰,其中后一个进程会覆盖前一个进程的工作量。

ETag 提供了一种允许乐观并发控制的方法,即允许进程在对资源执行操作之前查看资源是否已修改。

将 ETag 与 Secret Manager 搭配使用

以下资源修改请求支持 ETag:

secrets.patch 请求中,请求 ETag 嵌入在密文数据中。其他所有请求均接受可选 etag 参数。

如果提供的 ETag 与当前资源的 ETag 匹配,则请求 succeeds;否则将失败,并显示 FAILED_PRECONDITION 错误和 HTTP 状态代码 400。如果未提供 ETag,则请求将继续而不检查当前存储的 ETag 值。

资源 ETag 在创建资源时生成(projects.secrets.createprojects.secrets.addVersion),并针对上面列出的每个修改请求进行更新。修改请求仅更新它适用的资源的 ETag。也就是说,更新密钥版本不会影响 同样,更新 ETag 也不会影响密钥版本。

即使更新不会更改资源的状态,它仍会更新资源 ETag。

请思考以下示例:

  • 用户 1 尝试启用某个密文版本,但不知道该版本已启用。系统会处理此请求,但只会更改版本的 ETag,不会更改任何其他内容。

  • 使用旧 ETag 的用户 2 尝试停用该版本。

  • 此操作失败,因为系统会识别较新的 ETag,而 ETag 指示较新的 intent 使版本保持启用状态

由于 ETag 的更改,即使是看似不重要的更新也非常重要。这可以确保数据一致性 多个用户或系统与同一资源交互。

每当包含资源(SecretSecretVersion)时,响应中都会返回资源 etag

使用 ETag 删除 Secret

本部分介绍如何在删除密钥时使用 ETag。如果密文被其他进程修改,则删除操作将失败。

gcloud

在使用下面的命令数据之前,请先进行以下替换:

  • SECRET_ID:密钥的 ID 或密钥的完全限定标识符。
  • LOCATION:密钥的 Google Cloud 位置
  • ETAG:Secret 的实体标记。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:Secret 的 Google Cloud 位置
  • PROJECT_ID:Google Cloud 项目 ID。
  • SECRET_ID:密钥的 ID 或密钥的完全限定标识符。
  • ETAG:Secret 的实体标记。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 更新 Secret

本部分介绍如何在更新密钥时使用 ETag。如果密文被其他进程修改,则更新操作将失败。

gcloud

在使用下面的命令数据之前,请先进行以下替换:

  • SECRET_ID:密钥的 ID 或密钥的完全限定标识符。
  • LOCATION:密钥的 Google Cloud 位置
  • KEY:标签名称。
  • VALUE:相应的标签值。
  • ETAG:Secret 的实体标记。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"

响应会返回 Secret。

REST

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION:Secret 的 Google Cloud 位置
  • PROJECT_ID:Google Cloud 项目 ID。
  • SECRET_ID:密钥的 ID 或密钥的完全限定标识符。
  • ETAG:Secret 的实体标记。ETag 被指定为 私密 并且必须包含英文引号。例如,如果 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 更新 Secret 版本

本部分介绍了如何在更新密文版本时使用 ETag。如果密钥版本已被 被其他进程修改后,更新操作将失败。

gcloud

在使用下面的命令数据之前,请先进行以下替换:

  • VERSION_ID:密文版本的 ID。
  • SECRET_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"

响应会返回 Secret。

REST

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION:密钥的 Google Cloud 位置
  • PROJECT_ID:Google Cloud 项目 ID
  • SECRET_ID:密钥的 ID 或密钥的完全限定标识符
  • VERSION_ID:Secret 版本的 ID
  • ETAG:Secret 版本的实体标记。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

此处的代码示例介绍了如何使用 ETag 启用密文版本。您还可以在其他密文变更操作期间指定 ETag,例如在停用或销毁密文版本时。请参阅 Secret Manager 的代码示例

后续步骤