Crear un secreto regional

En esta página se describe cómo crear un secreto regional. Un secreto contiene una o varias versiones del secreto, así como metadatos como etiquetas y anotaciones. El contenido real de un secreto se almacena en una versión de secreto.

Antes de empezar

  1. Habilita la API Secret Manager.

  2. Configura Secret Manager para que use un endpoint regional.

  3. Configura la autenticación.

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

    REST

    Para usar las muestras de la API REST de esta página en un entorno de desarrollo local, debes usar las credenciales que proporciones a la CLI de gcloud.

      Instala Google Cloud CLI. Después de la instalación, inicializa la CLI de Google Cloud ejecutando el siguiente comando:

      gcloud init

      Si utilizas un proveedor de identidades (IdP) externo, primero debes iniciar sesión en la CLI de gcloud con tu identidad federada.

    Para obtener más información, consulta el artículo Autenticarse para usar REST de la documentación sobre autenticación de Google Cloud .

    Roles obligatorios

    Para obtener los permisos que necesitas para crear un secreto, pide a tu administrador que te conceda el rol de gestión de identidades y accesos Administrador de Secret Manager (roles/secretmanager.admin) en el proyecto, la carpeta o la organización. Para obtener más información sobre cómo conceder roles, consulta el artículo Gestionar el acceso a proyectos, carpetas y organizaciones.

    También puedes conseguir los permisos necesarios a través de roles personalizados u otros roles predefinidos.

    Crear un secreto regional

    Puedes crear secretos con la Google Cloud consola, la CLI de Google Cloud, la API Secret Manager o las bibliotecas de cliente de Secret Manager.

    Consola

    1. En la Google Cloud consola, ve a la página Secret Manager.

      Ir a Secret Manager

    2. En la página Secret Manager, haz clic en la pestaña Secretos regionales y, a continuación, en Crear secreto regional.

    3. En la página Crear secreto regional, introduce un nombre para el secreto en el campo Nombre. El nombre del secreto puede contener letras mayúsculas y minúsculas, números, guiones y guiones bajos. La longitud máxima permitida para el nombre es de 255 caracteres.

    4. Introduce un valor para el secreto (por ejemplo, abcd1234). El valor del secreto puede estar en cualquier formato, pero no debe superar los 64 KiB. También puedes subir un archivo de texto que contenga el valor del secreto con la opción Subir archivo. Esta acción crea automáticamente la versión del secreto.

    5. En la lista Región, elige la ubicación en la que quieres que se almacene tu secreto regional.

    6. Haz clic en Crear secreto.

    gcloud

    Antes de usar los datos de los comandos que se indican a continuación, haz los siguientes cambios:

    • SECRET_ID: el ID del secreto.
    • LOCATION: la Google Cloud ubicación del secreto.

    Ejecuta el siguiente comando:

    Linux, macOS o Cloud Shell

    gcloud secrets create SECRET_ID \
        --location=LOCATION

    Windows (PowerShell)

    gcloud secrets create SECRET_ID `
        --location=LOCATION

    Windows (cmd.exe)

    gcloud secrets create SECRET_ID ^
        --location=LOCATION

    REST

    Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

    • LOCATION: la Google Cloud ubicación del secreto.
    • PROJECT_ID: el ID del proyecto. Google Cloud
    • SECRET_ID: el ID del secreto.

    Método HTTP y URL:

    POST https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?secretId=SECRET_ID

    Cuerpo JSON de la solicitud:

    {}
    

    Para enviar tu solicitud, elige una de estas opciones:

    curl

    Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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

    PowerShell

    Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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

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

    Deberías recibir una respuesta JSON similar a la siguiente:

    {
      "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
      "createTime": "2024-03-25T08:24:13.153705Z",
      "etag": "\"161477e6071da9\""
    }
    

    Go

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	secretmanager "cloud.google.com/go/secretmanager/apiv1"
    	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
    	"google.golang.org/api/option"
    )
    
    // createSecret creates 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.
    func CreateRegionalSecret(w io.Writer, projectId, locationId, id string) error {
    	// parent := "projects/my-project/locations/my-location"
    	// id := "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 secretmanager client: %w", err)
    	}
    	defer client.Close()
    
    	parent := fmt.Sprintf("projects/%s/locations/%s", projectId, locationId)
    
    	// Build the request.
    	req := &secretmanagerpb.CreateSecretRequest{
    		Parent:   parent,
    		SecretId: id,
    	}
    
    	// Call the API.
    	result, err := client.CreateSecret(ctx, req)
    	if err != nil {
    		return fmt.Errorf("failed to create regional secret: %w", err)
    	}
    	fmt.Fprintf(w, "Created regional secret: %s\n", result.Name)
    	return nil
    }
    

    Java

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

    import com.google.cloud.secretmanager.v1.LocationName;
    import com.google.cloud.secretmanager.v1.Secret;
    import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
    import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
    import java.io.IOException;
    
    public class CreateRegionalSecret {
    
      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 to create.
        String secretId = "your-secret-id";
        createRegionalSecret(projectId, locationId, secretId);
      }
    
      // Create a new regional secret 
      public static Secret createRegionalSecret(
          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 parent name from the project.
          LocationName location = LocationName.of(projectId, locationId);
    
          // Build the regional secret to create.
          Secret secret =
              Secret.newBuilder().build();
    
          // Create the regional secret.
          Secret createdSecret = client.createSecret(location.toString(), secretId, secret);
          System.out.printf("Created regional secret %s\n", createdSecret.getName());
    
          return createdSecret;
        }
      }
    }

    Node.js

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Node.js e instalar el SDK de Node.js de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const projectId = 'my-project'
    // const locationId = 'locationId';
    // const secretId = 'my-secret';
    const parent = `projects/${projectId}/locations/${locationId}`;
    
    // Imports the Secret Manager libray
    
    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 createRegionalSecret() {
      const [secret] = await client.createSecret({
        parent: parent,
        secretId: secretId,
      });
    
      console.log(`Created regional secret ${secret.name}`);
    }
    
    createRegionalSecret();

    Python

    Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito cloud-platform.

    from google.cloud import secretmanager_v1
    
    
    def create_regional_secret(
        project_id: str,
        location_id: str,
        secret_id: str,
        ttl: Optional[str] = None,
    ) -> secretmanager_v1.Secret:
        """
        Creates a new regional secret with the given name.
        """
    
        # Endpoint to call the regional secret manager sever
        api_endpoint = f"secretmanager.{location_id}.rep.googleapis.com"
    
        # Create the Secret Manager client.
        client = secretmanager_v1.SecretManagerServiceClient(
            client_options={"api_endpoint": api_endpoint},
        )
    
        # Build the resource name of the parent project.
        parent = f"projects/{project_id}/locations/{location_id}"
    
        # Create the secret.
        response = client.create_secret(
            request={
                "parent": parent,
                "secret_id": secret_id,
                "secret": {"ttl": ttl},
            }
        )
    
        # Print the new secret name.
        print(f"Created secret: {response.name}")
    
        return response
    
    

    Añadir una versión de secreto

    Secret Manager crea versiones de los datos de los secretos automáticamente. Las operaciones de claves, como el acceso, la destrucción, la inhabilitación y la habilitación, se aplican a versiones de secretos específicas. Con Secret Manager, puedes asociar secretos a versiones específicas, como 42, o a alias dinámicos, como latest. Para obtener más información, consulta Añadir una versión secreta.

    Acceder a una versión de secreto

    Para acceder a los datos secretos de una versión de secreto concreta para autenticarte correctamente, consulta Acceder a una versión de secreto regional.

    Siguientes pasos