Secret Manager Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Secret Manager API. Read more about the client libraries for Cloud APIs in Client Libraries Explained.

Installing the client library

C#

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

Using PowerShell:

$ Install-Package Google.Cloud.SecretManager.V1 -Version 1.0.0

Using the dotnet CLI:

$ dotnet add package Google.Cloud.SecretManager.V1 -Version 1.0.0

Go

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

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

Java

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

If you are using Maven, add the following to your pom.xml file:

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

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

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

compile 'com.google.cloud:google-cloud-secretmanager:0.3.0'

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

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

If you're using 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.

Node.js

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

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

PHP

For more information, see Using PHP on Google Cloud.

$ composer require google/cloud-secret-manager

Python

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

$ pip install google-cloud-secret-manager

Ruby

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

$ gem install google-cloud-secret_manager

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For other ways to authenticate, see the GCP authentication documentation.

Cloud Console

  1. In the Cloud Console, go to the Create service account key page.

    Go to the Create Service Account Key page
  2. From the Service account list, select New service account.
  3. In the Service account name field, enter a name.
  4. From the Role list, select Project > Owner.

    Note: The Role field authorizes your service account to access resources. You can view and change this field later by using the Cloud Console. If you are developing a production app, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  5. Click Create. A JSON file that contains your key downloads to your computer.

Command line

You can run the following commands using the Cloud SDK on your local machine, or in Cloud Shell.

  1. Create the service account. Replace [NAME] with a name for the service account.

    gcloud iam service-accounts create [NAME]
  2. Grant permissions to the service account. Replace [PROJECT_ID] with your project ID.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    Note: The Role field authorizes your service account to access resources. You can view and change this field later by using Cloud Console. If you are developing a production app, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  3. Generate the key file. Replace [FILE_NAME] with a name for the key file.

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the file path of the JSON file that contains your service account key, and [FILE_NAME] with the filename. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Linux or macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

With PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

With command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C#

For more information, see the Secret Manager C# API reference documentation.


using System;
using System.Linq;
using System.Text;
using Google.Api.Gax.ResourceNames;
using Google.Protobuf;

// Imports the Secret Manager client library
using Google.Cloud.SecretManager.V1;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            // GCP project in which to store secrets in Secret Manager.
            string projectId = "YOUR-PROJECT-ID";

            // ID of the secret to create.
            string secretId = "YOUR-SECRET-ID";

            // Create a Secret Manager client.
            SecretManagerServiceClient client = SecretManagerServiceClient.Create();

            // Create the parent secret.
            var createSecretRequest = new CreateSecretRequest
            {
                ParentAsProjectName = new ProjectName(projectId),
                SecretId = secretId,
                Secret = new Secret
                {
                    Replication = new Replication
                    {
                        Automatic = new Replication.Types.Automatic(),
                    },
                },
            };

            var secret = client.CreateSecret(createSecretRequest);

            // Add a secret version.
            var addSecretVersionRequest = new AddSecretVersionRequest
            {
                ParentAsSecretName = secret.SecretName,
                Payload = new SecretPayload
                {
                    Data = ByteString.CopyFrom("my super secret data", Encoding.UTF8),
                },
            };

            var version = client.AddSecretVersion(addSecretVersionRequest);

            // Access the secret version.
            var accessSecretVersionRequest = new AccessSecretVersionRequest
            {
                SecretVersionName = version.SecretVersionName,
            };

            var result = client.AccessSecretVersion(accessSecretVersionRequest);

            // Print the results
            //
            // WARNING: Do not print secrets in production environments. This
            // snippet is for demonstration purposes only.
            string payload = result.Payload.Data.ToStringUtf8();
            Console.WriteLine($"Plaintext: {payload}");
        }
    }
}

Go

For more information, see the Secret Manager Go API reference documentation.


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

import (
	"context"
	"fmt"
	"log"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
)

func main() {
	// GCP project in which to store secrets in Secret Manager.
	projectID := "your-project-id"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		log.Fatalf("failed to setup client: %v", err)
	}

	// Create the request to create the secret.
	createSecretReq := &secretmanagerpb.CreateSecretRequest{
		Parent:   fmt.Sprintf("projects/%s", projectID),
		SecretId: "my-secret",
		Secret: &secretmanagerpb.Secret{
			Replication: &secretmanagerpb.Replication{
				Replication: &secretmanagerpb.Replication_Automatic_{
					Automatic: &secretmanagerpb.Replication_Automatic{},
				},
			},
		},
	}

	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

