管理密文

在 Secret Manager 中,密文是一系列密文版本的封装容器。密文存储标签和复制等元数据,但不包含实际密文。本主题介绍如何管理密文。您还可以管理密文的版本

准备工作

为每个项目配置一次 Secret Manager 和本地环境

列出密文

这些示例展示了如何列出您有权在项目中查看的所有密文。

如需列出密文,需要具有密文、项目、文件夹或组织的查看者角色 (roles/secretmanager.viewer)。不能对密文版本授予 IAM 角色。

网页界面

  1. 转到 Cloud Console 中的 Secret Manager 页面。

    转到 Secret Manager 页面

  2. 此页面显示项目中的密文列表。

命令行

要在命令行上使用 Secret Manager,请先安装或升级到 Cloud SDK 版本 305.0.0 或更高版本

$ gcloud secrets list

C#

要运行此代码,请先设置 C# 开发环境安装 Secret Manager C# SDK


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;

public class ListSecretsSample
{
    public void ListSecrets(string projectId = "my-project")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        ProjectName projectName = new ProjectName(projectId);

        // Call the API.
        foreach (Secret secret in client.ListSecrets(projectName))
        {
            // ...
        }
    }
}

Go

要运行此代码,请先设置 Go 开发环境安装 Secret Manager Go SDK

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"google.golang.org/api/iterator"
	secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
)

// listSecrets lists all secrets in the given project.
func listSecrets(w io.Writer, parent string) error {
	// parent := "projects/my-project"

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

	// Build the request.
	req := &secretmanagerpb.ListSecretsRequest{
		Parent: parent,
	}

	// Call the API.
	it := client.ListSecrets(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}

		if err != nil {
			return fmt.Errorf("failed to list secret versions: %v", err)
		}

		fmt.Fprintf(w, "Found secret %s\n", resp.Name)
	}

	return nil
}

Java

要运行此代码,请先设置 Java 开发环境安装 Secret Manager Java SDK

import com.google.cloud.secretmanager.v1.ProjectName;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient.ListSecretsPagedResponse;
import java.io.IOException;

public class ListSecrets {

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

  // List all secrets for a project
  public void listSecrets(String projectId) 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 parent name.
      ProjectName projectName = ProjectName.of(projectId);

      // Get all secrets.
      ListSecretsPagedResponse pagedResponse = client.listSecrets(projectName);

      // List all secrets.
      pagedResponse
          .iterateAll()
          .forEach(
              secret -> {
                System.out.printf("Secret %s\n", secret.getName());
              });
    }
  }
}

Node.js

要运行此代码,请先设置 Node.js 开发环境安装 Secret Manager Node.js SDK

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

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

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

async function listSecrets() {
  const [secrets] = await client.listSecrets({
    parent: parent,
  });

  secrets.forEach(secret => {
    const policy = secret.replication.replication;
    console.log(`${secret.name} (${policy})`);
  });
}

listSecrets();

PHP

如需运行此代码,请先了解如何在 Google Cloud 上使用 PHP安装 Secret Manager PHP SDK

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

/** Uncomment and populate these variables in your code */
// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');

// Create the Secret Manager client.
$client = new SecretManagerServiceClient();

// Build the resource name of the parent secret.
$parent = $client->projectName($projectId);

// List all secrets.
foreach ($client->listSecrets($parent) as $secret) {
    printf('Found secret %s', $secret->getName());
}

Python

要运行此代码,请先设置 Python 开发环境安装 Secret Manager Python SDK

def list_secrets(project_id):
    """
    List all secrets in the given project.
    """

    # 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 parent project.
    parent = f"projects/{project_id}"

    # List all secrets.
    for secret in client.list_secrets(request={"parent": parent}):
        print("Found secret: {}".format(secret.name))

Ruby

要运行此代码,请先设置 Ruby 开发环境安装 Secret Manager Ruby SDK

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

# 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 parent.
parent = client.project_path project: project_id

# Get the list of secrets.
list = client.list_secrets parent: parent

# Print out all secrets.
list.each do |secret|
  puts "Got secret #{secret.name}"
end

API

这些示例使用 curl 来使用 API 演示。

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets" \
    --request "GET" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id"

获取有关密文的详情

