シークレットを作成する

このトピックでは、シークレットを作成する方法について説明します。シークレットには 1 つ以上のシークレット バージョンとともに、ラベルやレプリケーション情報などのメタデータが含まれます。シークレットの実際のコンテンツは、シークレット バージョンに保存されます。

始める前に

  1. プロジェクトごとに 1 回、Secret Manager API を有効にします
  2. プロジェクト、フォルダ、または組織に対する Secret Manager 管理者ロール(roles/secretmanager.admin)を割り当てます。
  3. 次のいずれかの方法で Secret Manager API への認証を行います。

    • クライアント ライブラリを使用して Secret Manager API にアクセスする場合は、アプリケーションのデフォルト認証情報を設定します。
    • Google Cloud CLI を使用して Secret Manager API にアクセスする場合は、Google Cloud CLI 認証情報を使用して認証します。
    • REST 呼び出しを認証するには、Google Cloud CLI の認証情報またはアプリケーションのデフォルト認証情報を使用します。

シークレットを作成する

Console

  1. Google Cloud コンソールの [Secret Manager] ページに移動します。

    [Secret Manager] ページに移動

  2. [シークレット マネージャー] ページで、[シークレットを作成] をクリックします。

  3. [シークレットの作成] ページの [名前] に、シークレットの名前を入力します(例: my-secret)。シークレット名には大文字と小文字、数字、ハイフン、アンダースコアを使用できます。名前の最大長は 255 文字です。

  4. (省略可)最初のシークレットの作成時にシークレット バージョンも追加するには、[シークレットの値] フィールドにシークレットの値を入力します(例: abcd1234)。シークレット値の形式は任意ですが、64 KiB 以下にする必要があります。

  5. [リージョン] セクションは変更しません。

  6. [シークレットを作成] ボタンをクリックします。

gcloud

Secret Manager をコマンドラインで使用するには、まず Google Cloud CLI のバージョン 378.0.0 以降をインストールまたはアップグレードします。Compute Engine または GKE では、cloud-platform スコープを使用して認証する必要があります。

$ gcloud secrets create secret-id \
    --replication-policy="automatic"

C#

このコードを実行するには、まず C# 開発環境を設定し、Secret Manager C# SDK をインストールします。 Compute Engine または GKE では、cloud-platform スコープを使用して認証する必要があります。


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;

public class CreateSecretSample
{
    public Secret CreateSecret(
      string projectId = "my-project", string secretId = "my-secret")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the parent resource name.
        ProjectName projectName = new ProjectName(projectId);

        // Build the secret.
        Secret secret = new Secret
        {
            Replication = new Replication
            {
                Automatic = new Replication.Types.Automatic(),
            },
        };

        // Call the API.
        Secret createdSecret = client.CreateSecret(projectName, secretId, secret);
        return createdSecret;
    }
}

Go

このコードを実行するには、まず Go 開発環境を設定し、Secret Manager Go SDK をインストールします。 Compute Engine または GKE では、cloud-platform スコープを使用して認証する必要があります。

import (
	"context"
	"fmt"
	"io"

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

// createSecret creates a new secret with the given name. A secret is a logical
// wrapper around a collection of secret versions. Secret versions hold the
// actual secret material.
func createSecret(w io.Writer, parent, id string) error {
	// parent := "projects/my-project"
	// id := "my-secret"

	// 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.CreateSecretRequest{
		Parent:   parent,
		SecretId: id,
		Secret: &secretmanagerpb.Secret{
			Replication: &secretmanagerpb.Replication{
				Replication: &secretmanagerpb.Replication_Automatic_{
					Automatic: &secretmanagerpb.Replication_Automatic{},
				},
			},
		},
	}

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

Java

このコードを実行するには、まず Java 開発環境を設定し、Secret Manager Java SDK をインストールします。 Compute Engine または GKE では、cloud-platform スコープを使用して認証する必要があります。

import com.google.cloud.secretmanager.v1.ProjectName;
import com.google.cloud.secretmanager.v1.Replication;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import java.io.IOException;

public class CreateSecret {

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

  // Create a new secret with automatic replication.
  public static void createSecret(String projectId, String secretId) throws IOException {
    // Initialize the 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 from the project.
      ProjectName projectName = ProjectName.of(projectId);

      // Build the secret to create.
      Secret secret =
          Secret.newBuilder()
              .setReplication(
                  Replication.newBuilder()
                      .setAutomatic(Replication.Automatic.newBuilder().build())
                      .build())
              .build();

      // Create the secret.
      Secret createdSecret = client.createSecret(projectName, secretId, secret);
      System.out.printf("Created secret %s\n", createdSecret.getName());
    }
  }
}

