Anmerkungen erstellen und verwalten

Auf dieser Seite wird beschrieben, wie Sie einem Secret Annotationen hinzufügen und diese bearbeiten und ansehen.

Übersicht

Sie können Annotationen verwenden, um benutzerdefinierte Metadaten zu einem Secret zu speichern. Sie können beispielsweise ein Secret mit dem Pfad versehen, unter dem es bereitgestellt wird. Annotationen können in folgenden Fällen hilfreich sein:

  • Sie können Secrets nach Zweck, Umgebung (Entwicklung, Staging, Produktion) oder Sensitivitätsstufe kategorisieren. Dadurch lassen sich Secrets in Secret Manager einfacher suchen, filtern und organisieren.

  • Gibt das spezifische Format oder die Struktur des geheimen Werts an, damit die Arbeitslast ihn richtig interpretieren kann.

  • Hinweise zur Verwendung des Secrets oder besondere Überlegungen zum Umgang damit.

Wenn Sie beispielsweise ein Secret mit einem Datenbankpasswort haben, können Sie Annotationen wie die folgenden hinzufügen:

  • environment:production

  • purpose:database_access

  • owner:database_team

Mithilfe dieser Anmerkungen lässt sich der Zweck des Secrets, seine Umgebung und die dafür verantwortliche Person leicht ermitteln. Außerdem kann eine Arbeitslast, die auf dieses Secret zugreift, anhand der Anmerkungen bestätigen, dass sie das richtige Passwort für die Produktionsumgebung verwendet.

Hinweise sind nicht dasselbe wie Labels. Labels werden zum Sortieren, Filtern und Gruppieren von Ressourcen verwendet, während mit Annotationen beliebige, nicht identifizierbare Metadaten in einem Secret gespeichert werden. Beim Angeben von Metadaten in einem Label gibt es eine Beschränkung für Zeichen und Zeichenlänge. Die Metadaten in einer Annotation können begrenzt oder umfangreich, strukturiert oder unstrukturiert sein sowie Zeichen enthalten, die für Labels nicht zulässig sind.

Erforderliche Rollen

  • Zum Hinzufügen von Anmerkungen zu einem Secret und zum Aktualisieren von Anmerkungen ist die Rolle „Secret Manager Admin“ (roles/secretmanager.admin) für das Secret, das Projekt, den Ordner oder die Organisation erforderlich.

  • Wenn Sie Anmerkungen aufrufen möchten, benötigen Sie die Rolle „Secret Manager-Betrachter“ (roles/secretmanager.viewer) für das Secret, das Projekt, den Ordner oder die Organisation.

IAM-Rollen (Identity and Access Management) können in einer Secret-Version nicht zugewiesen werden. Weitere Informationen finden Sie unter Zugriffssteuerung mit IAM.

Einem Secret Anmerkungen hinzufügen

Sie können Anmerkungen hinzufügen, wenn Sie ein neues Secret erstellen oder ein vorhandenes Secret aktualisieren. Die Metadaten in einer Anmerkung werden als Schlüssel/Wert-Paare gespeichert. Sie haben folgende Möglichkeiten, Anmerkungen hinzuzufügen:

Console

  1. Rufen Sie in der Google Cloud Console die Seite Secret Manager auf.

    Zu Secret Manager

  2. Klicken Sie auf der Seite Secret Manager auf Secret erstellen.

  3. Geben Sie auf der Seite Secret erstellen im Feld Name einen Namen für das Secret ein.

  4. Geben Sie einen Wert für das Secret ein (z. B. abcd1234). Sie können auch eine Textdatei mit dem Secret-Wert über die Option Datei hochladen hochladen. Durch diese Aktion wird die Secret-Version automatisch erstellt.

  5. Rufen Sie den Bereich Anmerkungen auf und klicken Sie auf Anmerkung hinzufügen.

  6. Geben Sie den Schlüssel und den entsprechenden Wert ein.

  7. Klicken Sie auf Secret erstellen.

gcloud

Ersetzen Sie folgende Werte, bevor sie einen der Befehlsdaten verwenden:

  • SECRET_ID: die ID des Secrets
  • KEY: der Annotationsschlüssel
  • VALUE: der entsprechende Wert des Anmerkungsschlüssels