这些示例显示如何通过查看密文的元数据来获取密文的详细信息。

如需查看密文的元数据,需要具有密文、项目、文件夹或组织的密文查看者角色 (roles/secretmanager.viewer)。不能对密文版本授予 IAM 角色。

网页界面

  1. 转到 Cloud Console 中的 Secret Manager 页面。

    转到 Secret Manager 页面

  2. Secret Manager 页面上,点击密文的名称进行描述。

  3. 密文详情页面列出了有关密文的信息。

命令行

要在命令行上使用 Secret Manager,请先安装或升级到 Cloud SDK 版本 305.0.0 或更高版本

$ gcloud secrets describe secret-id

C#

要运行此代码,请先设置 C# 开发环境安装 Secret Manager C# SDK


using Google.Cloud.SecretManager.V1;

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

        // Build the resource name.
        SecretName secretName = new SecretName(projectId, secretId);

        // Call the API.
        Secret secret = client.GetSecret(secretName);
        return secret;
    }
}

Go

要运行此代码,请先设置 Go 开发环境安装 Secret Manager Go SDK

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
)

// getSecret gets information about the given secret. This only returns metadata
// about the secret container, not any secret material.
func getSecret(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: %v", err)
	}

	// Build the request.
	req := &secretmanagerpb.GetSecretRequest{
		Name: name,
	}

	// Call the API.
	result, err := client.GetSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get secret: %v", err)
	}

	replication := result.Replication.Replication
	fmt.Fprintf(w, "Found secret %s with replication policy %s\n", result.Name, replication)
	return nil
}

Java

要运行此代码,请先设置 Java 开发环境安装 Secret Manager Java SDK

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

public class GetSecret {

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

  // Get an existing secret.
  public void getSecret(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);

      // Create the secret.
      Secret secret = client.getSecret(secretName);

      // Get the replication policy.
      String replication = "";
      if (secret.getReplication().getAutomatic() != null) {
        replication = "AUTOMATIC";
      } else if (secret.getReplication().getUserManaged() != null) {
        replication = "MANAGED";
      } else {
        throw new IllegalStateException("Unknown replication type");
      }

      System.out.printf("Secret %s, replication %s\n", secret.getName(), replication);
    }
  }
}

Node.js

要运行此代码,请先设置 Node.js 开发环境安装 Secret Manager Node.js SDK

/**
 * 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 getSecret() {
  const [secret] = await client.getSecret({
    name: name,
  });

  const policy = secret.replication.replication;

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

getSecret();

PHP

如需运行此代码,请先了解如何在 Google Cloud 上使用 PHP安装 Secret Manager PHP SDK

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

/** Uncomment and populate these variables in your code */
// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');
// $secretId = 'YOUR_SECRET_ID' (e.g. 'my-secret');

// Create the Secret Manager client.
$client = new SecretManagerServiceClient();

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

// Get the secret.
$secret = $client->getSecret($name);

// Get the replication policy.
$replication = strtoupper($secret->getReplication()->getReplication());

// Print data about the secret.
printf('Got secret %s with replication policy %s', $secret->getName(), $replication);

Python

要运行此代码,请先设置 Python 开发环境安装 Secret Manager Python SDK

def get_secret(project_id, secret_id):
    """
    Get information about the given secret. This only returns metadata about
    the secret container, not any secret material.
    """

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

    # Get the secret.
    response = client.get_secret(request={"name": name})

    # Get the replication policy.
    if "automatic" in response.replication:
        replication = "AUTOMATIC"
    elif "user_managed" in response.replication:
        replication = "MANAGED"
    else:
        raise "Unknown replication {}".format(response.replication)

    # Print data about the secret.
    print("Got secret {} with replication policy {}".format(response.name, replication))

Ruby

要运行此代码,请先设置 Ruby 开发环境安装 Secret Manager Ruby SDK

# 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

# Get the secret.
secret = client.get_secret name: name

# Get the replication policy.
if !secret.replication.automatic.nil?
  replication = "automatic"
elsif !secret.replication.user_managed.nil?
  replication = "user managed"
else
  raise "Unknown replication #{secret.replication}"
end

# Print a success message.
puts "Got secret #{secret.name} with replication policy #{replication}"

API

