Add a secret version

Secret data is immutable and most operations take place on secret versions. A secret version contains the actual secret data, along with state and metadata about the secret. This topic describes how to add a secret version.

Required roles

To get the permissions that you need to add a secret version, ask your administrator to grant you the following IAM roles on a secret:

For more information about granting roles, see Manage access.

You might also be able to get the required permissions through custom roles or other predefined roles.

Add a secret version

Console

  1. Go to the Secret Manager page in the Google Cloud console.

    Go to the Secret Manager page

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

  3. In the Add new version dialog, in the Secret value field, enter a value for the secret (e.g. abcd1234).

  4. Click the Add new version button.

gcloud

To use Secret Manager on the command line, first Install or upgrade to version 378.0.0 or higher of the Google Cloud CLI. On Compute Engine or GKE, you must authenticate with the cloud-platform scope.

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

$ gcloud 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 it appears as plaintext in the list of processes and may be captured by other system users. Note that the command with the plaintext will also be in your shell history.

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

Optionally: Add a version from a file's contents when first creating a secret:

$ gcloud secrets create secret-id --data-file="/path/to/file.txt"

C#

To run this code, first set up a C# development environment and install the Secret Manager C# SDK. On Compute Engine or GKE, you must authenticate with the cloud-platform scope.


using System.Text;
using Google.Cloud.SecretManager.V1;
using Google.Protobuf;

public class AddSecretVersionSample
{
    public SecretVersion AddSecretVersion(
      string projectId = "my-project", string secretId = "my-secret",
      string data = "my secret data")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

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

        // Convert the payload to bytes.
        SecretPayload payload = new SecretPayload
        {
            Data = ByteString.CopyFrom(data, Encoding.UTF8),
        };

        // Call the API.
        SecretVersion version = client.AddSecretVersion(secretName, payload);
        return version;
    }
}

Go

To run this code, first set up a Go development environment and install the Secret Manager Go SDK. On Compute Engine or GKE, you must authenticate with the cloud-platform scope.

import (
	"context"
	"fmt"
	"hash/crc32"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
)

// 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")
	// Compute checksum, use Castagnoli polynomial. Providing a checksum
	// is optional.
	crc32c := crc32.MakeTable(crc32.Castagnoli)
	checksum := int64(crc32.Checksum(payload, crc32c))

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

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

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

Java

To run this code, first set up a Java development environment and install the Secret Manager Java SDK. On Compute Engine or GKE, you must authenticate with the cloud-platform scope.

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.cloud.secretmanager.v1.SecretPayload;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.zip.CRC32C;
import java.util.zip.Checksum;

public class AddSecretVersion {

  public static 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 static 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 secretName = SecretName.of(projectId, secretId);
      byte[] data = "my super secret data".getBytes();
      // Calculate data checksum. The library is available in Java 9+.
      // If using Java 8, the following library may be used:
      // https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/files/Crc32c
      Checksum checksum = new CRC32C();
      checksum.update(data, 0, data.length);

      // Create the secret payload.
      SecretPayload payload =
          SecretPayload.newBuilder()
              .setData(ByteString.copyFrom(data))
              // Providing data checksum is optional.
              .setDataCrc32C(checksum.getValue())
              .build();

      // Add the secret version.
      SecretVersion version = client.addSecretVersion(secretName, payload);
      System.out.printf("Added 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. On Compute Engine or GKE, you must authenticate with the cloud-platform scope.

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

To run this code, first learn about using PHP on Google Cloud and install the Secret Manager PHP SDK. On Compute Engine or GKE, you must authenticate with the cloud-platform scope.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient;
use Google\Cloud\SecretManager\V1\AddSecretVersionRequest;
use Google\Cloud\SecretManager\V1\SecretPayload;

/**
 * @param string $projectId Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId  Your secret ID (e.g. 'my-secret')
 */
function add_secret_version(string $projectId, string $secretId): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

    // Build the resource name of the parent secret and the payload.
    $parent = $client->secretName($projectId, $secretId);
    $secretPayload = new SecretPayload([
        'data' => 'my super secret data',
    ]);

    // Build the request.
    $request = AddSecretVersionRequest::build($parent, $secretPayload);

    // Access the secret version.
    $response = $client->addSecretVersion($request);

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

Python

To run this code, first set up a Python development environment and install the Secret Manager Python SDK. On Compute Engine or GKE, you must authenticate with the cloud-platform scope.

from google.cloud import secretmanager
import google_crc32c  # type: ignore


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

    # 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_bytes = payload.encode("UTF-8")

    # Calculate payload checksum. Passing a checksum in add-version request
    # is optional.
    crc32c = google_crc32c.Checksum()
    crc32c.update(payload_bytes)

    # Add the secret version.
    response = client.add_secret_version(
        request={
            "parent": parent,
            "payload": {
                "data": payload_bytes,
                "data_crc32c": int(crc32c.hexdigest(), 16),
            },
        }
    )

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

Ruby

To run this code, first set up a Ruby development environment and install the Secret Manager Ruby SDK. On Compute Engine or GKE, you must authenticate with the cloud-platform scope.

# 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

These examples use curl to demonstrate using the API. You can generate access tokens with gcloud auth print-access-token. On Compute Engine or GKE, you must authenticate with the cloud-platform scope.

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/v1/projects/project-id/secrets/secret-id:addVersion" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --data "{\"payload\": {\"data\": \"${SECRET_DATA}\"}}"

Secret version states

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.

What's next