Criar um secret regional

Nesta página, descrevemos como criar um secret regional. Um secret contém uma ou mais versões dele, junto com metadados como rótulos e anotações. O conteúdo real de um secret é armazenado em uma versão do secret.

Antes de começar

  1. Ative a API Secret Manager.

  2. Configure o Secret Manager para usar um endpoint regional.

  3. Configure a autenticação.

    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 as amostras da API REST nesta página em um ambiente de desenvolvimento local, use as credenciais fornecidas para a CLI gcloud.

        After installing the Google Cloud CLI, initialize it by running the following command:

        gcloud init

        If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      Para mais informações, consulte Autenticar para usar REST na documentação de autenticação do Google Cloud .

      Funções exigidas

      Para receber as permissões necessárias para criar um secret, peça ao administrador para conceder a você o papel do IAM Administrador do Secret Manager (roles/secretmanager.admin) no projeto, na pasta ou na organização. Para mais informações sobre a concessão de papéis, consulte Gerenciar o acesso a projetos, pastas e organizações.

      Também é possível conseguir as permissões necessárias por meio de papéis personalizados ou de outros papéis predefinidos.

      Criar um secret regional

      É possível criar secrets usando o console Google Cloud , a Google Cloud CLI, a API Secret Manager ou as bibliotecas de cliente do Secret Manager.

      Console

      1. No console Google Cloud , acesse a página Secret Manager.

        Acessar o Secret Manager

      2. Na página Secret Manager, clique na guia Secrets regionais e em Criar secret regional.

      3. Na página Criar secret regional, insira um nome para o secret no campo Nome. O nome do secret pode conter letras maiúsculas e minúsculas, numerais, hifens e sublinhados. O comprimento máximo permitido para um nome é de 255 caracteres.

      4. Insira um valor para o secret (por exemplo, abcd1234). O valor pode estar em qualquer formato, mas não pode ultrapassar 64 KiB. Também é possível fazer upload de um arquivo de texto com o valor do secret usando a opção Fazer upload do arquivo. Essa ação cria automaticamente a versão do secret.

      5. Escolha o local em que você quer armazenar o secret regional na lista Região.

      6. Clique em Criar secret.

      gcloud

      Antes de usar os dados do comando abaixo, faça estas substituições:

      • SECRET_ID: o ID do secret ou o identificador totalmente qualificado do secret.
      • LOCATION: o Google Cloud local do secret

      Execute o seguinte comando:

      Linux, macOS ou 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 os dados da solicitação abaixo, faça as substituições a seguir:

      • LOCATION: o Google Cloud local do secret
      • PROJECT_ID: o ID do projeto Google Cloud
      • SECRET_ID: o ID do secret ou o identificador totalmente qualificado do secret.

      Método HTTP e URL:

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

      Corpo JSON da solicitação:

      {}
      

      Para enviar a solicitação, escolha uma destas opções:

      curl

      Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

      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

      Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

      $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

      Você receberá uma resposta JSON semelhante a esta:

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

      Go

      Para executar esse código, primeiro configure um ambiente de desenvolvimento do Go e instale o SDK do Go do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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 executar esse código, primeiro configure um ambiente de desenvolvimento do Java e instale o SDK do Java do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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 executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Node.js do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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 executar esse código, primeiro configure um ambiente de desenvolvimento do Python e instale o SDK do Python do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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
      
      

      Adicionar uma versão do secret

      O Secret Manager cria automaticamente versões dos dados do secret usando versões do secret. As operações de chave, como acesso, destruição, desativação e ativação, são aplicadas a versões específicas do secret. Com o Secret Manager, você pode associar secrets a versões específicas, como 42, ou a aliases dinâmicos como latest. Para saber mais, consulte Adicionar uma versão do secret.

      Acessar uma versão do secret

      Para acessar os dados de uma versão específica do secret e fazer a autenticação, consulte Acessar uma versão regional do secret.

      A seguir