这些示例使用 curl 来使用 API 演示。

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id" \
    --request "GET" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id"

管理对密文的访问权限

这些示例展示了如何管理密文版本(包括密文本身)的访问权限。如需详细了解访问权限控制和权限,请参阅 Secret Manager IAM 文档

要管理对密文的访问权限,需要具有密文、项目、文件夹或组织的密文管理员角色 (roles/secretmanager.admin)。不能对密文版本授予 IAM 角色。

要授予访问权限:

网页界面

  1. 转到 Cloud Console 中的 Secret Manager 页面。

    转到 Secret Manager 页面

  2. Secret Manager 页面上,点击密文的名称。

  3. 如果面板尚未打开,请点击显示信息面板以打开面板。

  4. 在信息面板中,点击添加成员

  5. 新成员文本区域中,输入要添加的成员的电子邮件地址。

  6. 选择角色下拉列表中,选择 Secret Manager,然后选择 Secret Manager Secret Accessor

命令行

要在命令行上使用 Secret Manager,请先安装或升级到 Cloud SDK 版本 305.0.0 或更高版本

$ gcloud secrets add-iam-policy-binding secret-id \
    --member="member" \
    --role="roles/secretmanager.secretAccessor"

其中,memberIAM 成员,例如用户、群组或服务帐号。

C#

要运行此代码,请先设置 C# 开发环境安装 Secret Manager C# SDK


using Google.Cloud.SecretManager.V1;
using Google.Cloud.Iam.V1;

public class IamGrantAccessSample
{
    public Policy IamGrantAccess(
      string projectId = "my-project", string secretId = "my-secret",
      string member = "user:foo@example.com")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretName secretName = new SecretName(projectId, secretId);

        // Get current policy.
        Policy policy = client.GetIamPolicy(new GetIamPolicyRequest
        {
            ResourceAsResourceName = secretName,
        });

        // Add the user to the list of bindings.
        policy.AddRoleMember("roles/secretmanager.secretAccessor", member);

        // Save the updated policy.
        policy = client.SetIamPolicy(new SetIamPolicyRequest
        {
            ResourceAsResourceName = secretName,
            Policy = policy,
        });
        return policy;
    }
}

Go

要运行此代码,请先设置 Go 开发环境安装 Secret Manager Go SDK

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
)

// iamGrantAccess grants the given member access to the secret.
func iamGrantAccess(w io.Writer, name, member string) error {
	// name := "projects/my-project/secrets/my-secret"
	// member := "user:foo@example.com"

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

	// Get the current IAM policy.
	handle := client.IAM(name)
	policy, err := handle.Policy(ctx)
	if err != nil {
		return fmt.Errorf("failed to get policy: %v", err)
	}

	// Grant the member access permissions.
	policy.Add(member, "roles/secretmanager.secretAccessor")
	if err = handle.SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("failed to save policy: %v", err)
	}

	fmt.Fprintf(w, "Updated IAM policy for %s\n", name)
	return nil
}

Java

要运行此代码,请先设置 Java 开发环境安装 Secret Manager Java SDK

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import java.io.IOException;

public class IamGrantAccess {

  public void iamGrantAccess() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String secretId = "your-secret-id";
    String member = "user:foo@example.com";
    iamGrantAccess(projectId, secretId, member);
  }

  // Grant a member access to a particular secret.
  public void iamGrantAccess(String projectId, String secretId, String member) 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 from the version.
      SecretName secretName = SecretName.of(projectId, secretId);

      // Request the current IAM policy.
      Policy currentPolicy =
          client.getIamPolicy(
              GetIamPolicyRequest.newBuilder().setResource(secretName.toString()).build());

      // Build the new binding.
      Binding binding =
          Binding.newBuilder()
              .setRole("roles/secretmanager.secretAccessor")
              .addMembers(member)
              .build();

      // Create a new IAM policy from the current policy, adding the binding.
      Policy newPolicy = Policy.newBuilder().mergeFrom(currentPolicy).addBindings(binding).build();

      // Save the updated IAM policy.
      client.setIamPolicy(
          SetIamPolicyRequest.newBuilder()
              .setResource(secretName.toString())
              .setPolicy(newPolicy)
              .build());

      System.out.printf("Updated IAM policy for %s\n", secretId);
    }
  }
}

Node.js

要运行此代码,请先设置 Node.js 开发环境安装 Secret Manager Node.js SDK

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const name = 'projects/my-project/secrets/my-secret';
// const member = 'user:you@example.com';
//
// NOTE: Each member must be prefixed with its type. See the IAM documentation
// for more information: https://cloud.google.com/iam/docs/overview.

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

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

async function grantAccess() {
  // Get the current IAM policy.
  const [policy] = await client.getIamPolicy({
    resource: name,
  });

  // Add the user with accessor permissions to the bindings list.
  policy.bindings.push({
    role: 'roles/secretmanager.secretAccessor',
    members: [member],
  });

  // Save the updated IAM policy.
  await client.setIamPolicy({
    resource: name,
    policy: policy,
  });

  console.log(`Updated IAM policy for ${name}`);
}

grantAccess();

PHP

如需运行此代码,请先了解如何在 Google Cloud 上使用 PHP安装 Secret Manager PHP SDK

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

// Import the Secret Manager IAM library.
use Google\Cloud\Iam\V1\Binding;

/** Uncomment and populate these variables in your code */
// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');
// $secretId = 'YOUR_SECRET_ID' (e.g. 'my-secret');
// $member = 'YOUR_MEMBER' (e.g. 'user:foo@example.com');

// Create the Secret Manager client.
$client = new SecretManagerServiceClient();

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

// Get the current IAM policy.
$policy = $client->getIamPolicy($name);

// Update the bindings to include the new member.
$bindings = $policy->getBindings();
$bindings[] = new Binding([
    'members' => [$member],
    'role' => 'roles/secretmanager.secretAccessor',
]);
$policy->setBindings($bindings);

// Save the updated policy to the server.
$client->setIamPolicy($name, $policy);

// Print out a success message.
printf('Updated IAM policy for %s', $secretId);

Python

要运行此代码,请先设置 Python 开发环境安装 Secret Manager Python SDK

