Secret Manager client libraries

This page shows how to get started with the Cloud Client Libraries for the Secret Manager API. Client libraries make it easier to access Google Cloud APIs from a supported language. Although you can use Google Cloud APIs directly by making raw requests to the server, client libraries provide simplifications that significantly reduce the amount of code you need to write.

Read more about the Cloud Client Libraries and the older Google API Client Libraries in Client libraries explained.

Install the client library

C++

See Setting up a C++ development environment for details about this client library's requirements and install dependencies.

C#

If you are using Visual Studio 2017 or higher, open nuget package manager window and type the following:

Install-Package Google.Apis

If you are using .NET Core command-line interface tools to install your dependencies, run the following command:

dotnet add package Google.Apis

For more information, see Setting Up a C# Development Environment.

Go

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

For more information, see Setting Up a Go Development Environment.

Java

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.48.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>

If you are using Gradle, add the following to your dependencies:

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

If you are using sbt, add the following to your dependencies:

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

If you're using Visual Studio Code, IntelliJ, or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

For more information, see Setting Up a Java Development Environment.

Node.js

$ npm install --save @google-cloud/secret-manager

For more information, see Setting Up a Node.js Development Environment.

PHP

composer require google/apiclient

For more information, see Using PHP on Google Cloud.

Python

$ pip install google-cloud-secret-manager

For more information, see Setting Up a Python Development Environment.

Ruby

gem install google-api-client

For more information, see Setting Up a Ruby Development Environment.

Set up authentication

To authenticate calls to Google Cloud APIs, client libraries support Application Default Credentials (ADC); the libraries look for credentials in a set of defined locations and use those credentials to authenticate requests to the API. With ADC, you can make credentials available to your application in a variety of environments, such as local development or production, without needing to modify your application code.

For production environments, the way you set up ADC depends on the service and context. For more information, see Set up Application Default Credentials.

For a local development environment, you can set up ADC with the credentials that are associated with your Google Account:

  1. Install the Google Cloud CLI, then initialize it by running the following command:

    gcloud init
  2. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    A sign-in screen appears. After you sign in, your credentials are stored in the local credential file used by ADC.

Use the client library

The following example shows how to use the client library.

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

Additional resources

C++

The following list contains links to more resources related to the client library for C++:

C#

The following list contains links to more resources related to the client library for C#:

Go

The following list contains links to more resources related to the client library for Go:

Java

The following list contains links to more resources related to the client library for Java:

Node.js

The following list contains links to more resources related to the client library for Node.js:

PHP

The following list contains links to more resources related to the client library for PHP:

Python

The following list contains links to more resources related to the client library for Python:

Ruby

The following list contains links to more resources related to the client library for Ruby: