删除 Secret 标签

删除 Secret 的标签

代码示例

Go

如需了解如何安装和使用 Secret Manager 客户端库,请参阅 Secret Manager 客户端库

如需向 Secret Manager 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

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

// deleteSecret updates the metadata about an existing secret and remove an existing label.
func deleteSecretLabel(w io.Writer, name string) error {
	// name := "projects/my-project/secrets/my-secret"

	labelKey := "labelkey"

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

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

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

	labels := result.Labels

	delete(labels, labelKey)

	// Build the request to update the secret.
	updateReq := &secretmanagerpb.UpdateSecretRequest{
		Secret: &secretmanagerpb.Secret{
			Name:   name,
			Labels: labels,
		},
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"labels"},
		},
	}

	// Call the API.
	updateResult, err := client.UpdateSecret(ctx, updateReq)
	if err != nil {
		return fmt.Errorf("failed to update secret: %w", err)
	}
	fmt.Fprintf(w, "Updated secret: %s\n", updateResult.Name)
	return nil
}

Java

如需了解如何安装和使用 Secret Manager 客户端库,请参阅 Secret Manager 客户端库

如需向 Secret Manager 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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.FieldMaskOrBuilder;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DeleteSecretLabel {

  public static void deleteSecretLabel() throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // This is the id of the GCP project
    String projectId = "your-project-id";
    // This is the id of the secret to act on
    String secretId = "your-secret-id";
    // This is the key of the label to be deleted
    String labelKey = "your-label-key";
    deleteSecretLabel(projectId, secretId, labelKey);
  }

  // Update an existing secret, by deleting a label.
  public static Secret deleteSecretLabel(
                     String projectId, String secretId, String labelKey) 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.
    try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
      // Build the name.
      SecretName secretName = SecretName.of(projectId, secretId);

      // Get the existing secret
      Secret existingSecret = client.getSecret(secretName);

      Map<String, String> existingLabelsMap = 
              new HashMap<String, String>(existingSecret.getLabels());
      existingLabelsMap.remove(labelKey);

      // Build the updated secret.
      Secret secret =
          Secret.newBuilder()
              .setName(secretName.toString())
              .putAllLabels(existingLabelsMap)
              .build();

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

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

      return updatedSecret;
    }
  }
}

Node.js

如需了解如何安装和使用 Secret Manager 客户端库,请参阅 Secret Manager 客户端库

如需向 Secret Manager 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const name = 'projects/my-project/secrets/my-secret';
// const labelKey = 'secretmanager';

// 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,
  });

  return secret;
}

async function deleteSecretLabel() {
  const oldSecret = await getSecret();
  delete oldSecret.labels[labelKey];
  const [secret] = await client.updateSecret({
    secret: {
      name: name,
      labels: oldSecret.labels,
    },
    updateMask: {
      paths: ['labels'],
    },
  });

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

deleteSecretLabel();

Python

如需了解如何安装和使用 Secret Manager 客户端库,请参阅 Secret Manager 客户端库

如需向 Secret Manager 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import argparse

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


def delete_secret_label(
    project_id: str, secret_id: str, label_key: str
) -> secretmanager.UpdateSecretRequest:
    """
    Delete a label on an existing secret.
    """

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

    labels = response.labels

    # Delete the label
    labels.pop(label_key, None)

    # Update the secret.
    secret = {"name": name, "labels": labels}
    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 产品的代码示例,请参阅 Google Cloud 示例浏览器