Add a regional 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 page describes how to add a secret version.

For more information about versioning, see this video on versioning.

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 to projects, folders, and organizations.

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

IAM roles can't be granted on a secret version.

Add a secret version

To add a secret version, use one of the following methods:

Console

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

    Go to Secret Manager

  2. On the Secret Manager page, click the Regional secrets tab, and then locate the secret for which you want to add the new version.

  3. Click the Actions menu associated with that secret, and then click Add new version. The Add new version dialog appears.

  4. In the Secret value field, enter a value for the secret such as abcd1234. Alternatively, you can upload a file containing the secret value.

  5. Click Add new version.

gcloud

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

Before using any of the command data below, make the following replacements:

  • SECRET_ID: the ID of the secret or fully qualified identifier for the secret
  • LOCATION: the Google Cloud location of the secret
  • FILE_PATH: the full path (including file name) to the file containing the version details

Execute the following command:

Linux, macOS, or Cloud Shell

gcloud secrets versions add SECRET_ID --location=LOCATION --data-file="FILE_PATH"

Windows (PowerShell)

gcloud secrets versions add SECRET_ID --location=LOCATION --data-file="FILE_PATH"

Windows (cmd.exe)

gcloud secrets versions add SECRET_ID --location=LOCATION --data-file="FILE_PATH"

The response contains the newly created secret version.

Add a secret version directly on the command line

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.

Before using any of the command data below, make the following replacements:

  • SECRET_DATA: the data that you want to store in the secret version
  • SECRET_ID: the ID of the secret or fully qualified identifier for the secret
  • LOCATION: the Google Cloud location of the secret

Execute the following command:

Linux, macOS, or Cloud Shell

echo -n "SECRET_DATA" | \
    gcloud secrets versions add SECRET_ID --location=LOCATION --data-file=-

Windows (PowerShell)

echo -n "SECRET_DATA" | `
    gcloud secrets versions add SECRET_ID --location=LOCATION --data-file=-

Windows (cmd.exe)

echo -n "SECRET_DATA" | ^
    gcloud secrets versions add SECRET_ID --location=LOCATION --data-file=-

The response contains the newly created secret version.

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

Before using any of the command data below, make the following replacements:

  • SECRET_ID: the ID of the secret or fully qualified identifier for the secret
  • LOCATION: the Google Cloud location of the secret
  • FILE_PATH: the full path (including file name) to the file containing the version details

Execute the following command:

Linux, macOS, or Cloud Shell

gcloud secrets create SECRET_ID --location=LOCATION --data-file="FILE_PATH"

Windows (PowerShell)

gcloud secrets create SECRET_ID --location=LOCATION --data-file="FILE_PATH"

Windows (cmd.exe)

gcloud secrets create SECRET_ID --location=LOCATION --data-file="FILE_PATH"

The response contains the newly created secret version.

REST

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

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

Before using any of the request data, make the following replacements:

  • LOCATION: the Google Cloud location of the secret
  • PROJECT_ID: the Google Cloud project ID
  • SECRET_ID: the ID of the secret or fully qualified identifier for the secret

HTTP method and URL:

POST https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID:addVersion

Request JSON body:

{"payload": {"data": "${SECRET_DATA}"}}

To send your request, choose one of these options:

curl

Save the request body in a file named request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID:addVersion"

PowerShell

Save the request body in a file named request.json, and execute the following command:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID:addVersion" | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/1",
  "createTime": "2024-03-25T08:24:13.153705Z",
  "state": "ENABLED",
  "etag": "\"161477e6071da9\""
}

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"
	"google.golang.org/api/option"
)

// addSecretVersion adds a new secret version to the given secret with the
// provided payload.
func AddRegionalSecretVersion(w io.Writer, projectId, locationId, secretId string) error {
	// parent := "projects/my-project/locations/my-location/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()

	//Endpoint to send the request to regional server
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationId)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))

	if err != nil {
		return fmt.Errorf("failed to create regional secretmanager client: %w", err)
	}
	defer client.Close()

	parent := fmt.Sprintf("projects/%s/locations/%s/secrets/%s", projectId, locationId, secretId)

	// 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 regional secret version: %w", err)
	}
	fmt.Fprintf(w, "Added regional 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.SecretManagerServiceSettings;
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 AddRegionalSecretVersion {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Your GCP project ID.
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // Resource ID of the secret.
    String secretId = "your-secret-id";
    addRegionalSecretVersion(projectId, locationId, secretId);
  }

  // Add a new version to the existing regional secret.
  public static SecretVersion addRegionalSecretVersion(
      String projectId, String locationId, String secretId) 
      throws IOException {

    // Endpoint to call the regional secret manager sever
    String apiEndpoint = String.format("secretmanager.%s.rep.googleapis.com:443", locationId);
    SecretManagerServiceSettings secretManagerServiceSettings =
        SecretManagerServiceSettings.newBuilder().setEndpoint(apiEndpoint).build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (SecretManagerServiceClient client = 
        SecretManagerServiceClient.create(secretManagerServiceSettings)) {
      SecretName secretName = 
          SecretName.ofProjectLocationSecretName(projectId, locationId, secretId);
      byte[] data = "my super secret data".getBytes();
      // Calculate data checksum. The library is available in Java 9+.
      // For Java 8, use:
      // 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 regional secret version %s\n", version.getName());

      return version;
    }
  }
}

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 projectId = 'my-project';
// const locationId = 'location';
// const secretId = 'my-secret';

const parent = `projects/${projectId}/locations/${locationId}/secrets/${secretId}`;
// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Adding the endpoint to call the regional secret manager sever
const options = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;

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

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

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

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

addRegionalSecretVersion();

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_v1
import google_crc32c


def add_regional_secret_version(
    project_id: str,
    location_id: str,
    secret_id: str,
    payload: str,
) -> secretmanager_v1.SecretVersion:
    """
    Adds a new secret version to the given secret with the provided payload.
    """

    # Endpoint to call the regional secret manager sever.
    api_endpoint = f"secretmanager.{location_id}.rep.googleapis.com"

    # Create the Secret Manager client.
    client = secretmanager_v1.SecretManagerServiceClient(
        client_options={"api_endpoint": api_endpoint},
    )

    # Build the resource name of the parent secret.
    parent = f"projects/{project_id}/locations/{location_id}/secrets/{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}")
    return response

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.

You are billed for both enabled and disabled secret versions. You are not billed for secret versions that are in the destroyed state.

What's next