For more information, see the Secret Manager Java API reference documentation.

import com.google.cloud.secretmanager.v1.AccessSecretVersionRequest;
import com.google.cloud.secretmanager.v1.AccessSecretVersionResponse;
import com.google.cloud.secretmanager.v1.AddSecretVersionRequest;
import com.google.cloud.secretmanager.v1.CreateSecretRequest;
import com.google.cloud.secretmanager.v1.ProjectName;
import com.google.cloud.secretmanager.v1.Replication;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretPayload;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.protobuf.ByteString;

public class Quickstart {

  public void quickstart() throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String secretId = "your-secret-id";
    quickstart(projectId, secretId);
  }

  public void quickstart(String projectId, String secretId) throws Exception {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {

      // Build the parent name from the project.
      ProjectName parent = ProjectName.of(projectId);

      // Create the parent secret.
      CreateSecretRequest createRequest =
          CreateSecretRequest.newBuilder()
              .setParent(parent.toString())
              .setSecretId(secretId)
              .setSecret(
                  Secret.newBuilder()
                      .setReplication(
                          Replication.newBuilder()
                              .setAutomatic(Replication.Automatic.newBuilder().build())
                              .build())
                      .build())
              .build();

      Secret secret = client.createSecret(createRequest);

      // Add a secret version.
      AddSecretVersionRequest addRequest =
          AddSecretVersionRequest.newBuilder()
              .setParent(secret.getName())
              .setPayload(
                  SecretPayload.newBuilder()
                      .setData(ByteString.copyFromUtf8("hello world!"))
                      .build())
              .build();
      SecretVersion version = client.addSecretVersion(addRequest);

      // Access the secret version.
      AccessSecretVersionRequest accessRequest =
          AccessSecretVersionRequest.newBuilder().setName(version.getName()).build();
      AccessSecretVersionResponse response = client.accessSecretVersion(accessRequest);

      // 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 payload = response.getPayload().getData().toStringUtf8();
      System.out.printf("Plaintext: %s\n", payload);
    }
  }
}

Node.js

For more information, see the Secret Manager Node.js API reference documentation.

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

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

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

  console.info(`Created 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 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();

PHP

For more information, see the Secret Manager PHP API reference documentation.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1beta1\Replication;
use Google\Cloud\SecretManager\V1beta1\Replication\Automatic;
use Google\Cloud\SecretManager\V1beta1\Secret;
use Google\Cloud\SecretManager\V1beta1\SecretManagerServiceClient;
use Google\Cloud\SecretManager\V1beta1\SecretPayload;

/** Uncomment and populate these variables in your code */
// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');
// $secretId = 'YOUR_SECRET_ID' (e.g. 'my-secret');

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

// Build the parent name from the project.
$parent = $client->projectName($projectId);

// Create the parent secret.
$secret = $client->createSecret($parent, $secretId, [
    'secret' => new Secret([
        'replication' => new Replication([
            'automatic' => new Automatic(),
        ]),
    ]),
]);

// Add the secret version.
$version = $client->addSecretVersion($secret->getName(), new SecretPayload([
    'data' => 'hello world',
]));

// Access the secret version.
$response = $client->accessSecretVersion($version->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.
$payload = $response->getPayload()->getData();
printf('Plaintext: %s' . PHP_EOL, $payload);

Python

For more information, see the Secret Manager Python API reference documentation.

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

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

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

# Create the Secret Manager client.
client = secretmanager.SecretManagerServiceClient()

# Build the parent name from the project.
parent = client.project_path(project_id)

# Create the parent secret.
secret = client.create_secret(parent, secret_id, {
    'replication': {
        'automatic': {},
    },
})

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

# Access the secret version.
response = client.access_secret_version(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('Plaintext: {}'.format(payload))

Ruby

For more information, see the Secret Manager Ruby API reference documentation.

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

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

# Create the Secret Manager client.
client = Google::Cloud::SecretManager.secret_manager_service

# Build the parent name from the project.
parent = "projects/#{project_id}"

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

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

# Access the secret version.
response = client.access_secret_version 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
puts "Plaintext: #{payload}"

Additional resources