Bibliotecas de cliente do Secret Manager

Nesta página, mostramos como começar a usar as bibliotecas de cliente do Cloud para a API Secret Manager. As bibliotecas de cliente facilitam o acesso a APIs doCloud de Confiance by S3NS em uma linguagem compatível. É possível usar as APIs doCloud de Confiance by S3NS diretamente fazendo solicitações brutas ao servidor, mas as bibliotecas de cliente oferecem simplificações que reduzem significativamente a quantidade de código que você precisa escrever.

Saiba mais sobre as bibliotecas de cliente do Cloud e as bibliotecas de cliente de APIs do Google mais antigas em Explicação sobre as bibliotecas de cliente.

Instalar a biblioteca de cliente

C++

Consulte os requisitos e as dependências de instalação da biblioteca em Como configurar um ambiente de desenvolvimento em C++.

C#

Se você estiver usando o Visual Studio 2017 ou uma versão posterior, abra a janela do gerenciador de pacotes nuget e digite o seguinte:

Install-Package Google.Apis

Se você estiver usando as ferramentas da interface de linha de comando do .NET Core para instalar as dependências, execute o seguinte comando:

dotnet add package Google.Apis

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em C#.

Go

$ go get cloud.google.com/go/secretmanager/apiv1
$ go get google.golang.org/genproto/googleapis/cloud/secretmanager/v1

Para mais informações, consulte Como configurar um ambiente de desenvolvimento do Go.

Java

Se você estiver usando o Maven, adicione o código abaixo ao arquivo pom.xml. Para mais informações sobre BOMs, consulte BOM das bibliotecas do Google Cloud Platform.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.83.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-secretmanager</artifactId>
  </dependency>
</dependencies>

Se você estiver usando o Gradle, adicione isto às dependências:

implementation 'com.google.cloud:google-cloud-secretmanager:2.93.0'

Se você estiver usando o sbt, adicione o seguinte às suas dependências:

libraryDependencies += "com.google.cloud" % "google-cloud-secretmanager" % "2.93.0"

Se você estiver usando o Visual Studio Code ou o IntelliJ, poderá adicionar bibliotecas de cliente ao projeto usando estes plug-ins de IDE:

Os plug-ins também oferecem outras funcionalidades, como gerenciamento de chaves de contas de serviço. Consulte a documentação de cada plug-in para mais detalhes.

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Java.

Node.js

$ npm install @google-cloud/secret-manager

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Node.js.

PHP

composer require google/apiclient

Para mais informações, consulte Como usar o PHP no Google Cloud.

Python

$ pip install google-cloud-secret-manager

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Python.

Ruby

gem install google-api-client

Para mais informações, consulte Como configurar um ambiente de desenvolvimento em Ruby.

Configurar a autenticação

Para autenticar chamadas às APIs do Cloud de Confiance by S3NS , as bibliotecas de cliente oferecem suporte a Application Default Credentials (ADC). As bibliotecas procuram credenciais em um conjunto de locais definidos e as usam para autenticar solicitações à API. Com o ADC, é possível disponibilizar credenciais ao aplicativo em uma variedade de ambientes, como de desenvolvimento ou produção local, sem precisar modificar o código do aplicativo.

Em ambientes de produção, a maneira como você configura o ADC depende do serviço e do contexto. Para mais informações, consulte Configurar o Application Default Credentials.

Para um ambiente de desenvolvimento local, é possível configurar o ADC com as credenciais associadas à sua Conta do Google:

  1. Instale a Google Cloud CLI e faça login na CLI gcloud com sua identidade federada. Depois de fazer login, inicialize a Google Cloud CLI executando o seguinte comando:

    gcloud init
  2. Crie credenciais de autenticação local para sua conta de usuário:

    gcloud auth application-default login

    Se um erro de autenticação for retornado e você estiver usando um provedor de identidade (IdP) externo, confirme se você fez login na CLI gcloud com sua identidade federada.

    Uma tela de login é exibida. Após o login, suas credenciais são armazenadas no arquivo de credenciais local usado pelo ADC.

Usar a biblioteca de cliente

O exemplo a seguir mostra como usar a biblioteca de cliente.

Go


// Sample quickstart is a basic program that uses Secret Manager.
package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	// GCP project in which to store secrets in Secret Manager.
	projectID := "your-project-id"
	// Location at which you want to store your secrets
	locationID := "your-location-id"

	// Create the client.
	ctx := context.Background()
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationID)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))

	if err != nil {
		log.Fatalf("failed to setup client: %v", err)
	}
	defer client.Close()

	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)

	// Create the request to create the secret.
	createSecretReq := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: "my-secret",
	}

	secret, err := client.CreateSecret(ctx, createSecretReq)
	if err != nil {
		log.Fatalf("failed to create secret: %v", err)
	}

	// Declare the payload to store.
	payload := []byte("my super secret data")

	// Build the request.
	addSecretVersionReq := &secretmanagerpb.AddSecretVersionRequest{
		Parent: secret.Name,
		Payload: &secretmanagerpb.SecretPayload{
			Data: payload,
		},
	}

	// Call the API.
	version, err := client.AddSecretVersion(ctx, addSecretVersionReq)
	if err != nil {
		log.Fatalf("failed to add secret version: %v", err)
	}

	// Build the request.
	accessRequest := &secretmanagerpb.AccessSecretVersionRequest{
		Name: version.Name,
	}

	// Call the API.
	result, err := client.AccessSecretVersion(ctx, accessRequest)
	if err != nil {
		log.Fatalf("failed to access secret version: %v", err)
	}

	// Print the secret payload.
	//
	// WARNING: Do not print the secret in a production environment - this
	// snippet is showing how to access the secret material.
	log.Printf("Plaintext: %s", result.Payload.Data)
}

