יצירת סוד אזורי

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

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

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

  2. מגדירים את Secret Manager לשימוש בנקודת קצה אזורית.

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

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

    המסוף

    כשמשתמשים במסוף 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, לוחצים על הכרטיסייה Regional secrets ואז על Create regional secret.

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

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

  5. ברשימה Region, בוחרים את המיקום שבו רוצים לאחסן את הסוד האזורי.

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

gcloud

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

  • SECRET_ID: המזהה של הסוד.
  • LOCATION: Google Cloud המיקום של הסוד.

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

‫Linux,‏ macOS או Cloud Shell

gcloud secrets create SECRET_ID \
    --location=LOCATION

‏Windows (PowerShell)

gcloud secrets create SECRET_ID `
    --location=LOCATION

Windows‏ (cmd.exe)

gcloud secrets create SECRET_ID ^
    --location=LOCATION

REST

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

  • LOCATION: Google Cloud המיקום של הסוד.
  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • SECRET_ID: המזהה של הסוד.

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

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

גוף בקשת JSON:

{}

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

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

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

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

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

// 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 CreateRegionalSecret(w io.Writer, projectId, locationId, id string) error {
	// parent := "projects/my-project/locations/my-location"
	// id := "my-secret"

	// 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 secretmanager client: %w", err)
	}
	defer client.Close()

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

	// Build the request.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: id,
	}

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

Java

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח ב-Java ולהתקין את Secret Manager Java SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף cloud-platform.

import com.google.cloud.secretmanager.v1.LocationName;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import java.io.IOException;

public class CreateRegionalSecret {

  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 to create.
    String secretId = "your-secret-id";
    createRegionalSecret(projectId, locationId, secretId);
  }

  // Create a new regional secret 
  public static Secret createRegionalSecret(
      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 the 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)) {
      // Build the parent name from the project.
      LocationName location = LocationName.of(projectId, locationId);

      // Build the regional secret to create.
      Secret secret =
          Secret.newBuilder().build();

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

      return createdSecret;
    }
  }
}

Node.js

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח של Node.js ולהתקין את Secret Manager Node.js SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף cloud-platform.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project'
// const locationId = 'locationId';
// const secretId = 'my-secret';
const parent = `projects/${projectId}/locations/${locationId}`;

// Imports the Secret Manager libray

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

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

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

createRegionalSecret();

Python

כדי להריץ את הקוד הזה, קודם צריך להגדיר סביבת פיתוח בשפת Python ולהתקין את Secret Manager Python SDK. ב-Compute Engine או ב-GKE, צריך לעבור אימות באמצעות ההיקף cloud-platform.

from google.cloud import secretmanager_v1


def create_regional_secret(
    project_id: str,
    location_id: str,
    secret_id: str,
    ttl: Optional[str] = None,
) -> secretmanager_v1.Secret:
    """
    Creates a new regional secret with the given name.
    """

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

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

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

    return response

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

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

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

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

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