Hapus label rahasia

Menghapus label rahasia

Contoh kode

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Secret Manager, lihat Library klien Secret Manager.

Untuk mengautentikasi ke Secret Manager, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Secret Manager, lihat Library klien Secret Manager.

Untuk mengautentikasi ke Secret Manager, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * 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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Secret Manager, lihat Library klien Secret Manager.

Untuk mengautentikasi ke Secret Manager, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Langkah selanjutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contoh Google Cloud.