def iam_grant_access(project_id, secret_id, member):
    """
    Grant the given member access to a 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)

    # Get the current IAM policy.
    policy = client.get_iam_policy(request={"resource": name})

    # Add the given member with access permissions.
    policy.bindings.add(role="roles/secretmanager.secretAccessor", members=[member])

    # Update the IAM Policy.
    new_policy = client.set_iam_policy(request={"resource": name, "policy": policy})

    # Print data about the secret.
    print("Updated IAM policy on {}".format(secret_id))

Ruby

要运行此代码,请先设置 Ruby 开发环境安装 Secret Manager Ruby SDK

# project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# secret_id  = "YOUR-SECRET-ID"             # (e.g. "my-secret")
# member     = "USER-OR-ACCOUNT"            # (e.g. "user:foo@example.com")

# 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

# Get the current IAM policy.
policy = client.get_iam_policy resource: name

# Add new member to current bindings
policy.bindings << Google::Iam::V1::Binding.new(
  members: [member],
  role:    "roles/secretmanager.secretAccessor"
)

# Update IAM policy
new_policy = client.set_iam_policy resource: name, policy: policy

# Print a success message.
puts "Updated IAM policy for #{secret_id}"

API

这些示例使用 curl 来使用 API 演示。

注意:与其他示例不同,它将替换整个 IAM 政策。

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id:setIamPolicy" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id" \
    --data "{\"policy\": {\"bindings\": [{\"members\": [\"member\"], \"role\": \"roles/secretmanager.secretAccessor\"}]}}"

如需撤销访问权限:

网页界面

  1. 转到 Cloud Console 中的 Secret Manager 页面。

    转到 Secret Manager 页面

  2. Secret Manager 页面上,点击密文的名称。

  3. 如果面板尚未打开,请点击显示信息面板以打开面板。

  4. 在信息面板中,展开 Secret Manager Secret Accessor

  5. 点击要撤销访问权限的垃圾桶图标。

  6. 在弹出窗口中,确认并点击移除

命令行

要在命令行上使用 Secret Manager,请先安装或升级到 Cloud SDK 版本 305.0.0 或更高版本

$ gcloud secrets remove-iam-policy-binding secret-id \
    --member="member" \
    --role="roles/secretmanager.secretAccessor"

其中,memberIAM 成员,例如用户、群组或服务帐号。

C#

要运行此代码,请先设置 C# 开发环境安装 Secret Manager C# SDK


using Google.Cloud.SecretManager.V1;
using Google.Cloud.Iam.V1;

public class IamRevokeAccessSample
{
    public Policy IamRevokeAccess(
      string projectId = "my-project", string secretId = "my-secret",
      string member = "user:foo@example.com")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretName secretName = new SecretName(projectId, secretId);

        // Get current policy.
        Policy policy = client.GetIamPolicy(new GetIamPolicyRequest
        {
            ResourceAsResourceName = secretName,
        });

        // Remove the user to the list of bindings.
        policy.RemoveRoleMember("roles/secretmanager.secretAccessor", member);

        // Save the updated policy.
        policy = client.SetIamPolicy(new SetIamPolicyRequest
        {
            ResourceAsResourceName = secretName,
            Policy = policy,
        });
        return policy;
    }
}

Go

要运行此代码,请先设置 Go 开发环境安装 Secret Manager Go SDK

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
)

// iamRevokeAccess revokes the given member's access on the secret.
func iamRevokeAccess(w io.Writer, name, member string) error {
	// name := "projects/my-project/secrets/my-secret"
	// member := "user:foo@example.com"

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

	// Get the current IAM policy.
	handle := client.IAM(name)
	policy, err := handle.Policy(ctx)
	if err != nil {
		return fmt.Errorf("failed to get policy: %v", err)
	}

	// Grant the member access permissions.
	policy.Remove(member, "roles/secretmanager.secretAccessor")
	if err = handle.SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("failed to save policy: %v", err)
	}

	fmt.Fprintf(w, "Updated IAM policy for %s\n", name)
	return nil
}

Java

要运行此代码,请先设置 Java 开发环境安装 Secret Manager Java SDK

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import java.io.IOException;

public class IamRevokeAccess {

  public void iamRevokeAccess() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String secretId = "your-secret-id";
    String member = "user:foo@example.com";
    iamRevokeAccess(projectId, secretId, member);
  }

  // Revoke a member access to a particular secret.
  public void iamRevokeAccess(String projectId, String secretId, String member) 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 from the version.
      SecretName secretName = SecretName.of(projectId, secretId);

      // Request the current IAM policy.
      Policy policy =
          client.getIamPolicy(
              GetIamPolicyRequest.newBuilder().setResource(secretName.toString()).build());

      // Search through bindings and remove matches.
      String roleToFind = "roles/secretmanager.secretAccessor";
      for (Binding binding : policy.getBindingsList()) {
        if (binding.getRole() == roleToFind && binding.getMembersList().contains(member)) {
          binding.getMembersList().remove(member);
        }
      }

      // Save the updated IAM policy.
      client.setIamPolicy(
          SetIamPolicyRequest.newBuilder()
              .setResource(secretName.toString())
              .setPolicy(policy)
              .build());

      System.out.printf("Updated IAM policy for %s\n", secretId);
    }
  }
}

Node.js

要运行此代码,请先设置 Node.js 开发环境安装 Secret Manager Node.js SDK

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const name = 'projects/my-project/secrets/my-secret';
// const member = 'user:you@example.com';
//
// NOTE: Each member must be prefixed with its type. See the IAM documentation
// for more information: https://cloud.google.com/iam/docs/overview.

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

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

async function grantAccess() {
  // Get the current IAM policy.
  const [policy] = await client.getIamPolicy({
    resource: name,
  });

  // Build a new list of policy bindings with the user excluded.
  for (const i in policy.bindings) {
    const binding = policy.bindings[i];
    if (binding.role !== 'roles/secretmanager.secretAccessor') {
      continue;
    }

    const idx = binding.members.indexOf(member);
    if (idx !== -1) {
      binding.members.splice(idx, 1);
    }
  }

  // Save the updated IAM policy.
  await client.setIamPolicy({
    resource: name,
    policy: policy,
  });

  console.log(`Updated IAM policy for ${name}`);
}

grantAccess();

PHP

如需运行此代码,请先了解如何在 Google Cloud 上使用 PHP安装 Secret Manager PHP SDK

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

/** Uncomment and populate these variables in your code */
// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');
// $secretId = 'YOUR_SECRET_ID' (e.g. 'my-secret');
// $member = 'YOUR_MEMBER' (e.g. 'user:foo@example.com');

// Create the Secret Manager client.
$client = new SecretManagerServiceClient();

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

// Get the current IAM policy.
$policy = $client->getIamPolicy($name);

// Remove the member from the list of bindings.
foreach ($policy->getBindings() as $binding) {
    if ($binding->getRole() == 'roles/secretmanager.secretAccessor') {
        $members = $binding->getMembers();
        foreach ($members as $i => $existingMember) {
            if ($member == $existingMember) {
                unset($members[$i]);
                $binding->setMembers($members);
                break;
            }
        }
    }
}

// Save the updated policy to the server.
$client->setIamPolicy($name, $policy);

// Print out a success message.
printf('Updated IAM policy for %s', $secretId);

Python

要运行此代码,请先设置 Python 开发环境安装 Secret Manager Python SDK

def iam_revoke_access(project_id, secret_id, member):
    """
    Revoke the given member access to a 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)

    # Get the current IAM policy.
    policy = client.get_iam_policy(request={"resource": name})

    # Remove the given member's access permissions.
    accessRole = "roles/secretmanager.secretAccessor"
    for b in list(policy.bindings):
        if b.role == accessRole and member in b.members:
            b.members.remove(member)

    # Update the IAM Policy.
    new_policy = client.set_iam_policy(request={"resource": name, "policy": policy})

    # Print data about the secret.
    print("Updated IAM policy on {}".format(secret_id))