Führen Sie folgenden Befehl aus:

Linux, macOS oder Cloud Shell

gcloud secrets create SECRET_ID \
    --set-annotations= KEY1=VAL1,KEY2=VAL2

Windows (PowerShell)

gcloud secrets create SECRET_ID `
    --set-annotations= KEY1=VAL1,KEY2=VAL2

Windows (cmd.exe)

gcloud secrets create SECRET_ID ^
    --set-annotations= KEY1=VAL1,KEY2=VAL2

Die Antwort enthält das Secret und die Anmerkungen.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_ID: die Google Cloud Projekt-ID
  • SECRET_ID: die ID des Secrets
  • KEY: der Annotationsschlüssel
  • VALUE: der entsprechende Wert des Anmerkungsschlüssels

HTTP-Methode und URL:

PATCH https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID?updateMask=annotations

JSON-Text der Anfrage:

{'annotations': {'KEY1': 'VALUE1', 'KEY2': 'VALUE2' }}

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID?updateMask=annotations"

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

$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.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID?updateMask=annotations" | Select-Object -Expand Content

Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-09-02T07:14:00.281541Z",
  "etag": "\"16211dcd99c386\"",
  "annotations": {
    "key1": "value1",
    "key2": "value2"
  }
}

C#

Um diesen Code auszuführen, müssen Sie eine C#-Entwicklungsumgebung einrichten und das Secret Manager C# SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;
using System.Collections.Generic;

public class CreateSecretWithAnnotationsSample
{
    public Secret CreateSecretWithAnnotations(
      string projectId = "my-project", string secretId = "my-secret", string annotationKey = "my-annotation-key", string annotationValue = "my-annotation-value")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

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

        // Build the secret.
        Secret secret = new Secret
        {
            Replication = new Replication
            {
                Automatic = new Replication.Types.Automatic(),
            },
            Annotations =
            {
              { annotationKey, annotationValue }
            },
        };

        // Call the API.
        Secret createdSecret = client.CreateSecret(projectName, secretId, secret);
        return createdSecret;
    }
}

Go

Um diesen Code auszuführen, müssen Sie zuerst eine Go-Entwicklungsumgebung einrichten und das Secret Manager Go SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

import (
	"context"
	"fmt"
	"io"

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

// createSecretWithAnnotations creates a new secret with the given name and annotations.
func createSecretWithAnnotations(w io.Writer, parent, secretId string) error {
	// parent := "projects/my-project"
	// id := "my-secret"

	annotationKey := "annotationkey"
	annotationValue := "annotationvalue"

	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.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: secretId,
		Secret: &secretmanagerpb.Secret{
			Replication: &secretmanagerpb.Replication{
				Replication: &secretmanagerpb.Replication_Automatic_{
					Automatic: &secretmanagerpb.Replication_Automatic{},
				},
			},
			Annotations: map[string]string{
				annotationKey: annotationValue,
			},
		},
	}

	result, err := client.CreateSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create secret: %w", err)
	}
	fmt.Fprintf(w, "Created secret with annotations: %s\n", result.Name)
	return nil
}

Java

Um diesen Code auszuführen, müssen Sie zuerst eine Java-Entwicklungsumgebung einrichten und das Secret Manager Java SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

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

public class CreateSecretWithAnnotations {

  public static void createSecretWithAnnotations() 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 annotation to be added
    String annotationKey = "your-annotation-key";
    // This is the value of the annotation to be added
    String annotationValue = "your-annotation-value";
    createSecretWithAnnotations(projectId, secretId, annotationKey, annotationValue);
  }

  // Create a secret with annotations.
  public static Secret createSecretWithAnnotations(
       String projectId,
       String secretId,
       String annotationKey,
       String annotationValue
  ) 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.
      ProjectName projectName = ProjectName.of(projectId);

      // Build the secret to create with labels.
      Secret secret =
          Secret.newBuilder()
                  .setReplication(
                  Replication.newBuilder()
                      .setAutomatic(Replication.Automatic.newBuilder().build())
                      .build())
                  .putAnnotations(annotationKey, annotationValue)
              .build();

      // Create the secret.
      Secret createdSecret = client.createSecret(projectName, secretId, secret);
      System.out.printf("Created secret %s\n", createdSecret.getName());
      return createdSecret;
    }
  }
}

Node.js

Um diesen Code auszuführen, müssen Sie zuerst eine Node.js-Entwicklungsumgebung einrichten und das Cloud KMS Node.js SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

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

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

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

async function createSecretWithAnnotations() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: {
      replication: {
        automatic: {},
      },
      annotations: {
        [annotationKey]: annotationValue,
      },
    },
  });

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

createSecretWithAnnotations();

PHP

Um diesen Code auszuführen, müssen Sie zuerst die Informationen zur Verwendung von PHP in Google Cloud und zum Installieren des Secret Manager PHP SDK lesen. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

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

/**
 * @param string $projectId       Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId        Your secret ID (e.g. 'my-secret')
 * @param string $annotationKey   Your annotation key (e.g. 'annotation-key')
 * @param string $annotationValue Your annotation value (e.g. 'annotation-value')
 */
function create_secret_with_annotations(string $projectId, string $secretId, string $annotationKey, string $annotationValue): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

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

    $secret = new Secret([
        'replication' => new Replication([
            'automatic' => new Automatic(),
        ]),
    ]);

    // set the annoation.
    $annotation = [$annotationKey => $annotationValue];
    $secret->setAnnotations($annotation);

    // Build the request.
    $request = CreateSecretRequest::build($parent, $secretId, $secret);

    // Create the secret.
    $newSecret = $client->createSecret($request);

    // Print the new secret name.
    printf('Created secret %s with annotations', $newSecret->getName());
}

Python

Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Secret Manager Python SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

import argparse
import typing

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


def create_secret_with_annotations(
    project_id: str,
    secret_id: str,
    annotations: typing.Dict[str, str],
) -> secretmanager.Secret:
    """
    Create a new secret with the given name. A secret is a logical wrapper
    around a collection of secret versions. Secret versions hold the actual
    secret material.
    """

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent project.
    parent = f"projects/{project_id}"

    # Create the secret.
    response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
            "secret": {
                "replication": {"automatic": {}},
                "annotations": annotations,
            },
        }
    )

    # Print the new secret name.
    print(f"Created secret: {response.name}")

    return response

Ruby

Um diesen Code auszuführen, müssen Sie zuerst eine Ruby-Entwicklungsumgebung einrichten und das Secret Manager Ruby SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

require "google/cloud/secret_manager"

##
# Create a secret with annotation.
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param secret_id [String] Your secret name (e.g. "my-secret")
# @param annotation_key [String] Your annotation key (e.g. "my-annotation-key")
# @param annotation_value [String] Your annotation value (e.g. "my-annotation-value")
#
def create_secret_with_annotations project_id:, secret_id:, annotation_key:, annotation_value:
  # Create a Secret Manager client.
  client = Google::Cloud::SecretManager.secret_manager_service

  # Build the resource name of the parent project.
  parent = client.project_path project: project_id

  # Create the secret.
  secret = client.create_secret(
    parent:    parent,
    secret_id: secret_id,
    secret:    {
      replication: {
        automatic: {}
      },
      annotations: {
        annotation_key => annotation_value
      }
    }
  )

  # Print the new secret name.
  puts "Created secret: #{secret.name}"
end

Informationen zum Hinzufügen von Anmerkungen zu einem vorhandenen Secret finden Sie in diesem Dokument im Abschnitt Anmerkungen bearbeiten.

Für Anmerkungsschlüssel gelten die folgenden Anforderungen:

  • Schlüssel müssen für ein Secret eindeutig sein. Sie können einen Schlüssel nicht mehrmals im selben Secret verwenden.

  • Schlüssel müssen zwischen 1 und 63 Zeichen lang sein.

  • Schlüssel müssen eine UTF-8-Codierung von maximal 128 Byte aufweisen.

  • Schlüssel müssen mit einem alphanumerischen Zeichen beginnen und enden.

  • Schlüssel können Bindestriche, Unterstriche und Punkte zwischen den alphanumerischen Zeichen enthalten.

  • Die Gesamtgröße der Anmerkungsschlüssel und ‑werte muss kleiner als 16 KiB sein.

Anmerkungen bearbeiten

Sie haben folgende Möglichkeiten, Anmerkungen zu bearbeiten:

Console

  1. Rufen Sie in der Google Cloud Console die Seite Secret Manager auf.

    Zu Secret Manager

  2. Suchen Sie in der Liste nach dem Secret und klicken Sie auf das Menü Aktionen, das mit diesem Secret verknüpft ist. Klicken Sie im Menü Aktionen auf Bearbeiten.

  3. Rufen Sie auf der Seite Secret bearbeiten den Bereich Hinweise auf. Hier können Sie den Wert einer vorhandenen Anmerkung ändern, die Anmerkung löschen oder eine neue Anmerkung hinzufügen.

  4. Klicken Sie nach den Änderungen auf Geheimnis aktualisieren.

gcloud

Vorhandene Anmerkungen bearbeiten

Ersetzen Sie folgende Werte, bevor sie einen der Befehlsdaten verwenden:

  • SECRET_ID: die ID des Secrets
  • KEY: der Annotationsschlüssel
  • VALUE: der entsprechende Wert des Anmerkungsschlüssels

Führen Sie folgenden Befehl aus:

Linux, macOS oder Cloud Shell

gcloud secrets update SECRET_ID --update-annotations= KEY=VAL

Windows (PowerShell)

gcloud secrets update SECRET_ID --update-annotations= KEY=VAL

Windows (cmd.exe)

gcloud secrets update SECRET_ID --update-annotations= KEY=VAL

In der Antwort werden das Secret und die Annotationen bearbeitet.

Bestimmte Anmerkung entfernen

Verwenden Sie den folgenden Befehl, um Annotationen zu entfernen:

gcloud secrets update SECRET_ID --remove-annotations= KEY=VAL

Alle Anmerkungen löschen

Verwenden Sie den folgenden Befehl, um alle Annotationen zu löschen:

gcloud secrets update SECRET_ID --clear-annotations

REST

Verwenden Sie den folgenden Befehl, um alle Annotationen zu löschen:

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_ID: die Google Cloud Projekt-ID
  • SECRET_ID: die ID des Secrets

HTTP-Methode und URL:

PATCH https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID?updateMask=annotations

JSON-Text der Anfrage:

{'annotations': {}}

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID?updateMask=annotations"

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

$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.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID?updateMask=annotations" | Select-Object -Expand Content

Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-09-02T07:14:00.281541Z",
  "etag": "\"16211dd90b37e7\""
}

C#

Um diesen Code auszuführen, müssen Sie eine C#-Entwicklungsumgebung einrichten und das Secret Manager C# SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;
using Google.Protobuf.Collections;
using Google.Protobuf.WellKnownTypes;

public class EditSecretAnnotationsSample
{
    public Secret EditSecretAnnotations(
      string projectId = "my-project", string secretId = "my-secret", string annotationKey = "my-annotation-key", string annotationValue = "my-annotation-value")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the secretName with the fields.
        SecretName secretName = new SecretName(projectId, secretId);

        // Get the exisitng secret.
        Secret secret = client.GetSecret(secretName);

        // Edit the Secret annotations
        secret.Annotations[annotationKey] = annotationValue;

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

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

Go

Um diesen Code auszuführen, müssen Sie zuerst eine Go-Entwicklungsumgebung einrichten und das Secret Manager Go SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

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

// editSecretAnnotation updates the annotations about an existing secret.
// If the annotation key exists, it updates the annotation, otherwise it creates a new one.
func editSecretAnnotation(w io.Writer, secretName string) error {
	// name := "projects/my-project/secrets/my-secret"

	annotationKey := "annotationkey"
	annotationValue := "updatedannotationvalue"

	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: secretName,
	}

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

	annotations := result.Annotations

	annotations[annotationKey] = annotationValue

	// Build the request to update the secret.
	update_req := &secretmanagerpb.UpdateSecretRequest{
		Secret: &secretmanagerpb.Secret{
			Name:        secretName,
			Annotations: annotations,
		},
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"annotations"},
		},
	}

	update_result, err := client.UpdateSecret(ctx, update_req)
	if err != nil {
		return fmt.Errorf("failed to update secret: %w", err)
	}
	fmt.Fprintf(w, "Updated secret: %s\n", update_result.Name)
	return nil
}

Java

Um diesen Code auszuführen, müssen Sie zuerst eine Java-Entwicklungsumgebung einrichten und das Secret Manager Java SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

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;
import java.util.HashMap;
import java.util.Map;

public class EditSecretAnnotations {

  public static void editSecretAnnotations() 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 annotation to be added/updated
    String annotationKey = "your-annotation-key";
    // This is the value of the annotation to be added/updated
    String annotationValue = "your-annotation-value";
    editSecretAnnotations(projectId, secretId, annotationKey, annotationValue);
  }

  // Update an existing secret, by creating a new annotation or updating an existing annotation.
  public static Secret editSecretAnnotations(
       String projectId,
       String secretId,
       String annotationKey,
       String annotationValue
  ) 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> existingAnnotationsMap = 
                      new HashMap<String, String>(existingSecret.getAnnotationsMap());

      // Add a new annotation key and value.
      existingAnnotationsMap.put(annotationKey, annotationValue);

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

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

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

      return updatedSecret;
    }
  }
}

Node.js

Um diesen Code auszuführen, müssen Sie zuerst eine Node.js-Entwicklungsumgebung einrichten und das Cloud KMS Node.js SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

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

// 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 editSecretAnnotations() {
  const oldSecret = await getSecret();
  oldSecret.annotations[annotationKey] = annotationValue;
  const [secret] = await client.updateSecret({
    secret: {
      name: name,
      annotations: oldSecret.annotations,
    },
    updateMask: {
      paths: ['annotations'],
    },
  });

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

editSecretAnnotations();

PHP

Um diesen Code auszuführen, müssen Sie zuerst die Informationen zur Verwendung von PHP in Google Cloud und zum Installieren des Secret Manager PHP SDK lesen. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

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

/**
 * @param string $projectId       Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId        Your secret ID (e.g. 'my-secret')
 * @param string $annotationKey   Your annotation key (e.g. 'annotation-key')
 * @param string $annotationValue Your annotation value (e.g. 'annotation-value')
 */
function edit_secret_annotations(string $projectId, string $secretId, string $annotationKey, string $annotationValue): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

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

    // Build the request.
    $request = GetSecretRequest::build($name);

    // get the secret.
    $getSecret = $client->getSecret($request);

    // get the annotations
    $annotations = $getSecret->getAnnotations();

    // update the annotation - need to create a new annotations map with the updated values
    $newAnnotations = [];
    foreach ($annotations as $key => $value) {
        $newAnnotations[$key] = $value;
    }
    $newAnnotations[$annotationKey] = $annotationValue;
    $getSecret->setAnnotations($newAnnotations);

    // set the field mask
    $fieldMask = new FieldMask();
    $fieldMask->setPaths(['annotations']);

    // build the secret
    $request = new UpdateSecretRequest();
    $request->setSecret($getSecret);
    $request->setUpdateMask($fieldMask);

    // update the secret
    $updateSecret = $client->updateSecret($request);

    // print the updated secret
    printf('Updated secret %s annotations' . PHP_EOL, $updateSecret->getName());
}

Python

Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Secret Manager Python SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.


import argparse
from typing import Dict

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


def edit_secret_annotations(
    project_id: str, secret_id: str, new_annotations: Dict[str, str]
) -> secretmanager.UpdateSecretRequest:
    """
    Create or update a annotation 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})

    annotations = response.annotations

    # Update the annotations
    for annotation_key in new_annotations:
        annotations[annotation_key] = new_annotations[annotation_key]

    # Update the secret.
    secret = {"name": name, "annotations": annotations}
    update_mask = {"paths": ["annotations"]}
    response = client.update_secret(
        request={"secret": secret, "update_mask": update_mask}
    )

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

    return response

Ruby

Um diesen Code auszuführen, müssen Sie zuerst eine Ruby-Entwicklungsumgebung einrichten und das Secret Manager Ruby SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

require "google/cloud/secret_manager"

##
# Edits a secret annotations.
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param secret_id [String] Your secret name (e.g. "my-secret")
# @param annotation_key [String] Your annotation key (e.g. "my-annotation-key")
# @param annotation_value [String] Your annotation value (e.g. "my-annotation-value")
#
def edit_secret_annotations project_id:, secret_id:, annotation_key:, annotation_value:
  # 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 existing secret.
  existing_secret = client.get_secret name: name

  # Get the existing secret's annotations.
  existing_secret_annotations = existing_secret.annotations.to_h

  # Add a new annotation key and value.
  existing_secret_annotations[annotation_key] = annotation_value

  # Updates the secret.
  secret = client.update_secret(
    secret: {
      name: name,
      annotations: existing_secret_annotations
    },
    update_mask: {
      paths: ["annotations"]
    }
  )

  # Print the updated secret name and annotations.
  puts "Updated secret: #{secret.name}"
  puts "New updated annotations: #{secret.annotations}"
end

Anmerkungen ansehen

Verwenden Sie eine der folgenden Methoden, um Anmerkungen zu einem Secret aufzurufen:

Console

  1. Rufen Sie in der Google Cloud Console die Seite Secret Manager auf.

    Zu Secret Manager

  2. Klicken Sie auf der Seite Secret Manager auf das Secret, dessen Anmerkungen Sie sich ansehen möchten.

  3. Die Seite mit den Secret-Details wird geöffnet. Klicken Sie auf den Tab Übersicht. Hier sehen Sie die Vermerke, die dem Secret angehängt sind. Die Schlüssel werden in der linken Spalte aufgeführt, die Werte in der rechten.

gcloud

Ersetzen Sie folgende Werte, bevor sie einen der Befehlsdaten verwenden:

  • SECRET_ID: die ID des Secrets

Führen Sie folgenden Befehl aus:

Linux, macOS oder Cloud Shell

gcloud secrets describe SECRET_ID

Windows (PowerShell)

gcloud secrets describe SECRET_ID

Windows (cmd.exe)

gcloud secrets describe SECRET_ID

Die Antwort enthält das Secret und die Anmerkungen.

REST

Ersetzen Sie diese Werte in den folgenden Anfragedaten:

  • PROJECT_ID: die Google Cloud Projekt-ID
  • SECRET_ID: die ID des Secrets

HTTP-Methode und URL:

GET https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID

JSON-Text der Anfrage:

{}

Wenn Sie die Anfrage senden möchten, wählen Sie eine der folgenden Optionen aus:

curl

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID"

PowerShell

Speichern Sie den Anfragetext in einer Datei mit dem Namen request.json und führen Sie den folgenden Befehl aus:

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID" | Select-Object -Expand Content

Sie sollten eine JSON-Antwort ähnlich wie diese erhalten:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-09-02T07:14:00.281541Z",
  "etag": "\"16211dcd99c386\"",
  "annotations": {
    "key1": "value1",
    "key2": "value2"
  }
}

C#

Um diesen Code auszuführen, müssen Sie eine C#-Entwicklungsumgebung einrichten und das Secret Manager C# SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;
using Google.Protobuf.Collections;
using Google.Protobuf.WellKnownTypes;
using System;

public class ViewSecretAnnotationsSample
{
    public Secret ViewSecretAnnotations(
      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);

        // Fetch the secret.
        Secret secret = client.GetSecret(secretName);

        // Get the secret's annotations.
        MapField<string, string> secretAnnotations = secret.Annotations;

        // Print the annotations.
        foreach (var annotation in secret.Annotations)
        {
            Console.WriteLine($"Annotation Key: {annotation.Key}, Annotation Value: {annotation.Value}");
        }
        return secret;
    }
}

Go

Um diesen Code auszuführen, müssen Sie zuerst eine Go-Entwicklungsumgebung einrichten und das Secret Manager Go SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

import (
	"context"
	"fmt"
	"io"

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

// viewSecretAnnotations gets annotations with the given secret.
func viewSecretAnnotations(w io.Writer, secretName string) error {
	// name := "projects/my-project/secrets/my-secret"

	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.
	req := &secretmanagerpb.GetSecretRequest{
		Name: secretName,
	}

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

	annotations := result.Annotations
	fmt.Fprintf(w, "Found secret %s\n", result.Name)

	for key, value := range annotations {
		fmt.Fprintf(w, "Annotations key %s : Annotations Value %s", key, value)
	}
	return nil
}

Java

Um diesen Code auszuführen, müssen Sie zuerst eine Java-Entwicklungsumgebung einrichten und das Secret Manager Java SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

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;
import java.util.Map;

public class ViewSecretAnnotations {

  public static void viewSecretAnnotations() 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 whose annotations to view
    String secretId = "your-secret-id";
    viewSecretAnnotations(projectId, secretId);
  }

  // View the annotations of an existing secret.
  public static Map<String, String> viewSecretAnnotations(
      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.
    try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
      // Build the name.
      SecretName secretName = SecretName.of(projectId, secretId);

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

      Map<String, String> annotations = secret.getAnnotationsMap();

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

      for (Map.Entry<String, String> annotation : annotations.entrySet()) {
        System.out.printf("Annotation key : %s, Annotation Value : %s\n", 
            annotation.getKey(), annotation.getValue());
      }

      return secret.getAnnotationsMap();
    }
  }
}

Node.js

Um diesen Code auszuführen, müssen Sie zuerst eine Node.js-Entwicklungsumgebung einrichten und das Cloud KMS Node.js SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const parent = '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 viewSecretAnnotations() {
  const [secret] = await client.getSecret({
    name: name,
  });

  for (const key in secret.annotations) {
    console.log(`${key} : ${secret.annotations[key]}`);
  }
}

viewSecretAnnotations();

PHP

Um diesen Code auszuführen, müssen Sie zuerst die Informationen zur Verwendung von PHP in Google Cloud und zum Installieren des Secret Manager PHP SDK lesen. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

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

/**
 * @param string $projectId Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId  Your secret ID (e.g. 'my-secret')
 */
function view_secret_annotations(string $projectId, string $secretId): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

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

    // Build the request.
    $request = GetSecretRequest::build($name);

    // get the secret.
    $getSecret = $client->getSecret($request);

    // get the annotations
    $annotations = $getSecret->getAnnotations();

    // print the secret name
    printf('Get secret %s with annotation:' . PHP_EOL, $getSecret->getName());
    // we can even loop over all the annotations
    foreach ($annotations as $key => $val) {
        printf("\t$key: $val" . PHP_EOL);
    }
}

Python

Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Secret Manager Python SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

import argparse

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


def view_secret_annotations(project_id: str, secret_id: str) -> None:
    """
    List all secret annotations in the given secret.
    """
    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent secret.
    name = client.secret_path(project_id, secret_id)

    response = client.get_secret(request={"name": name})

    print(f"Got secret {response.name} with annotations :")
    for key in response.annotations:
        print(f"{key} : {response.annotations[key]}")

Ruby

Um diesen Code auszuführen, müssen Sie zuerst eine Ruby-Entwicklungsumgebung einrichten und das Secret Manager Ruby SDK installieren. In Compute Engine oder GKE müssen Sie sich mit dem Bereich cloud-platform authentifizieren.

require "google/cloud/secret_manager"

##
# View annotations of a secret.
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param secret_id [String] Your secret name (e.g. "my-secret")
#
def view_secret_annotations project_id:, secret_id:
  # 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 existing secret.
  existing_secret = client.get_secret name: name

  # Get the existing secret's annotations.
  existing_secret_annotations = existing_secret.annotations.to_h

  # Print the secret name and the annotations.
  puts "Secret: #{existing_secret.name}"
  existing_secret_annotations.each do |key, value|
    puts "Annotation Key: #{key}, Annotation Value: #{value}"
  end
end

Nächste Schritte