Recupera il secret regionale

Recupera il secret regionale

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, consulta quanto segue:

Esempio di codice

Go

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

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

// getSecret gets information about the given secret. This only returns metadata
// about the secret container, not any secret material.
func GetRegionalSecret(w io.Writer, projectId, locationId, secretId string) error {
	// name := "projects/my-project/locations/my-location/secrets/my-secret"

	// Create the client.
	ctx := context.Background()
	//Endpoint to send the request to regional server
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationId)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))

	if err != nil {
		return fmt.Errorf("failed to create regional secretmanager client: %w", err)
	}
	defer client.Close()

	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s", projectId, locationId, secretId)
	// 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)
	}

	fmt.Fprintf(w, "Found regional secret %s \n", result.Name)
	return nil
}

Java

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

public class GetRegionalSecret {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Your GCP project ID.
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // Resource ID of the secret you want to retrieve.
    String secretId = "your-secret-id";
    getRegionalSecret(projectId, locationId, secretId);
  }

  // Get an existing secret.
  public static Secret getRegionalSecret(
      String projectId, String locationId, String secretId) 
      throws IOException {

    // Endpoint to call the regional secret manager sever
    String apiEndpoint = String.format("secretmanager.%s.rep.googleapis.com:443", locationId);
    SecretManagerServiceSettings secretManagerServiceSettings =
        SecretManagerServiceSettings.newBuilder().setEndpoint(apiEndpoint).build();

    // Initialize the 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(secretManagerServiceSettings)) {
      // Build the name.
      SecretName secretName = 
          SecretName.ofProjectLocationSecretName(projectId, locationId, secretId);

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

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

      return secret;
    }
  }
}

Node.js

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'my-location';
// const secretId = 'my-secret';

const name = `projects/${projectId}/locations/${locationId}/secrets/${secretId}`;

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

// Adding the endpoint to call the regional secret manager sever
const options = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;

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

async function getRegionalSecret() {
  const [secret] = await client.getSecret({
    name: name,
  });

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

getRegionalSecret();

PHP

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

// 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 $locationId Your secret Location (e.g. "us-central1")
 * @param string $secretId  Your secret ID (e.g. 'my-secret')
 */
function get_regional_secret(string $projectId, string $locationId, string $secretId): void
{
    // Specify regional endpoint.
    $options = ['apiEndpoint' => "secretmanager.$locationId.rep.googleapis.com"];

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

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

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

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

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

Ruby

Per scoprire come installare e utilizzare la libreria client per Secret Manager, consulta Librerie client di Secret Manager.

Per autenticarti in Secret Manager, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

# project_id  = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# location_id = "YOUR-GOOGLE-CLOUD-LOCATION" # (e.g. "us-west1")
# secret_id   = "YOUR-SECRET-ID"             # (e.g. "my-secret")

# Require the Secret Manager client library.
require "google/cloud/secret_manager"

# Endpoint for the regional secret manager service.
api_endpoint = "secretmanager.#{location_id}.rep.googleapis.com"

# Create the Secret Manager client.
client = Google::Cloud::SecretManager.secret_manager_service do |config|
  config.endpoint = api_endpoint
end

# Build the resource name of the secret.
name = client.secret_path project: project_id, location: location_id, secret: secret_id

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

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

Passaggi successivi

Per cercare e filtrare i sample di codice per altri Google Cloud prodotti, consulta il Google Cloud browser di sample.