יצירת סוד

בדף הזה מוסבר איך ליצור סוד. סוד מכיל גרסה אחת או יותר של הסוד, וגם מטא-נתונים כמו תוויות ומדיניות שכפול. התוכן בפועל של סוד מאוחסן בגרסת סוד.

לפני שמתחילים

  1. מפעילים את Secret Manager API.

  2. מגדירים אימות.

    צריך לבחור את הכרטיסייה הרלוונטית לאופן שבו תכננתם להשתמש בדוגמאות בדף הזה:

    המסוף

    כשמשתמשים במסוף Google Cloud כדי לגשת לשירותים ולממשקי ה-API, לא צריך להגדיר אימות. Google Cloud

    gcloud

    במסוף Google Cloud , מפעילים את Cloud Shell.

    הפעלת Cloud Shell

    בחלק התחתון של Google Cloud המסוף יתחיל סשן של Cloud Shell ותופיע הודעה של שורת הפקודה. Cloud Shell היא סביבת מעטפת שבה ה-CLI של Google Cloud מותקן ומוגדרים ערכים לפרויקט הקיים. הסשן יופעל תוך כמה שניות.

    REST

    כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של API בארכיטקטורת REST שבדף הזה, צריך להשתמש בפרטי הכניסה שאתם נותנים ל-CLI של gcloud.

      התקינו את ה-CLI של Google Cloud.

      אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

    מידע נוסף מופיע במאמר אימות לשימוש ב-REST במסמכי האימות של Google Cloud .

התפקידים הנדרשים

כדי לקבל את ההרשאות שדרושות ליצירת סוד, צריך לבקש מהאדמין להקצות לכם את תפקיד ה-IAM‏ Secret Manager Admin (roles/secretmanager.admin) בפרויקט, בתיקייה או בארגון. כדי לקרוא הסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

יכול להיות שאפשר לקבל את ההרשאות הנדרשות גם באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש.

יצירת סוד

אפשר ליצור סודות באמצעות מסוף Google Cloud , Google Cloud CLI,‏ Secret Manager API או ספריות הלקוח של Secret Manager.

המסוף

  1. נכנסים לדף Secret Manager במסוף Google Cloud .

    מעבר אל Secret Manager

  2. בדף Secret Manager, לוחצים על Create secret.

  3. בדף יצירת Secret, מזינים שם ל-Secret בשדה שם. שם הסוד יכול להכיל אותיות רישיות וקטנות, ספרות, מקפים וקווים תחתונים. האורך המקסימלי של השם הוא 255 תווים.

  4. מזינים ערך לסוד (לדוגמה, abcd1234). ערך הסוד יכול להיות בכל פורמט, אבל הוא לא יכול להיות גדול מ-64KiB. אפשר גם להעלות קובץ טקסט שמכיל את הערך הסודי באמצעות האפשרות העלאת קובץ. הפעולה הזו יוצרת באופן אוטומטי את גרסת הסוד.

  5. לוחצים על Create secret (יצירת סוד).

gcloud

לפני השימוש בנתוני הפקודה הבאים, צריך להחליף את הנתונים הבאים:

  • SECRET_ID: המזהה של הסוד.
  • REPLICATION_POLICY: מדיניות השכפול של הסוד, שיכולה להיות אוטומטית או מנוהלת על ידי המשתמש.

מריצים את הפקודה הבאה:

‫Linux,‏ macOS או Cloud Shell

gcloud secrets create SECRET_ID \
    --replication-policy="REPLICATION_POLICY"

‏Windows (PowerShell)

