Secret-Version hinzufügen

Fügt eine neue Version des Secrets hinzu.

Dokumentationsseiten mit diesem Codebeispiel

Die folgenden Dokumente enthalten das Codebeispiel im Kontext:

Codebeispiel

C#

Informationen zum Installieren und Verwenden der Clientbibliothek für Secret Manager finden Sie unter Secret Manager-Clientbibliotheken.


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

Informationen zum Installieren und Verwenden der Clientbibliothek für Secret Manager finden Sie unter Secret Manager-Clientbibliotheken.

import (
	"context"
	"fmt"
	"io"

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

// 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)
	}
	defer client.Close()

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

Informationen zum Installieren und Verwenden der Clientbibliothek für Secret Manager finden Sie unter Secret Manager-Clientbibliotheken.

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;

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

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

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

Node.js

Informationen zum Installieren und Verwenden der Clientbibliothek für Secret Manager finden Sie unter Secret Manager-Clientbibliotheken.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für Secret Manager finden Sie unter Secret Manager-Clientbibliotheken.

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

Informationen zum Installieren und Verwenden der Clientbibliothek für Secret Manager finden Sie unter Secret Manager-Clientbibliotheken.

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

    # 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(
        request={"parent": parent, "payload": {"data": payload}}
    )

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

Ruby

Informationen zum Installieren und Verwenden der Clientbibliothek für Secret Manager finden Sie unter Secret Manager-Clientbibliotheken.

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

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud-Produkte finden Sie im Google Cloud-Beispielbrowser.