Add secret version

Adds a new version of the secret.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

To learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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 learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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 learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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 learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * 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 learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// 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 learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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 learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.