Elenca i secret e visualizza i relativi dettagli

In Secret Manager, un secret funge da contenitore per più versioni di secret. Contiene informazioni importanti come etichette e impostazioni di rotazione, ma non il valore segreto stesso. Questa pagina spiega come recuperare un elenco di tutti i secret all'interno di un progetto e visualizzare i metadati associati a ciascun secret.

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per elencare i secret e visualizzarne i metadati, chiedi all'amministratore di concederti il ruolo IAM Visualizzatore Secret Manager (roles/secretmanager.viewer) per il progetto, la cartella o l'organizzazione. Per ulteriori informazioni sulla concessione dei ruoli, consulta Gestire l'accesso a progetti, cartelle e organizzazioni.

Potresti anche riuscire a ottenere le autorizzazioni richieste tramite i ruoli personalizzati o altri ruoli predefiniti.

Elenco secret

Per recuperare un elenco di tutti i secret all'interno di un progetto, utilizza uno dei seguenti metodi:

Console

  1. Nella console Google Cloud, vai alla pagina Secret Manager.

    Vai a Secret Manager

  2. Controlla l'elenco dei secret nel progetto. Puoi fare clic su un secret per visualizzarne i metadati.

gcloud

Prima di utilizzare i dati dei comandi riportati di seguito, effettua le seguenti sostituzioni:

Esegui il seguente comando:

Linux, macOS o Cloud Shell

gcloud secrets list

Windows (PowerShell)

gcloud secrets list

Windows (cmd.exe)

gcloud secrets list

La risposta restituisce l'elenco dei secret e delle relative versioni.

REST

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • PROJECT_ID: l'ID Google Cloud progetto

Metodo HTTP e URL:

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

Corpo JSON della richiesta:

{}

Per inviare la richiesta, scegli una delle seguenti opzioni:

curl

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

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"

PowerShell

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

$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" | Select-Object -Expand Content

Dovresti ricevere una risposta JSON simile alla seguente:

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

C#

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo C# e installare l'SDK C# di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.


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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Go e installare l'SDK Go di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

import (
	"context"
	"fmt"
	"io"

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

// 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: %w", err)
	}
	defer client.Close()

	// 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 secrets: %w", err)
		}

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

	return nil
}

Java

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Java e installare l'SDK Java di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

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 static 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 static 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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Node.js e installare l'SDK Node.js di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

/**
 * 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.userManaged
      ? secret.replication.userManaged
      : secret.replication.automatic;
    console.log(`${secret.name} (${policy})`);
  });
}

listSecrets();

PHP

Per eseguire questo codice, devi innanzitutto scoprire come utilizzare PHP su Google Cloud e installare l'SDK PHP di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

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

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

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

    // Build the request.
    $request = ListSecretsRequest::build($parent);

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

Python

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Python e installare l'SDK Python di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

def list_secrets(project_id: str) -> None:
    """
    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(f"Found secret: {secret.name}")

Ruby

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Ruby e installare l'SDK Ruby di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

# 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

Visualizza dettagli del secret

Per visualizzare i metadati di un segreto, utilizza uno dei seguenti metodi:

Console

  1. Nella console Google Cloud, vai alla pagina Secret Manager.

    Vai a Secret Manager

  2. Fai clic sul segreto di cui vuoi visualizzare i dettagli.

  3. Nella pagina dei dettagli del secret, fai clic sulla scheda Panoramica. Questa scheda mostra i dettagli generali e i metadati associati al segreto.

gcloud

Prima di utilizzare i dati dei comandi riportati di seguito, effettua le seguenti sostituzioni:

  • SECRET_ID: l'ID della secret o l'identificatore completo della secret

Esegui il seguente comando:

Linux, macOS o Cloud Shell

gcloud secrets describe SECRET_ID

Windows (PowerShell)

gcloud secrets describe SECRET_ID

Windows (cmd.exe)

gcloud secrets describe SECRET_ID

La risposta restituisce il segreto.

REST

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • PROJECT_ID: l' Google Cloud ID progetto
  • SECRET_ID: l'ID della secret o l'identificatore completo della secret

Metodo HTTP e URL:

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

Corpo JSON della richiesta:

{}

Per inviare la richiesta, scegli una delle seguenti opzioni:

curl

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

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

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

$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

Dovresti ricevere una risposta JSON simile alla seguente:

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

C#

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo C# e installare l'SDK C# di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.


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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Go e installare l'SDK Go di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

import (
	"context"
	"fmt"
	"io"

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

// 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: %w", err)
	}
	defer client.Close()

	// 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: %w", err)
	}

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

Java

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Java e installare l'SDK Java di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

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 static 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 static 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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Node.js e installare l'SDK Node.js di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

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

Per eseguire questo codice, devi innanzitutto scoprire come utilizzare PHP su Google Cloud e installare l'SDK PHP di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

// 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 get_secret(string $projectId, string $secretId): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

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

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

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

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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Python e installare l'SDK Python di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

def get_secret(project_id: str, secret_id: str) -> secretmanager.GetSecretRequest:
    """
    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 Exception(f"Unknown replication {response.replication}")

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

Ruby

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Ruby e installare l'SDK Ruby di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito cloud-platform.

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

Passaggi successivi