Creating secrets and versions

This topic shows you how to create and access the contents of a secret. For information about managing secrets, refer to Managing secrets.

In Secret Manager, secrets must be created before they can be accessed. This topic describes how to create a secret, add secret versions, and access those secret versions.

Create a secret

A secret contains one or more secret versions, along with metadata such as labels and replication information.

The actual contents of a secret are stored in a secret version.

Creating a secret requires the roles/secretmanager.admin IAM role on the parent project.

Web UI

  1. Go to the Secret Manager page in the Cloud Console.

    Go to the Secret Manager page

  2. On the Secret Manager page, click Create Secret.

  3. On the Create secret page, under Name, enter my-secret.

  4. (Optional) In the Secret value field, enter abcd1234 to also add a secret version when creating the initial secret.

  5. Leave the Regions section unchanged.

  6. Click the Create secret button.

Command-line

$ gcloud beta secrets create SECRET_ID \
    --replication-policy="automatic"

C#

/// <summary>
/// Create a new secret in the given project with the given name.
/// </summary>
/// <param name="projectId">ID of the project in which to create the secret.</param>
/// <param name="secretId">ID of the secret.</param>
/// <example>
/// Create a secret.
/// <code>CreateSecret("my-project", "my-secret")</code>
/// </example>
public static void CreateSecret(string projectId, string secretId)
{
    SecretManagerServiceClient client = SecretManagerServiceClient.Create();

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

    // Create the secret.
    var secret = client.CreateSecret(request);
    Console.WriteLine($"Created secret {secret.Name}");
}

Go

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1beta1"
	secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1"
)

// 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 createSecret(w io.Writer, parent, id string) error {
	// parent := "projects/my-project"
	// id := "my-secret"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %v", err)
	}

	// Build the request.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: id,
		Secret: &secretmanagerpb.Secret{
			Replication: &secretmanagerpb.Replication{
				Replication: &secretmanagerpb.Replication_Automatic_{
					Automatic: &secretmanagerpb.Replication_Automatic{},
				},
			},
		},
	}

	// Call the API.
	result, err := client.CreateSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create secret: %v", err)
	}
	fmt.Fprintf(w, "Created secret: %s\n", result.Name)
	return nil
}

Java

import com.google.cloud.secretmanager.v1beta1.CreateSecretRequest;
import com.google.cloud.secretmanager.v1beta1.ProjectName;
import com.google.cloud.secretmanager.v1beta1.Replication;
import com.google.cloud.secretmanager.v1beta1.Secret;
import com.google.cloud.secretmanager.v1beta1.SecretManagerServiceClient;
import java.io.IOException;

public class CreateSecret {

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

  // Add a new version to the existing secret.
  public void createSecret(String projectId, String secretId) throws IOException {
    // 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);

      // Build the secret to create.
      Secret secret =
          Secret.newBuilder()
              .setReplication(
                  Replication.newBuilder()
                      .setAutomatic(Replication.Automatic.newBuilder().build())
                      .build())
              .build();

      // Create the request.
      CreateSecretRequest request =
          CreateSecretRequest.newBuilder()
              .setParent(parent.toString())
              .setSecretId(secretId)
              .setSecret(secret)
              .build();

      // Create the secret.
      Secret createdSecret = client.createSecret(request);
      System.out.printf("Created secret %s\n", createdSecret.getName());
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const parent = 'projects/my-project';
// const secretId = 'my-secret';

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

async function createSecret() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: {
      replication: {
        automatic: {},
      },
    },
  });

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

createSecret();

PHP

// 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;