gcloud secrets create SECRET_ID `
    --replication-policy="REPLICATION_POLICY"

Windows‏ (cmd.exe)

gcloud secrets create SECRET_ID ^
    --replication-policy="REPLICATION_POLICY"

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • SECRET_ID: המזהה של הסוד.
  • REPLICATION_POLICY: מדיניות השכפול של הסוד, שיכולה להיות אוטומטית או מנוהלת על ידי המשתמש.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID

גוף בקשת JSON:

{
  "replication": {
    "REPLICATION_POLICY": {}
  }
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

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

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$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.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

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

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"
	"time"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
	"google.golang.org/protobuf/types/known/durationpb"
)

// createSecretWithTTL creates a new secret with the given name and ttl.
func createSecretWithTTL(w io.Writer, parent, id string, d time.Duration) error {
	// parent := "projects/my-project"
	// id := "my-secret"

	expiration := &secretmanagerpb.Secret_Ttl{Ttl: durationpb.New(d)}

	// 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{},
				},
			},
			Expiration: expiration,
		},
	}

	// 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 with ttl: %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 com.google.protobuf.Duration;
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);

      // Optionally set a TTL for the secret. This demonstrates how to configure
      // a secret to be automatically deleted after a certain period. The TTL is
      // specified in seconds (e.g., 900 for 15 minutes). This can be useful
      // for managing sensitive data and reducing storage costs.
      Duration ttl = Duration.newBuilder().setSeconds(900).build();

      // Build the secret to create.
      Secret secret =
          Secret.newBuilder()
              .setReplication(
                  Replication.newBuilder()
                      .setAutomatic(Replication.Automatic.newBuilder().build())
                      .build())
              .setTtl(ttl)
              .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';
// const ttl = undefined // Optional: Specify TTL in seconds (e.g., '900s' for 15 minutes).

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

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

async function createSecret() {
  const secretConfig = {
    replication: {
      automatic: {},
    },
  };

  // Add TTL to the secret configuration if provided
  if (ttl) {
    secretConfig.ttl = {
      seconds: parseInt(ttl.replace('s', ''), 10),
    };
    console.log(`Secret TTL set to ${ttl}`);
  }

  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: secretConfig,
  });

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

createSecret();

PHP

כדי להריץ את הקוד הזה, קודם צריך לקרוא על שימוש ב-PHP ב-Google Cloud ולהתקין את 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.

# Import the Secret Manager client library.
from google.cloud import secretmanager


def create_secret(
    project_id: str, secret_id: str, ttl: Optional[str] = None
) -> secretmanager.Secret:
    """
    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.

     Args:
        project_id (str): The project ID where the secret is to be created.
        secret_id (str): The ID to assign to the new secret. This ID must be unique within the project.
        ttl (Optional[str]): An optional string that specifies the secret's time-to-live in seconds with
                             format (e.g., "900s" for 15 minutes). If specified, the secret
                             versions will be automatically deleted upon reaching the end of the TTL period.

    Returns:
        secretmanager.Secret: An object representing the newly created secret, containing details like the
                              secret's name, replication settings, and optionally its TTL.

    Example:
        # Create a secret with automatic replication and no TTL
        new_secret = create_secret("my-project", "my-new-secret")

        # Create a secret with a TTL of 30 days
        new_secret_with_ttl = create_secret("my-project", "my-timed-secret", "7776000s")
    """

    # 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": {}}, "ttl": ttl},
        }
    )

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

כדי לבחור את מדיניות השכפול המתאימה לסוד שלכם, קראו את המאמר בנושא בחירת מדיניות שכפול.

הוספת גרסה של סוד

‫Secret Manager יוצר גרסאות אוטומטיות של נתוני סודות באמצעות גרסאות של סודות. פעולות שקשורות למפתחות, כמו גישה, השמדה, השבתה והפעלה, מוחלות על גרסאות ספציפיות של סודות. באמצעות Secret Manager, אפשר לשייך סודות לגרסאות ספציפיות כמו 42 או לכינויים דינמיים כמו latest. מידע נוסף זמין במאמר הוספת גרסה של סוד.

גישה לגרסה של סוד

כדי לגשת לנתונים הסודיים מגרסה סודית מסוימת לצורך אימות מוצלח, אפשר לעיין במאמר בנושא גישה לגרסה סודית.

המאמרים הבאים