Ruby

要运行此代码,请先设置 Ruby 开发环境安装 Secret Manager Ruby SDK

# project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# secret_id  = "YOUR-SECRET-ID"             # (e.g. "my-secret")
# member     = "USER-OR-ACCOUNT"            # (e.g. "user:foo@example.com")

# 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

# Get the current IAM policy.
policy = client.get_iam_policy resource: name

# Remove the member from the current bindings
policy.bindings.each do |bind|
  if bind.role == "roles/secretmanager.secretAccessor"
    bind.members.delete member
  end
end

# Update IAM policy
new_policy = client.set_iam_policy resource: name, policy: policy

# Print a success message.
puts "Updated IAM policy for #{secret_id}"

API

这些示例使用 curl 来使用 API 演示。

注意:与其他示例不同,它将替换整个 IAM 政策。

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id:setIamPolicy" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id" \
    --data "{\"policy\": {\"bindings\": []}}"

更新密文

这些示例展示了如何更新密文的元数据。

要更新密文的元数据,需要具有密文或项目的密文管理员角色 (roles/secretmanager.admin)。不能对密文版本授予 IAM 角色。

网页界面

  1. 转到 Cloud Console 中的 Secret Manager 页面。

    转到 Secret Manager 页面

  2. Secret Manager 页面上,点击密文的名称进行更新。

  3. 如果信息面板已关闭,请点击显示信息面板以显示信息。

  4. 信息面板中,选择标签标签页。

  5. 点击添加标签,然后输入值为 rocks 的密钥 secretmanager

  6. 点击保存

命令行

要在命令行上使用 Secret Manager,请先安装或升级到 Cloud SDK 版本 305.0.0 或更高版本

$ gcloud secrets update secret-id \
    --update-labels=key=value

C#

要运行此代码,请先设置 C# 开发环境安装 Secret Manager C# SDK


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

public class UpdateSecretSample
{
    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),
        };
        secret.Labels["secretmanager"] = "rocks";

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

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

Go

要运行此代码,请先设置 Go 开发环境安装 Secret Manager Go SDK

import (
	"context"
	"fmt"
	"io"

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

// updateSecret updates the metadata about an existing secret.
func updateSecret(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: %v", err)
	}

	// 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 secret: %v", err)
	}
	fmt.Fprintf(w, "Updated secret: %s\n", result.Name)
	return nil
}

Java