/** 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 resource name of the parent project.
$parent = $client->projectName($projectId);

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

// Print the new secret name.
printf('Created secret: %s', $secret->getName());

Python

def create_secret(project_id, secret_id):
    """
    Create 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.
    """

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

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

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

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

    # Print the new secret name.
    print('Created secret: {}'.format(response.name))

Ruby

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

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

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

# Build the resource name of the parent project.
parent = client.project_path project: project_id

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

# Print the new secret name.
puts "Created secret: #{secret.name}"

API

$ curl "https://secretmanager.googleapis.com/v1beta1/projects/PROJECT_ID/secrets?secretId=SECRET_ID" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: PROJECT_ID" \
    --data "{\"replication\": {\"automatic\": {}}}"

Add a secret version

A secret version contains the actual contents of a secret. A secret version can be enabled, disabled, or destroyed. To change the contents of a secret, you create a new version.

Adding a secret version requires the roles/secretmanager.admin IAM role on the secret itself or on all secrets in the project.

Web UI

  1. Go to the Secret Manager page in the Cloud Console.

    Go to the Secret Manager page

  2. On the Secret Manager page, click View more more_vert and select Add new version.

  3. In the Add new version dialog, in the Secret value field, enter abcd1234.

  4. Click the Add new version button.

Command-line

Add a secret version from the contents of a file on disk:

$ gcloud beta secrets versions add "SECRET_ID" --data-file="/path/to/file.txt"

You can also add a secret version directly on the command line, but this is discouraged because the plaintext will appear in your shell history:

$ echo -n "this is my super secret data" | \
    gcloud beta secrets versions add "SECRET_ID" --data-file=-

C#

/// <summary>
/// Add a secret version to the given secret. The given secret must
/// already exist.
/// </summary>
/// <param name="projectId">ID of the project where the secret resides.</param>
/// <param name="secretId">ID of the secret.</param>
/// <example>
/// Add a secret version.
/// <code>AddSecretVersion("my-project", "my-secret")</code>
/// </example>
public static void AddSecretVersion(string projectId, string secretId)
{
    SecretManagerServiceClient client = SecretManagerServiceClient.Create();

    // Create the secret payload.
    var payload = "my super secret data";

    // Create the request.
    var request = new AddSecretVersionRequest
    {
        ParentAsSecretName = new SecretName(projectId, secretId),
        Payload = new SecretPayload
        {
            Data = ByteString.CopyFrom(payload, Encoding.UTF8),
        },
    };

    // Add the secret version.
    var version = client.AddSecretVersion(request);
    Console.WriteLine($"Added secret version {version.Name}");
}

Go

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1beta1"
	secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1"
)

// addSecretVersion adds a new secret version to the given secret with the
// provided payload.
func addSecretVersion(w io.Writer, parent string) error {
	// parent := "projects/my-project/secrets/my-secret"

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

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %v", err)
	}

	// Build the request.
	req := &secretmanagerpb.AddSecretVersionRequest{
		Parent: parent,
		Payload: &secretmanagerpb.SecretPayload{
			Data: payload,
		},
	}

	// Call the API.
	result, err := client.AddSecretVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to add secret version: %v", err)
	}
	fmt.Fprintf(w, "Added secret version: %s\n", result.Name)
	return nil
}

Java

import com.google.cloud.secretmanager.v1beta1.AddSecretVersionRequest;
import com.google.cloud.secretmanager.v1beta1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1beta1.SecretName;
import com.google.cloud.secretmanager.v1beta1.SecretPayload;
import com.google.cloud.secretmanager.v1beta1.SecretVersion;
import com.google.protobuf.ByteString;
import java.io.IOException;

public class AddSecretVersion {

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

  // Add a new version to the existing secret.
  public void addSecretVersion(String projectId, String secretId) throws IOException {
    // 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()) {
      SecretName name = SecretName.of(projectId, secretId);

      // Create the secret payload.
      SecretPayload payload =
          SecretPayload.newBuilder()
              .setData(ByteString.copyFromUtf8("my super secret data"))
              .build();

      // Create the request.
      AddSecretVersionRequest request =
          AddSecretVersionRequest.newBuilder()
              .setParent(name.toString())
              .setPayload(payload)
              .build();

      // Add the secret version.
      SecretVersion version = client.addSecretVersion(request);
      System.out.printf("Added secret version %s\n", version.getName());
    }
  }
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const parent = 'projects/my-project/secrets/my-secret';

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

// Payload is the plaintext data to store in the secret
const payload = Buffer.from('my super secret data', 'utf8');

async function addSecretVersion() {
  const [version] = await client.addSecretVersion({
    parent: parent,
    payload: {
      data: payload,
    },
  });

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

addSecretVersion();

PHP

// Import the Secret Manager client library.
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 resource name of the parent secret.
$parent = $client->secretName($projectId, $secretId);

// Access the secret version.
$response = $client->addSecretVersion($parent, new SecretPayload([
    'data' => 'my super secret data',
]));

// Print the new secret version name.
printf('Added secret version: %s', $response->getName());

Python

def add_secret_version(project_id, secret_id, payload):
    """
    Add a new secret version to the given secret with the provided payload.
    """

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

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

    # Build the resource name of the parent secret.
    parent = client.secret_path(project_id, secret_id)

    # Convert the string payload into a bytes. This step can be omitted if you
    # pass in bytes instead of a str for the payload argument.
    payload = payload.encode('UTF-8')

    # Add the secret version.
    response = client.add_secret_version(parent, {'data': payload})

    # Print the new secret version name.
    print('Added secret version: {}'.format(response.name))

Ruby

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

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

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

# Build the resource name of the secret version.
name = client.secret_path project: project_id, secret: secret_id

# Add the secret version.
version = client.add_secret_version(
  parent:  name,
  payload: {
    data: "my super secret data"
  }
)

# Print the new secret version name.
puts "Added secret version: #{version.name}"

API

Base64-encode the secret data and save it as a shell variable.

$ SECRET_DATA=$(echo "seCr3t" | base64)

Invoke the API using curl.

$ curl "https://secretmanager.googleapis.com/v1beta1/projects/PROJECT_ID/secrets/SECRET_ID:addVersion" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: PROJECT_ID" \
    --data "{\"payload\": {\"data\": \"${SECRET_DATA}\"}}"

Access a secret version

Accessing a secret version returns the secret contents, as well as additional metadata about the secret version. When you access a secret version, you specify its version-id. You can also access the latest version of a secret by specifying "latest" as the version.

Accessing a secret version requires the roles/secretmanager.secretAccessor IAM role on the secret version, the secret, or all secrets in the project.

Web UI

  1. Go to the Secret Manager page in the Cloud Console.

    Go to the Secret Manager page

  2. On the Secret Manager page, click on the Name of a secret.

  3. On the Secret details page, in the Versions table, locate a secret version to access.

  4. In the Actions column, click View moremore_vert.

  5. Click View secret value from the menu.

  6. You will see dialog that shows the secret version value. Click Done to finish.

Command-line

Access a secret version:

$ gcloud beta secrets versions access VERSION_ID --secret="SECRET_ID"

C#

/// <summary>
/// Accesses a secret with provided version.
/// </summary>
/// <param name="projectId">ID of the project where the secret resides.</param>
/// <param name="secretId">ID of the secret.</param>
/// <param name="secretVersion">Version of the secret.</param>
/// <example>
/// With a specific version.
/// <code>AccessSecretVersion("my-project", "my-secret", "5")</code>
/// </example>
/// <example>
/// With an alias version.
/// <code>AccessSecretVersion("my-project", "my-secret", "latest")</code>
/// </example>
public static void AccessSecretVersion(string projectId, string secretId, string secretVersion)
{
    SecretManagerServiceClient client = SecretManagerServiceClient.Create();

    // Create the request.
    var request = new AccessSecretVersionRequest
    {
        SecretVersionName = new SecretVersionName(projectId, secretId, secretVersion),
    };

    // Access the secret and print the result.
    //
    // WARNING: Do not print secrets in production environments. This
    // snippet is for demonstration purposes only.
    var version = client.AccessSecretVersion(request);
    string payload = version.Payload.Data.ToStringUtf8();
    Console.WriteLine($"Payload: {payload}");
}

Go

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1beta1"
	secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1"
)

// accessSecretVersion accesses the payload for the given secret version if one
// exists. The version can be a version number as a string (e.g. "5") or an
// alias (e.g. "latest").
func accessSecretVersion(w io.Writer, name string) error {
	// name := "projects/my-project/secrets/my-secret/versions/5"
	// name := "projects/my-project/secrets/my-secret/versions/latest"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %v", err)
	}

	// Build the request.
	req := &secretmanagerpb.AccessSecretVersionRequest{
		Name: name,
	}

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

	// WARNING: Do not print the secret in a production environment - this snippet
	// is showing how to access the secret material.
	fmt.Fprintf(w, "Plaintext: %s\n", string(result.Payload.Data))
	return nil
}

Java

import com.google.cloud.secretmanager.v1beta1.AccessSecretVersionRequest;
import com.google.cloud.secretmanager.v1beta1.AccessSecretVersionResponse;
import com.google.cloud.secretmanager.v1beta1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1beta1.SecretVersionName;
import java.io.IOException;

public class AccessSecretVersion {

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

  // Access the payload for the given secret version if one exists. The version
  // can be a version number as a string (e.g. "5") or an alias (e.g. "latest").
  public void accessSecretVersion(String projectId, String secretId, String versionId)
      throws IOException {
    // 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()) {
      SecretVersionName name = SecretVersionName.of(projectId, secretId, versionId);

      // Access the secret version.
      AccessSecretVersionRequest request =
          AccessSecretVersionRequest.newBuilder().setName(name.toString()).build();
      AccessSecretVersionResponse response = client.accessSecretVersion(request);

      // 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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const name = 'projects/my-project/secrets/my-secret/versions/5';
// const name = 'projects/my-project/secrets/my-secret/versions/latest';

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

async function accessSecretVersion() {
  const [version] = await client.accessSecretVersion({
    name: name,
  });

  // Extract the payload as a string.
  const payload = version.payload.data.toString('utf8');

  // WARNING: Do not print the secret in a production environment - this
  // snippet is showing how to access the secret material.
  console.info(`Payload: ${payload}`);
}

accessSecretVersion();

PHP

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

/** 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');
// $versionId = 'YOUR_VERSION_ID' (e.g. 'latest' or '5');

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

// Build the resource name of the secret version.
$name = $client->secretVersionName($projectId, $secretId, $versionId);

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

Python

def access_secret_version(project_id, secret_id, version_id):
    """
    Access the payload for the given secret version if one exists. The version
    can be a version number as a string (e.g. "5") or an alias (e.g. "latest").
    """

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

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

    # Build the resource name of the secret version.
    name = client.secret_version_path(project_id, secret_id, version_id)

    # Access the secret version.
    response = client.access_secret_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

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

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

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

# Build the resource name of the secret version.
name = client.secret_version_path(
  project:        project_id,
  secret:         secret_id,
  secret_version: version_id
)

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

API

$ curl "https://secretmanager.googleapis.com/v1beta1/projects/PROJECT_ID/secrets/SECRET_ID/versions/VERSION_ID:access" \
    --request "GET" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: PROJECT_ID"

The response payload.data is the base64-encoded contents of the secret version. Here is an example of extracting the secret using the jq tool:

$ curl "https://secretmanager.googleapis.com/v1beta1/projects/PROJECT_ID/secrets/SECRET_ID/versions/VERSION_ID:access" \
    --request "GET" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: PROJECT_ID" \
    | jq -r ".payload.data" | base64 --decode