Managing secret versions

In addition to the secret contents, a secret version contains information about the state of the version and some other metadata. This topic describes how to manage a secret's versions. A secret version can be in one of the following states at any given time:

  • Enabled - In this state, the secret version can be accessed and described. This is the default state for a new secret version.

  • Disabled - In this state, the secret version cannot be accessed, but the secret's contents still exist. The secret version can be re-enabled to restore access.

  • Destroyed - In this state, the secret version's contents are discarded. The secret version cannot be changed to another state.

Get a secret version

When you get a secret version, all of the secret version's metadata except for contents of the secret version.

Getting a secret version requires the roles/secretmanager.viewer IAM role on the secret version, parent secret, or 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 on the Name of a secret.

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

  4. Find the ID of the version in the table and read its metadata.

Command-line

To use Secret Manager on the command line, first Install or upgrade to version 281.0.0 or higher of the Cloud SDK.

$ gcloud secrets versions describe version-id --secret="secret-id"

C#

To run this code, first set up a C# development environment and install the Secret Manager C# SDK.


using Google.Cloud.SecretManager.V1;

public class GetSecretVersionSample
{
    public SecretVersion GetSecretVersion(
      string projectId = "my-project", string secretId = "my-secret", string secretVersionId = "123")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretVersionName secretVersionName = new SecretVersionName(projectId, secretId, secretVersionId);

        // Call the API.
        SecretVersion version = client.GetSecretVersion(secretVersionName);
        return version;
    }
}

Go

To run this code, first set up a Go development environment and install the Secret Manager Go SDK.

import (
	"context"
	"fmt"
	"io"

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

// getSecretVersion gets information about the given secret version. It does not
// include the payload data.
func getSecretVersion(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.GetSecretVersionRequest{
		Name: name,
	}

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

	fmt.Fprintf(w, "Found secret version %s with state %s\n",
		result.Name, result.State)
	return nil
}

Java

To run this code, first set up a Java development environment and install the Secret Manager Java SDK.

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.cloud.secretmanager.v1.SecretVersionName;
import java.io.IOException;

public class GetSecretVersion {

  public void getSecretVersion() 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";
    getSecretVersion(projectId, secretId, versionId);
  }

  // Get an existing secret version.
  public void getSecretVersion(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()) {
      // Build the name from the version.
      SecretVersionName secretVersionName = SecretVersionName.of(projectId, secretId, versionId);

      // Create the secret.
      SecretVersion version = client.getSecretVersion(secretVersionName);
      System.out.printf("Secret version %s, state %s\n", version.getName(), version.getState());
    }
  }
}

Node.js

To run this code, first set up a Node.js development environment and install the Secret Manager Node.js SDK.

/**
 * 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 getSecretVersion() {
  const [version] = await client.getSecretVersion({
    name: name,
  });

  console.info(`Found secret ${version.name} with state ${version.state}`);
}

getSecretVersion();

PHP

To run this code, first learn about using PHP on Google Cloud and install the Secret Manager PHP SDK.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\SecretManagerServiceClient;
use Google\Cloud\SecretManager\V1\SecretVersion\State;

/** 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->getSecretVersion($name);

// Get the state string from the enum.
$state = State::name($response->getState());

// Print a success message.
printf('Got secret version %s with state %s', $response->getName(), $state);

Python

To run this code, first set up a Python development environment and install the Secret Manager Python SDK.

def get_secret_version(project_id, secret_id, version_id):
    """
    Get information about the given secret version. It does not include the
    payload data.
    """

    # Import the Secret Manager client library.
    from google.cloud import 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)

    # Get the secret version.
    response = client.get_secret_version(name)

    # Print information about the secret version.
    state = response.State.Name(response.state)
    print('Got secret version {} with state {}'.format(response.name, state))

Ruby

To run this code, first set up a Ruby development environment and install the Secret Manager Ruby SDK.

# 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
)

# Get the secret version.
version = client.get_secret_version name: name

# Get the state.
state = version.state.to_s.downcase

# Print a success message.
puts "Got secret version #{version.name} with state #{state}"

API

These examples use curl to demonstrate using the API.

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

Listing a secret's versions

Listing secret versions returns all versions associated with the secret, and the state of each, whether enabled, disabled, or destroyed.

Listing secret versions requires the roles/secretmanager.viewer IAM role on the parent secret or 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 on the Name of a secret.

  3. The Secret details page displays the list of versions in the Versions table.

Command-line

To use Secret Manager on the command line, first Install or upgrade to version 281.0.0 or higher of the Cloud SDK.

$ gcloud secrets versions list secret-id

C#

To run this code, first set up a C# development environment and install the Secret Manager C# SDK.


using Google.Cloud.SecretManager.V1;

public class ListSecretVersionsSample
{
    public void ListSecretVersions(string projectId = "my-project", string secretId = "my-secret")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretName secretName = new SecretName(projectId, secretId);

        // Call the API.
        foreach (SecretVersion secretVersion in client.ListSecretVersions(secretName))
        {
            // ...
        }
    }
}

Go

To run this code, first set up a Go development environment and install the Secret Manager Go SDK.

import (
	"context"
	"fmt"
	"io"

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

// listSecretVersions lists all secret versions in the given secret and their
// metadata.
func listSecretVersions(w io.Writer, parent string) error {
	// parent := "projects/my-project/secrets/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.ListSecretVersionsRequest{
		Parent: parent,
	}

	// Call the API.
	it := client.ListSecretVersions(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}

		if err != nil {
			return fmt.Errorf("failed to list secret versions: %v", err)
		}

		fmt.Fprintf(w, "Found secret version %s with state %s\n",
			resp.Name, resp.State)
	}

	return nil
}

Java

To run this code, first set up a Java development environment and install the Secret Manager Java SDK.

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient.ListSecretVersionsPagedResponse;
import com.google.cloud.secretmanager.v1.SecretName;
import java.io.IOException;

public class ListSecretVersions {

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

  // List all secret versions for a secret.
  public void listSecretVersions(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.
      SecretName projectName = SecretName.of(projectId, secretId);

      // Get all versions.
      ListSecretVersionsPagedResponse pagedResponse = client.listSecretVersions(projectName);

      // List all versions and their state.
      pagedResponse
          .iterateAll()
          .forEach(
              version -> {
                System.out.printf("Secret version %s, %s\n", version.getName(), version.getState());
              });
    }
  }
}

Node.js

To run this code, first set up a Node.js development environment and install the Secret Manager Node.js SDK.

/**
 * 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();

async function listSecretVersions() {
  const [versions] = await client.listSecretVersions({
    parent: parent,
  });

  versions.forEach(version => {
    console.log(`${version.name}: ${version.state}`);
  });
}

listSecretVersions();

PHP

To run this code, first learn about using PHP on Google Cloud and install the Secret Manager PHP SDK.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\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 secret.
$parent = $client->secretName($projectId, $secretId);

// List all secret versions.
foreach ($client->listSecretVersions($parent) as $version) {
    printf('Found secret version %s', $version->getName());
}

Python

To run this code, first set up a Python development environment and install the Secret Manager Python SDK.

def list_secret_versions(project_id, secret_id):
    """
    List all secret versions in the given secret and their metadata.
    """

    # Import the Secret Manager client library.
    from google.cloud import 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)

    # List all secret versions.
    for version in client.list_secret_versions(parent):
        print('Found secret version: {}'.format(version.name))

Ruby

To run this code, first set up a Ruby development environment and install the Secret Manager Ruby SDK.

# 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.
parent = client.secret_path project: project_id, secret: secret_id

# Get the list of secret versions.
list = client.list_secret_versions parent: parent

# List all secret versions.
list.each do |version|
  puts "Got secret version #{version.name}"
end

API

These examples use curl to demonstrate using the API.

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

Changing a secret version's state

Disable a secret version

Disabling a secret version changes a secret version's state from enabled to disabled. This will make the secret version inaccessible.

Disabling a secret version requires the roles/secretmanager.admin IAM role on the secret version, parent secret, or 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 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 Disable from the menu.

  6. In the Disable secret version dialog, click the Disable selected versions button.

Command-line

To use Secret Manager on the command line, first Install or upgrade to version 281.0.0 or higher of the Cloud SDK.

$ gcloud secrets versions disable version-id --secret="secret-id"

C#

To run this code, first set up a C# development environment and install the Secret Manager C# SDK.


using Google.Cloud.SecretManager.V1;

public class DisableSecretVersionSample
{
    public SecretVersion DisableSecretVersion(
      string projectId = "my-project", string secretId = "my-secret", string secretVersionId = "123")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretVersionName secretVersionName = new SecretVersionName(projectId, secretId, secretVersionId);

        // Call the API.
        SecretVersion version = client.DisableSecretVersion(secretVersionName);
        return version;
    }
}

Go

To run this code, first set up a Go development environment and install the Secret Manager Go SDK.

import (
	"context"
	"fmt"

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

// disableSecretVersion disables the given secret version. Future requests will
// throw an error until the secret version is enabled. Other secrets versions
// are unaffected.
func disableSecretVersion(name string) error {
	// name := "projects/my-project/secrets/my-secret/versions/5"

	// 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.DisableSecretVersionRequest{
		Name: name,
	}

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

Java

To run this code, first set up a Java development environment and install the Secret Manager Java SDK.

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.cloud.secretmanager.v1.SecretVersionName;
import java.io.IOException;

public class DisableSecretVersion {

  public void disableSecretVersion() 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";
    disableSecretVersion(projectId, secretId, versionId);
  }

  // Disable an existing secret version.
  public void disableSecretVersion(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()) {
      // Build the name from the version.
      SecretVersionName secretVersionName = SecretVersionName.of(projectId, secretId, versionId);

      // Create the secret.
      SecretVersion version = client.disableSecretVersion(secretVersionName);
      System.out.printf("Disabled secret version %s\n", version.getName());
    }
  }
}

Node.js

To run this code, first set up a Node.js development environment and install the Secret Manager Node.js SDK.

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

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

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

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

  console.info(`Disabled ${version.name}`);
}

disableSecretVersion();

PHP

To run this code, first learn about using PHP on Google Cloud and install the Secret Manager PHP SDK.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\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);

// Disable the secret version.
$response = $client->disableSecretVersion($name);

// Print a success message.
printf('Disabled secret version: %s', $response->getName());

Python

To run this code, first set up a Python development environment and install the Secret Manager Python SDK.

def disable_secret_version(project_id, secret_id, version_id):
    """
    Disable the given secret version. Future requests will throw an error until
    the secret version is enabled. Other secrets versions are unaffected.
    """

    # Import the Secret Manager client library.
    from google.cloud import 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)

    # Disable the secret version.
    response = client.disable_secret_version(name)

    print('Disabled secret version: {}'.format(response.name))

Ruby

To run this code, first set up a Ruby development environment and install the Secret Manager Ruby SDK.

# 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
)

# Disable the secret version.
response = client.disable_secret_version name: name

# Print a success message.
puts "Disabled secret version: #{response.name}"

API

These examples use curl to demonstrate using the API.

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id/versions/version-id?updateMask=state" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id" \
    --data "{\"state\": \"DISABLED\"}"

Enable a secret version

Enabling a secret version changes a secret version's state from disabled to enabled. This will make the secret version accessible again.

Enabling a secret version requires the roles/secretmanager.admin IAM role on the secret version, parent secret, or 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 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 Enable from the menu.

  6. In the Enable secret version dialog, click the Enable selected versions button.

Command-line

To use Secret Manager on the command line, first Install or upgrade to version 281.0.0 or higher of the Cloud SDK.

$ gcloud secrets versions enable version-id --secret="secret-id"

C#

To run this code, first set up a C# development environment and install the Secret Manager C# SDK.


using Google.Cloud.SecretManager.V1;

public class EnableSecretVersionSample
{
    public SecretVersion EnableSecretVersion(
      string projectId = "my-project", string secretId = "my-secret", string secretVersionId = "123")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretVersionName secretVersionName = new SecretVersionName(projectId, secretId, secretVersionId);

        // Call the API.
        SecretVersion version = client.EnableSecretVersion(secretVersionName);
        return version;
    }
}

Go

To run this code, first set up a Go development environment and install the Secret Manager Go SDK.

import (
	"context"
	"fmt"

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

// enableSecretVersion enables the given secret version, enabling it to be
// accessed after previously being disabled. Other secrets versions are
// unaffected.
func enableSecretVersion(name string) error {
	// name := "projects/my-project/secrets/my-secret/versions/5"

	// 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.EnableSecretVersionRequest{
		Name: name,
	}

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

Java

To run this code, first set up a Java development environment and install the Secret Manager Java SDK.

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.cloud.secretmanager.v1.SecretVersionName;
import java.io.IOException;

public class EnableSecretVersion {

  public void enableSecretVersion() 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";
    enableSecretVersion(projectId, secretId, versionId);
  }

  // Enable an existing secret version.
  public void enableSecretVersion(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()) {
      // Build the name from the version.
      SecretVersionName secretVersionName = SecretVersionName.of(projectId, secretId, versionId);

      // Create the secret.
      SecretVersion version = client.enableSecretVersion(secretVersionName);
      System.out.printf("Enabled secret version %s\n", version.getName());
    }
  }
}

Node.js

To run this code, first set up a Node.js development environment and install the Secret Manager Node.js SDK.

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

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

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

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

  console.info(`Enabled ${version.name}`);
}

enableSecretVersion();

PHP

To run this code, first learn about using PHP on Google Cloud and install the Secret Manager PHP SDK.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\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);

// Enable the secret version.
$response = $client->enableSecretVersion($name);

// Print a success message.
printf('Enabled secret version: %s', $response->getName());

Python

To run this code, first set up a Python development environment and install the Secret Manager Python SDK.

def enable_secret_version(project_id, secret_id, version_id):
    """
    Enable the given secret version, enabling it to be accessed after
    previously being disabled. Other secrets versions are unaffected.
    """

    # Import the Secret Manager client library.
    from google.cloud import 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)

    # Disable the secret version.
    response = client.enable_secret_version(name)

    print('Enabled secret version: {}'.format(response.name))

Ruby

To run this code, first set up a Ruby development environment and install the Secret Manager Ruby SDK.

# 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
)

# Enable the secret version.
response = client.enable_secret_version name: name

# Print a success message.
puts "Enabled secret version: #{response.name}"

API

These examples use curl to demonstrate using the API.

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id/versions/version-id?updateMask=state" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id" \
    --data "{\"state\": \"ENABLED\"}"

Destroy a secret version

Destroying a secret version is permanent and cannot be undone. It is strongly recommended that you disable a secret version before destroying it. Secret Manager does not support soft deletes.

Destroying a secret version requires the roles/secretmanager.admin IAM role on the secret version, parent secret, or 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 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 Destroy from the menu.

  6. In the Destroy secret version dialog, enter the name of the secret.

  7. Click the Destroy selected versions button.

Command-line

To use Secret Manager on the command line, first Install or upgrade to version 281.0.0 or higher of the Cloud SDK.

$ gcloud secrets versions destroy version-id --secret="secret-id"

C#

To run this code, first set up a C# development environment and install the Secret Manager C# SDK.


using Google.Cloud.SecretManager.V1;

public class DestroySecretVersionSample
{
    public SecretVersion DestroySecretVersion(
      string projectId = "my-project", string secretId = "my-secret", string secretVersionId = "123")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretVersionName secretVersionName = new SecretVersionName(projectId, secretId, secretVersionId);

        // Call the API.
        SecretVersion version = client.DestroySecretVersion(secretVersionName);
        return version;
    }
}

Go

To run this code, first set up a Go development environment and install the Secret Manager Go SDK.

import (
	"context"
	"fmt"

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

// destroySecretVersion destroys the given secret version, making the payload
// irrecoverable. Other secrets versions are unaffected.
func destroySecretVersion(name string) error {
	// name := "projects/my-project/secrets/my-secret/versions/5"

	// 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.DestroySecretVersionRequest{
		Name: name,
	}

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

Java

To run this code, first set up a Java development environment and install the Secret Manager Java SDK.

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.cloud.secretmanager.v1.SecretVersionName;
import java.io.IOException;

public class DestroySecretVersion {

  public void destroySecretVersion() 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";
    destroySecretVersion(projectId, secretId, versionId);
  }

  // Destroy an existing secret version.
  public void destroySecretVersion(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()) {
      // Build the name from the version.
      SecretVersionName secretVersionName = SecretVersionName.of(projectId, secretId, versionId);

      // Create the secret.
      SecretVersion version = client.destroySecretVersion(secretVersionName);
      System.out.printf("Destroyed secret version %s\n", version.getName());
    }
  }
}

Node.js

To run this code, first set up a Node.js development environment and install the Secret Manager Node.js SDK.

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

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

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

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

  console.info(`Destroyed ${version.name}`);
}

destroySecretVersion();

PHP

To run this code, first learn about using PHP on Google Cloud and install the Secret Manager PHP SDK.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\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);

// Destroy the secret version.
$response = $client->destroySecretVersion($name);

// Print a success message.
printf('Destroyed secret version: %s', $response->getName());

Python

To run this code, first set up a Python development environment and install the Secret Manager Python SDK.

def destroy_secret_version(project_id, secret_id, version_id):
    """
    Destroy the given secret version, making the payload irrecoverable. Other
    secrets versions are unaffected.
    """

    # Import the Secret Manager client library.
    from google.cloud import 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)

    # Destroy the secret version.
    response = client.destroy_secret_version(name)

    print('Destroyed secret version: {}'.format(response.name))

Ruby

To run this code, first set up a Ruby development environment and install the Secret Manager Ruby SDK.

# 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
)

# Destroy the secret version.
response = client.destroy_secret_version name: name

# Print a success message.
puts "Destroyed secret version: #{response.name}"

API

These examples use curl to demonstrate using the API.

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id/versions/version-id:destroy" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id"