要运行此代码,请先设置 Java 开发环境安装 Secret Manager Java SDK

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 UpdateSecret {

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

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

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

Node.js

要运行此代码,请先设置 Node.js 开发环境安装 Secret Manager Node.js SDK

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

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

updateSecret();

PHP

如需运行此代码,请先了解如何在 Google Cloud 上使用 PHP安装 Secret Manager PHP SDK

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

/** Uncomment and populate these variables in your code */
// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');
// $secretId = 'YOUR_SECRET_ID' (e.g. 'my-secret');

// 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)
  ->setLabels(['secretmanager' => 'rocks']);

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

$response = $client->updateSecret($secret, $updateMask);

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

Python

要运行此代码,请先设置 Python 开发环境安装 Secret Manager Python SDK

def update_secret(project_id, secret_id):
    """
    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, "labels": {"secretmanager": "rocks"}}
    update_mask = {"paths": ["labels"]}
    response = client.update_secret(
        request={"secret": secret, "update_mask": update_mask}
    )

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

Ruby

要运行此代码,请先设置 Ruby 开发环境安装 Secret Manager Ruby SDK

# 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,
    labels: {
      "secretmanager": "rocks"
    }
  },
  update_mask: {
    paths: ["labels"]
  }
)

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

API

这些示例使用 curl 来使用 API 演示。

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id?updateMask=labels" \
    --request "PATCH" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id" \
    --data "{"labels": {"key": "value"}}"

删除密文

以下示例显示了如何删除密文及其所有版本。这是一项不可逆转的操作。任何尝试访问已删除密文的服务或工作负载都会收到 Not Found 错误。

如需删除密文,需要具有密文、项目、文件夹或组织的密文管理员角色 (roles/secretmanager.admin)。不能对密文版本授予 IAM 角色。

网页界面

  1. 转到 Cloud Console 中的 Secret Manager 页面。

    转到 Secret Manager 页面

  2. Secret Manager 页面上的操作列中,点击查看更多

  3. 在菜单中选择删除

  4. 删除密文对话框中,输入密文的名称。

  5. 点击删除密文按钮。

命令行

要在命令行上使用 Secret Manager,请先安装或升级到 Cloud SDK 版本 305.0.0 或更高版本

$ gcloud secrets delete secret-id

C#

要运行此代码,请先设置 C# 开发环境安装 Secret Manager C# SDK


using Google.Cloud.SecretManager.V1;

public class DeleteSecretSample
{
    public void DeleteSecret(
      string projectId = "my-project", string secretId = "my-secret")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretName secretName = new SecretName(projectId, secretId);

        // Delete the secret.
        client.DeleteSecret(secretName);
    }
}

Go

要运行此代码,请先设置 Go 开发环境安装 Secret Manager Go SDK

import (
	"context"
	"fmt"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
)

// deleteSecret deletes the secret with the given name and all of its versions.
func deleteSecret(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: %v", err)
	}

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

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

Java

要运行此代码,请先设置 Java 开发环境安装 Secret Manager Java SDK

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

public class DeleteSecret {

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

  // Delete an existing secret with the given name.
  public void deleteSecret(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 secret name.
      SecretName secretName = SecretName.of(projectId, secretId);

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

Node.js

要运行此代码,请先设置 Node.js 开发环境安装 Secret Manager Node.js SDK

/**
 * 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 deleteSecret() {
  await client.deleteSecret({
    name: name,
  });

  console.log(`Deleted secret ${name}`);
}

deleteSecret();

PHP

如需运行此代码,请先了解如何在 Google Cloud 上使用 PHP安装 Secret Manager PHP SDK

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

/** Uncomment and populate these variables in your code */
// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');
// $secretId = 'YOUR_SECRET_ID' (e.g. 'my-secret');

// Create the Secret Manager client.
$client = new SecretManagerServiceClient();

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

// Delete the secret.
$client->deleteSecret($name);
printf('Deleted secret %s', $secretId);

Python

要运行此代码,请先设置 Python 开发环境安装 Secret Manager Python SDK

def delete_secret(project_id, secret_id):
    """
    Delete the secret with the given name and all of its versions.
    """

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

    # Delete the secret.
    client.delete_secret(request={"name": name})

Ruby

要运行此代码,请先设置 Ruby 开发环境安装 Secret Manager Ruby SDK

# 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

# Delete the secret.
client.delete_secret name: name

# Print a success message.
puts "Deleted secret #{name}"

API

这些示例使用 curl 来使用 API 演示。

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id" \
    --request "DELETE" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id"

后续步骤