Node.js

このコードを実行するには、まず Node.js 開発環境を設定し、Secret Manager Node.js SDK をインストールします。 Compute Engine または GKE では、cloud-platform スコープを使用して認証する必要があります。

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

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

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

async function createSecret() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: {
      replication: {
        automatic: {},
      },
    },
  });

  console.log(`Created secret ${secret.name}`);
}

createSecret();

PHP

このコードを実行するには、まず Google Cloud での PHP の使用について確認して、Secret Manager PHP SDK をインストールします。 Compute Engine または GKE では、cloud-platform スコープを使用して認証する必要があります。

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\CreateSecretRequest;
use Google\Cloud\SecretManager\V1\Replication;
use Google\Cloud\SecretManager\V1\Replication\Automatic;
use Google\Cloud\SecretManager\V1\Secret;
use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient;

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

    // Build the resource name of the parent project.
    $parent = $client->projectName($projectId);

    $secret = new Secret([
        'replication' => new Replication([
            'automatic' => new Automatic(),
        ]),
    ]);

    // Build the request.
    $request = CreateSecretRequest::build($parent, $secretId, $secret);

    // Create the secret.
    $newSecret = $client->createSecret($request);

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

Python

このコードを実行するには、まず Python 開発環境を設定し、Secret Manager Python SDK をインストールします。 Compute Engine または GKE では、cloud-platform スコープを使用して認証する必要があります。

def create_secret(project_id: str, secret_id: str) -> secretmanager.CreateSecretRequest:
    """
    Create a new secret with the given name. A secret is a logical wrapper
    around a collection of secret versions. Secret versions hold the actual
    secret material.
    """

    # 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 project.
    parent = f"projects/{project_id}"

    # Create the secret.
    response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
            "secret": {"replication": {"automatic": {}}},
        }
    )

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

Ruby

このコードを実行するには、まず Ruby 開発環境を設定し、Secret Manager Ruby SDK をインストールします。 Compute Engine または GKE では、cloud-platform スコープを使用して認証する必要があります。

# 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 project.
parent = client.project_path project: project_id

# Create the secret.
secret = client.create_secret(
  parent:    parent,
  secret_id: secret_id,
  secret:    {
    replication: {
      automatic: {}
    }
  }
)

# Print the new secret name.
puts "Created secret: #{secret.name}"

API

次の例では、API の使用を示すために curl を使用します。gcloud auth print-access-token を使用してアクセス トークンを生成できます。Compute Engine または GKE では、cloud-platform スコープを使用して認証する必要があります。

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets?secretId=secret-id" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --data "{\"replication\": {\"automatic\": {}}}"

シークレットに適したレプリケーション ポリシーを選択するには、レプリケーション ポリシーを選択するをご覧ください。

シークレット バージョンを追加する

Secret Manager では、シークレット バージョンを使用してシークレット データが自動的にバージョニングされます。アクセス、破棄、無効化、有効化などのほとんどの操作は、シークレット バージョンで行われます。Secret Manager では、シークレットを 42 のような特定のバージョン、または latest のような変動的なエイリアスに固定できます。シークレット バージョンを追加する方法をご確認ください。

シークレット バージョンにアクセス

特定のシークレット バージョンのシークレット データにアクセスし、認証を成功させるためには、シークレット バージョンにアクセスするをご覧ください。

次のステップ