Java

import com.google.cloud.secretmanager.v1.AccessSecretVersionResponse;
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 com.google.cloud.secretmanager.v1.SecretPayload;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.protobuf.ByteString;

public class RegionalQuickstart {

  public void main(String[] args) throws Exception {
    // 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.
    String secretId = "your-secret-id";
    regionalQuickstart(projectId, locationId, secretId);
  }

  // Demonstrates basic capabilities in the regional Secret Manager API.
  public SecretPayload regionalQuickstart(
      String projectId, String locationId, String secretId) 
      throws Exception {

    // 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 parent = LocationName.of(projectId, locationId);

      // Create the parent secret.
      Secret secret =
          Secret.newBuilder()
              .build();

      Secret createdSecret = client.createSecret(parent, secretId, secret);

      // Add a secret version.
      SecretPayload payload =
          SecretPayload.newBuilder().setData(ByteString.copyFromUtf8("Secret data")).build();
      SecretVersion addedVersion = client.addSecretVersion(createdSecret.getName(), payload);

      // Access the secret version.
      AccessSecretVersionResponse response = client.accessSecretVersion(addedVersion.getName());

      // Print the secret payload.
      //
      // WARNING: Do not print the secret in a production environment - this
      // snippet is showing how to access the secret material.
      String data = response.getPayload().getData().toStringUtf8();
      // System.out.printf("Plaintext: %s\n", data);

      return payload;
    }
  }
}

Node.js


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

// Import the Secret Manager client and instantiate it:
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');
const client = new SecretManagerServiceClient(options);

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// projectId = 'my-project', // Project for which to manage secrets.
// locationID = 'my-location', // Region location to store secrets in
// secretId = 'foo', // Secret ID.
// payload = 'hello world!' // String source data.

const parent = `projects/${projectId}/locations/${locationId}`;

async function createAndAccessSecret() {
  // Create the secret.
  const [secret] = await client.createSecret({
    parent: parent,
    secret: {
      name: secretId,
    },
    secretId,
  });

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

  // Add a version with a payload onto the secret.
  const [version] = await client.addSecretVersion({
    parent: secret.name,
    payload: {
      data: Buffer.from(payload, 'utf8'),
    },
  });

  console.info(`Added regional secret version ${version.name}`);

  // Access the secret.
  const [accessResponse] = await client.accessSecretVersion({
    name: version.name,
  });

  const responsePayload = accessResponse.payload.data.toString('utf8');
  console.info(`Payload: ${responsePayload}`);
}
createAndAccessSecret();

Python

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

# TODO (developer): uncomment variables and assign a value.

# GCP project in which to store secrets in Secret Manager.
# project_id = "YOUR_PROJECT_ID"

# Location where the secret is to be stored
# location_id = "YOUR_LOCATION_ID"

# ID of the secret to create.
# secret_id = "YOUR_SECRET_ID"

# 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 parent name from the project.
parent = f"projects/{project_id}/locations/{location_id}"

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

# Add the secret version.
version = client.add_secret_version(
    request={"parent": secret.name, "payload": {"data": b"hello world!"}}
)

# Access the secret version.
response = client.access_secret_version(request={"name": version.name})

# Print the secret payload.
#
# WARNING: Do not print the secret in a production environment - this
# snippet is showing how to access the secret material.
payload = response.payload.data.decode("UTF-8")
print(f"Plaintext: {payload}")

Outros recursos

C++

A lista a seguir contém links para mais recursos relacionados à biblioteca de cliente para C++:

C#

Confira na lista a seguir os links para mais recursos relacionados à biblioteca de cliente para C#:

Go

Confira na lista a seguir os links para mais recursos relacionados à biblioteca de cliente para Go:

Java

Confira na lista a seguir os links para mais recursos relacionados à biblioteca de cliente para Java:

Node.js

Confira na lista a seguir os links para mais recursos relacionados à biblioteca de cliente para Node.js:

PHP

Confira na lista a seguir os links para mais recursos relacionados à biblioteca de cliente para PHP:

Python

Confira na lista a seguir os links para mais recursos relacionados à biblioteca de cliente para Python:

Ruby

Confira na lista a seguir os links para mais recursos relacionados à biblioteca de cliente para Ruby: