יצירת קובצי snapshot של דיסקים רגילים ושל דיסקים בארכיון

יצירת תמונות מצב רגילות כדי לגבות מעת לעת נתונים מנפחי אחסון של דיסקים מתמידים אזוריים ושל Google Cloud Hyperdisk.

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

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

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

כדי לקבל את ההרשאות שדרושות ליצירה ולניהול של תמונות מצב, צריך לבקש מהאדמין להקצות לכם את תפקידי ה-IAM הבאים בפרויקט:

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

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

ההרשאות הנדרשות

כדי ליצור ולנהל תמונות מצב, צריך את ההרשאות הבאות:

  • compute.snapshots.create בפרויקט
  • כדי ליצור תמונת מצב של דיסק האתחול של מכונה שמצורף אליה חשבון שירות: iam.serviceAccounts.actAs בחשבון השירות של המכונה
  • כדי ליצור snapshot של דיסק אזורי: compute.disks.createSnapshot
  • אם הכונן הוא כונן אזורי ואתם רוצים ליצור תמונת מצב של הנתונים בכונן:
    • compute.instances.useReadOnly
    • compute.disks.createSnapshot
  • אם הדיסק הוא דיסק אזורי ואתם רוצים ליצור snapshot של נקודת שחזור של רפליקה: compute.disks.createSnapshot
  • אם רוצים ליצור snapshot בהיקף אזורי:
    • compute.regionSnapshots.create
    • compute.disks.useReadOnly
  • כדי ליצור קובץ snapshot של דיסק אזורי מנקודת שחזור של העתק: compute.disks.createSnapshot בדיסק
  • כדי ליצור תזמון של snapshot: compute.resourcePolicies.create בפרויקט או בארגון
  • כדי לצרף לוח זמנים של תמונות במסגרת לדיסק:
    • compute.disks.addResourcePolicies בדיסק
    • compute.resourcePolicies.use במדיניות המשאבים
  • כדי למחוק snapshot:
    • compute.snapshots.delete בתמונת המצב
    • compute.snapshots.list בפרויקט

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

הכנה ליצירת תמונות מצב

כדי להתכונן ליצירת תמונות מצב של כרכים של Persistent Disk או Hyperdisk, פועלים לפי השלבים הבאים:

יצירת תמונת מצב של דיסק

השלבים ליצירת קובץ snapshot של דיסק משתנים בהתאם לסוג הדיסק: דיסק אזורי או דיסק אזורי.

יצירת קובץ snapshot של דיסק אזורי

המסוף

  1. נכנסים לדף Create a Snapshot במסוף Google Cloud .

    כניסה לדף Create a Snapshot
  2. מזינים שם לתמונת המצב.
  3. בוחרים סוג תמונת מצב. ברירת המחדל היא תמונת מצב של STANDARD, שהיא האפשרות הטובה ביותר לגיבוי לטווח ארוך ולתוכנית התאוששות מאסון (DR).

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

  4. אופציונלי: מזינים תיאור של התמונה.
  5. בקטע דיסק מקור, בוחרים את הדיסק הקיים שרוצים ליצור ממנו תמונת מצב.
  6. בקטע מיקום, בוחרים את מיקום האחסון של התמונה.

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

    1. בוחרים את סוג מיקום האחסון שרוצים לשמור בו את התמונה.

      • בוחרים באפשרות Multi-regional (אזורים מרובים) כדי ליהנות מזמינות גבוהה יותר בעלות גבוהה יותר.
      • כדי לקבל יותר שליטה על המיקום הפיזי של הנתונים בעלות נמוכה יותר, בוחרים באפשרות תמונות מצב אזוריות.
    2. בשדה Select location (בחירת מיקום), בוחרים את האזור הספציפי או את מספר האזורים שרוצים להשתמש בהם. כדי להשתמש באזור או במספר אזורים שהכי קרובים לדיסק המקור, בוחרים באפשרות Based on disk's location (על סמך המיקום של הדיסק).
  7. לוחצים על Create (יצירה) כדי ליצור את התמונה.

gcloud

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

  • כדי ליצור snapshot במיקום ברירת המחדל המוגדר מראש או בהתאמה אישית בהגדרות ה-snapshot, משתמשים בפקודה gcloud compute snapshots create.

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk-zone=SOURCE_ZONE \
        --source-disk=SOURCE_DISK_NAME \
        --snapshot-type=SNAPSHOT_TYPE
    
  • לחלופין, כדי לבטל את הגדרות הצילום וליצור צילום במיקום אחסון מותאם אישית, צריך לכלול את הדגל --storage-location כדי לציין איפה לאחסן את הצילום.

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk-zone=SOURCE_ZONE \
        --source-disk=SOURCE_DISK_NAME \
        --snapshot-type=SNAPSHOT_TYPE \
        --storage-location=STORAGE_LOCATION
    
  • (תצוגה מקדימה) כדי ליצור תמונת מצב בהיקף אזורי באזור מותר, צריך לכלול את הדגל --region כדי לציין איפה ליצור את תמונת המצב.

    gcloud beta compute snapshots create SNAPSHOT_NAME \
        --region=SNAPSHOT_SCOPE_REGION
        --source-disk=SOURCE_DISK_NAME \
        --source-disk-zone=SOURCE_ZONE \
        --snapshot-type=SNAPSHOT_TYPE
    

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

  • SNAPSHOT_NAME: שם לקובץ ה-snapshot.
  • SOURCE_ZONE: האזור של דיסק המקור.
  • SOURCE_DISK_NAME: השם של נפח האחסון המתמיד (persistent disk) שממנו רוצים ליצור קובץ snapshot.
  • SNAPSHOT_TYPE: סוג ה-snapshot, ‏ STANDARD או ARCHIVE. אם לא מציינים סוג של snapshot, נוצר STANDARD snapshot.
  • STORAGE_LOCATION: אופציונלי: בשביל תמונות מצב בהיקף גלובלי, אזור Cloud Storage או אזור Cloud Storage שבו רוצים לאחסן את תמונת המצב. אפשר לציין רק מיקום אחסון אחד.

    משתמשים בפרמטר --storage-location רק כשרוצים לשנות את מיקום האחסון שמוגדר כברירת מחדל בהגדרות של התמונה, בין אם הוא מוגדר מראש או בהתאמה אישית.

  • SNAPSHOT_SCOPE_REGION: אופציונלי: אם מדובר בקובץ snapshot בהיקף אזורי, מציינים את האזור שה-snapshot מוגבל אליו. אם כוללים את הפרמטר הזה, אי אפשר להשתמש בפרמטר --storage-location. הדומיין STORAGE_LOCATION מוגדר אוטומטית ל-SNAPSHOT_SCOPE_REGION.

Terraform

כדי ליצור קובץ snapshot של דיסק אחסון מתמיד אזורי, משתמשים במשאב google_compute_snapshot.

resource "google_compute_snapshot" "snapdisk" {
  name        = "snapshot-name"
  source_disk = google_compute_disk.default.name
  zone        = "us-central1-a"
}

כדי ללמוד איך להחיל הגדרות ב-Terraform או להסיר אותן, ראו פקודות בסיסיות ב-Terraform.

המשך

Go

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Goהוראות ההגדרה שבמדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Go API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/protobuf/proto"
)

// createSnapshot creates a snapshot of a disk.
func createSnapshot(
	w io.Writer,
	projectID, diskName, snapshotName, zone, region, location, diskProjectID string,
) error {
	// projectID := "your_project_id"
	// diskName := "your_disk_name"
	// snapshotName := "your_snapshot_name"
	// zone := "europe-central2-b"
	// region := "eupore-central2"
	// location = "eupore-central2"
	// diskProjectID = "YOUR_DISK_PROJECT_ID"

	ctx := context.Background()

	snapshotsClient, err := compute.NewSnapshotsRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewSnapshotsRESTClient: %w", err)
	}
	defer snapshotsClient.Close()

	if zone == "" && region == "" {
		return fmt.Errorf("you need to specify `zone` or `region` for this function to work")
	}

	if zone != "" && region != "" {
		return fmt.Errorf("you can't set both `zone` and `region` parameters")
	}

	if diskProjectID == "" {
		diskProjectID = projectID
	}

	disk := &computepb.Disk{}
	locations := []string{}
	if location != "" {
		locations = append(locations, location)
	}

	if zone != "" {
		disksClient, err := compute.NewDisksRESTClient(ctx)
		if err != nil {
			return fmt.Errorf("NewDisksRESTClient: %w", err)
		}
		defer disksClient.Close()

		getDiskReq := &computepb.GetDiskRequest{
			Project: projectID,
			Zone:    zone,
			Disk:    diskName,
		}

		disk, err = disksClient.Get(ctx, getDiskReq)
		if err != nil {
			return fmt.Errorf("unable to get disk: %w", err)
		}
	} else {
		regionDisksClient, err := compute.NewRegionDisksRESTClient(ctx)
		if err != nil {
			return fmt.Errorf("NewRegionDisksRESTClient: %w", err)
		}
		defer regionDisksClient.Close()

		getDiskReq := &computepb.GetRegionDiskRequest{
			Project: projectID,
			Region:  region,
			Disk:    diskName,
		}

		disk, err = regionDisksClient.Get(ctx, getDiskReq)
		if err != nil {
			return fmt.Errorf("unable to get disk: %w", err)
		}
	}

	req := &computepb.InsertSnapshotRequest{
		Project: projectID,
		SnapshotResource: &computepb.Snapshot{
			Name:             proto.String(snapshotName),
			SourceDisk:       proto.String(disk.GetSelfLink()),
			StorageLocations: locations,
		},
	}

	op, err := snapshotsClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create snapshot: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Snapshot created\n")

	return nil
}

Java

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaהוראות ההגדרה שבמדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Java API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.RegionDisksClient;
import com.google.cloud.compute.v1.Snapshot;
import com.google.cloud.compute.v1.SnapshotsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateSnapshot {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // You need to pass `zone` or `region` parameter relevant to the disk you want to
    // snapshot, but not both. Pass `zone` parameter for zonal disks and `region` for
    // regional disks.

    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the disk you want to create.
    String diskName = "YOUR_DISK_NAME";

    // Name of the snapshot that you want to create.
    String snapshotName = "YOUR_SNAPSHOT_NAME";

    // The zone of the source disk from which you create the snapshot (for zonal disks).
    String zone = "europe-central2-b";

    // The region of the source disk from which you create the snapshot (for regional disks).
    String region = "your-disk-region";

    // The Cloud Storage multi-region or the Cloud Storage region where you
    // want to store your snapshot.
    // You can specify only one storage location. Available locations:
    // https://cloud.google.com/storage/docs/locations#available-locations
    String location = "europe-central2";

    // Project ID or project number of the Cloud project that
    // hosts the disk you want to snapshot. If not provided, the value will be defaulted
    // to 'projectId' value.
    String diskProjectId = "YOUR_DISK_PROJECT_ID";

    createSnapshot(projectId, diskName, snapshotName, zone, region, location, diskProjectId);
  }

  // Creates a snapshot of a disk.
  public static void createSnapshot(String projectId, String diskName, String snapshotName,
      String zone, String region, String location, String diskProjectId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    // 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 `snapshotsClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (SnapshotsClient snapshotsClient = SnapshotsClient.create()) {

      if (zone.isEmpty() && region.isEmpty()) {
        throw new Error("You need to specify 'zone' or 'region' for this function to work");
      }

      if (!zone.isEmpty() && !region.isEmpty()) {
        throw new Error("You can't set both 'zone' and 'region' parameters");
      }

      // If Disk's project id is not specified, then the projectId parameter will be used.
      if (diskProjectId.isEmpty()) {
        diskProjectId = projectId;
      }

      // If zone is not empty, use the DisksClient to create a disk.
      // Else, use the RegionDisksClient.
      Disk disk;
      if (!zone.isEmpty()) {
        DisksClient disksClient = DisksClient.create();
        disk = disksClient.get(projectId, zone, diskName);
      } else {
        RegionDisksClient regionDisksClient = RegionDisksClient.create();
        disk = regionDisksClient.get(diskProjectId, region, diskName);
      }

      // Set the snapshot properties.
      Snapshot snapshotResource;
      if (!location.isEmpty()) {
        snapshotResource = Snapshot.newBuilder()
            .setName(snapshotName)
            .setSourceDisk(disk.getSelfLink())
            .addStorageLocations(location)
            .build();
      } else {
        snapshotResource = Snapshot.newBuilder()
            .setName(snapshotName)
            .setSourceDisk(disk.getSelfLink())
            .build();
      }

      // Wait for the operation to complete.
      Operation operation = snapshotsClient.insertAsync(projectId, snapshotResource)
          .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Snapshot creation failed!" + operation);
        return;
      }

      // Retrieve the created snapshot.
      Snapshot snapshot = snapshotsClient.get(projectId, snapshotName);
      System.out.printf("Snapshot created: %s", snapshot.getName());

    }
  }
}

Node.js

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה שבמדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Node.js API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const diskName = 'YOUR_DISK_NAME';
// const snapshotName = 'YOUR_SNAPSHOT_NAME';
// const zone = 'europe-central2-b';
// const region = '';
// const location = 'europe-central2';
// let diskProjectId = 'YOUR_DISK_PROJECT_ID';

const compute = require('@google-cloud/compute');

async function createSnapshot() {
  const snapshotsClient = new compute.SnapshotsClient();

  let disk;

  if (!zone && !region) {
    throw new Error(
      'You need to specify `zone` or `region` for this function to work.'
    );
  }

  if (zone && region) {
    throw new Error("You can't set both `zone` and `region` parameters");
  }

  if (!diskProjectId) {
    diskProjectId = projectId;
  }

  if (zone) {
    const disksClient = new compute.DisksClient();
    [disk] = await disksClient.get({
      project: diskProjectId,
      zone,
      disk: diskName,
    });
  } else {
    const regionDisksClient = new compute.RegionDisksClient();
    [disk] = await regionDisksClient.get({
      project: diskProjectId,
      region,
      disk: diskName,
    });
  }

  const snapshotResource = {
    name: snapshotName,
    sourceDisk: disk.selfLink,
  };

  if (location) {
    snapshotResource.storageLocations = [location];
  }

  const [response] = await snapshotsClient.insert({
    project: projectId,
    snapshotResource,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.GlobalOperationsClient();

  // Wait for the create snapshot operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
    });
  }

  console.log('Snapshot created.');
}

createSnapshot();

Python

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonהוראות ההגדרה שבמדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Python API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def create_snapshot(
    project_id: str,
    disk_name: str,
    snapshot_name: str,
    *,
    zone: str | None = None,
    region: str | None = None,
    location: str | None = None,
    disk_project_id: str | None = None,
) -> compute_v1.Snapshot:
    """
    Create a snapshot of a disk.

    You need to pass `zone` or `region` parameter relevant to the disk you want to
    snapshot, but not both. Pass `zone` parameter for zonal disks and `region` for
    regional disks.

    Args:
        project_id: project ID or project number of the Cloud project you want
            to use to store the snapshot.
        disk_name: name of the disk you want to snapshot.
        snapshot_name: name of the snapshot to be created.
        zone: name of the zone in which is the disk you want to snapshot (for zonal disks).
        region: name of the region in which is the disk you want to snapshot (for regional disks).
        location: The Cloud Storage multi-region or the Cloud Storage region where you
            want to store your snapshot.
            You can specify only one storage location. Available locations:
            https://cloud.google.com/storage/docs/locations#available-locations
        disk_project_id: project ID or project number of the Cloud project that
            hosts the disk you want to snapshot. If not provided, will look for
            the disk in the `project_id` project.

    Returns:
        The new snapshot instance.
    """
    if zone is None and region is None:
        raise RuntimeError(
            "You need to specify `zone` or `region` for this function to work."
        )
    if zone is not None and region is not None:
        raise RuntimeError("You can't set both `zone` and `region` parameters.")

    if disk_project_id is None:
        disk_project_id = project_id

    if zone is not None:
        disk_client = compute_v1.DisksClient()
        disk = disk_client.get(project=disk_project_id, zone=zone, disk=disk_name)
    else:
        regio_disk_client = compute_v1.RegionDisksClient()
        disk = regio_disk_client.get(
            project=disk_project_id, region=region, disk=disk_name
        )

    snapshot = compute_v1.Snapshot()
    snapshot.source_disk = disk.self_link
    snapshot.name = snapshot_name
    if location:
        snapshot.storage_locations = [location]

    snapshot_client = compute_v1.SnapshotsClient()
    operation = snapshot_client.insert(project=project_id, snapshot_resource=snapshot)

    wait_for_extended_operation(operation, "snapshot creation")

    return snapshot_client.get(project=project_id, snapshot=snapshot_name)

REST

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

  • כדי ליצור snapshot במיקום ברירת המחדל המוגדר מראש או בהתאמה אישית בהגדרות ה-snapshot, שולחים בקשת POST אל ה-method‏ snapshots.insert:

    POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots
    {
        "name": "SNAPSHOT_NAME",
        "sourceDisk": "projects/SOURCE_PROJECT_ID/zones/SOURCE_ZONE/disks/SOURCE_DISK_NAME",
        "snapshotType": "SNAPSHOT_TYPE"
    }
    
  • לחלופין, כדי לשנות את הגדרות התמונה ולשמור אותה במיקום אחסון מותאם אישית, שולחים בקשת POST אל snapshots.insert וכוללים את המאפיין storageLocations בבקשה:

    POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots
    {
        "name": "SNAPSHOT_NAME",
        "sourceDisk": "projects/SOURCE_PROJECT_ID/zones/SOURCE_ZONE/disks/SOURCE_DISK_NAME",
        "snapshotType": "SNAPSHOT_TYPE",
        "storageLocations": [
            "STORAGE_LOCATION"
        ],
    }
    
  • (תצוגה מקדימה) כדי ליצור snapshot בהיקף אזורי באזור מותר, שולחים בקשת POST אל ה-method‏ snapshots.insert ומגדירים את אזור היצירה:

    POST https://compute.googleapis.com/compute/beta/projects/DESTINATION_PROJECT_ID/regions/SNAPSHOT_SCOPE_REGION/snapshots
    {
        "name": "SNAPSHOT_NAME",
        "sourceDisk": "projects/SOURCE_PROJECT_ID/zones/SOURCE_ZONE/disks/SOURCE_DISK_NAME",
        "snapshotType": "SNAPSHOT_TYPE"
    }
    

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

  • DESTINATION_PROJECT_ID: מזהה הפרויקט שבו רוצים ליצור את התמונה.
  • SNAPSHOT_NAME: שם לקובץ ה-snapshot.
  • SOURCE_PROJECT_ID: מזהה הפרויקט של דיסק המקור.
  • SOURCE_ZONE: האזור של דיסק המקור.
  • SOURCE_DISK_NAME: השם של נפח האחסון המתמיד (persistent disk) שממנו רוצים ליצור קובץ snapshot.
  • SNAPSHOT_TYPE: סוג ה-snapshot, ‏ STANDARD או ARCHIVE. אם לא מציינים סוג של snapshot, נוצר STANDARD snapshot.
  • STORAGE_LOCATION: אופציונלי: בשביל תמונות מצב בהיקף גלובלי, אזור Cloud Storage או אזור Cloud Storage שבו רוצים לאחסן את תמונת המצב. אפשר לציין רק מיקום אחסון אחד.

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

  • SNAPSHOT_SCOPE_REGION: אופציונלי: אם מדובר בקובץ snapshot בהיקף אזורי, מציינים את האזור שה-snapshot מוגבל אליו. אם כוללים את הפרמטר הזה, אי אפשר להשתמש בפרמטר storageLocations. הדומיין STORAGE_LOCATION מוגדר אוטומטית ל-SNAPSHOT_SCOPE_REGION.

יצירת קובץ snapshot של דיסק אזורי

אפשר ליצור קובצי snapshot של הדיסק האזורי באחת מהדרכים הבאות:

  • באמצעות הנתונים בדיסק המקור. כדי להשתמש בשיטה הזו ליצירת תמונת מצב, צריך שתהיה לכם רפליקה אזורית מסונכרנת.
  • באמצעות נקודת הבדיקה לשחזור העותק של דיסק פגום. אפשר ליצור תמונות מצב מנקודת ביקורת רק באמצעות Google Cloud CLI או REST.

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

המסוף

  1. נכנסים לדף Create a Snapshot במסוף Google Cloud .

    כניסה לדף Create a Snapshot
  2. מזינים שם לתמונת המצב.
  3. בוחרים סוג תמונת מצב. ברירת המחדל היא תמונת מצב של STANDARD, שהיא האפשרות הטובה ביותר לגיבוי לטווח ארוך ולתוכנית התאוששות מאסון (DR).

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

  4. אופציונלי: מזינים תיאור של התמונה.
  5. בקטע דיסק מקור, בוחרים את הדיסק הקיים שרוצים ליצור ממנו תמונת מצב.
  6. בקטע מיקום, בוחרים את מיקום האחסון של התמונה.

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

    1. בוחרים את סוג מיקום האחסון שרוצים לשמור בו את התמונה.

      • בוחרים באפשרות Multi-regional (אזורים מרובים) כדי ליהנות מזמינות גבוהה יותר בעלות גבוהה יותר.
      • כדי לקבל יותר שליטה על המיקום הפיזי של הנתונים בעלות נמוכה יותר, בוחרים באפשרות תמונות מצב אזוריות.
    2. בשדה Select location (בחירת מיקום), בוחרים את האזור הספציפי או את מספר האזורים שרוצים להשתמש בהם. כדי להשתמש באזור או במספר אזורים שהכי קרובים לדיסק המקור, בוחרים באפשרות Based on disk's location (על סמך המיקום של הדיסק).
  7. לוחצים על Create (יצירה) כדי ליצור את התמונה.

gcloud

אפשר ליצור תמונת מצב באמצעות הנתונים של דיסק המקור או באמצעות נקודת שחזור של העתק שלו.

מנתוני דיסק

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

  • כדי ליצור snapshot במיקום ברירת המחדל המוגדר מראש או בהתאמה אישית בהגדרות ה-snapshot, משתמשים בפקודה gcloud compute snapshots create.

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk-region=SOURCE_REGION \
        --source-disk=SOURCE_DISK_NAME \
        --snapshot-type=SNAPSHOT_TYPE
    
  • לחלופין, כדי לבטל את הגדרות הצילום וליצור צילום במיקום אחסון מותאם אישית, צריך לכלול את הדגל --storage-location כדי לציין איפה לאחסן את הצילום.

    gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk-region=SOURCE_REGION \
        --source-disk=SOURCE_DISK_NAME \
        --snapshot-type=SNAPSHOT_TYPE \
        --storage-location=STORAGE_LOCATION
    
  • (תצוגה מקדימה) כדי ליצור תמונת מצב בהיקף אזורי באזור מותר, צריך לכלול את הדגל --region כדי לציין איפה ליצור את תמונת המצב.

    gcloud beta compute snapshots create SNAPSHOT_NAME \
        --region=SNAPSHOT_SCOPE_REGION \
        --source-disk=SOURCE_DISK_NAME \
        --source-disk-region=SOURCE_REGION \
        --snapshot-type=SNAPSHOT_TYPE
    

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

  • SNAPSHOT_NAME: שם לקובץ ה-snapshot.
  • SOURCE_REGION: האזור של דיסק המקור.
  • SOURCE_DISK_NAME: השם של הדיסק האזורי המתמיד או של נפח האחסון Hyperdisk Balanced High Availability שממנו רוצים ליצור קובץ snapshot.
  • SNAPSHOT_TYPE: סוג ה-snapshot, ‏ STANDARD או ARCHIVE. אם לא מציינים סוג של snapshot, נוצר STANDARD snapshot.
  • STORAGE_LOCATION: אופציונלי: בשביל תמונות מצב בהיקף גלובלי, אזור Cloud Storage או אזור Cloud Storage שבו רוצים לאחסן את תמונת המצב. אפשר לציין רק מיקום אחסון אחד.

    משתמשים בפרמטר --storage-location רק כשרוצים לשנות את מיקום האחסון שמוגדר כברירת מחדל בהגדרות של התמונה, בין אם הוא מוגדר מראש או בהתאמה אישית.

  • SNAPSHOT_SCOPE_REGION: אופציונלי: אם מדובר בקובץ snapshot בהיקף אזורי, מציינים את האזור שה-snapshot מוגבל אליו. אם כוללים את הפרמטר הזה, אי אפשר להשתמש בפרמטר --storage-location. הדומיין STORAGE_LOCATION מוגדר אוטומטית ל-SNAPSHOT_SCOPE_REGION.

מנקודת הביקורת

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

כדי ליצור snapshot באמצעות נקודת הבדיקה לשחזור הרפליקה, משתמשים בפקודה gcloud compute snapshots create . כדי לציין שאתם רוצים ליצור את ה-snapshot באמצעות נקודת ביקורת לשחזור רפליקה, צריך לכלול את הדגל --source-disk-for-recovery-checkpoint. מחריגים את הפרמטרים --source-disk ו---source-disk-region.

gcloud compute snapshots create SNAPSHOT_NAME \
    --source-disk-for-recovery-checkpoint=SOURCE_DISK \
    --source-disk-for-recovery-checkpoint-region=SOURCE_REGION \
    --storage-location=STORAGE_LOCATION \
    --snapshot-type=SNAPSHOT_TYPE

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

  • DESTINATION_PROJECT_ID: מזהה הפרויקט שבו רוצים ליצור את התמונה.
  • SNAPSHOT_NAME: שם לקובץ ה-snapshot.
  • SOURCE_PROJECT_ID: מזהה הפרויקט של דיסק המקור שרוצים להשתמש בנקודת הבדיקה שלו כדי ליצור את ה-Snapshot.
  • SOURCE_REGION: האזור של דיסק המקור שרוצים להשתמש בנקודת הבדיקה שלו כדי ליצור את ה-snapshot.
  • SOURCE_DISK_NAME: השם של דיסק המקור שאתם רוצים להשתמש בנקודת הבדיקה שלו כדי ליצור את ה-snapshot.
  • STORAGE_LOCATION: אופציונלי: אזור Cloud Storage מרובה אזורים או אזור Cloud Storage שבו רוצים לאחסן את ה-snapshot. אפשר לציין רק מיקום אחסון אחד.
    משתמשים בפרמטר רק אם רוצים לשנות את מיקום האחסון שמוגדר כברירת מחדל או בהתאמה אישית בהגדרות של התמונה.
  • SNAPSHOT_TYPE: סוג ה-snapshot, ‏ STANDARD או ARCHIVE. אם לא מציינים סוג תמונת מצב, נוצרת תמונת מצב STANDARD.

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

The device is fully replicated and should not create snapshots out of a recovery checkpoint. Please
create regular snapshots instead.

‫Google Cloud CLI מחכה עד שהפעולה מחזירה סטטוס של READY או FAILED, או עד שהיא מגיעה לזמן הקצוב לתפוגה המקסימלי, ומחזירה את הפרטים האחרונים הידועים של התמונה.

Terraform

ספק Terraform ל- Google Cloud לא תומך ביצירת תמונת מצב של דיסק אזורי. כדי לעקוב אחרי ההגבלה הזו, אפשר לעיין בבעיה ב-GitHub.

המשך

Go

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Goהוראות ההגדרה שבמדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Go API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "cloud.google.com/go/compute/apiv1/computepb"
	"google.golang.org/protobuf/proto"
)

// createSnapshot creates a snapshot of a disk.
func createSnapshot(
	w io.Writer,
	projectID, diskName, snapshotName, zone, region, location, diskProjectID string,
) error {
	// projectID := "your_project_id"
	// diskName := "your_disk_name"
	// snapshotName := "your_snapshot_name"
	// zone := "europe-central2-b"
	// region := "eupore-central2"
	// location = "eupore-central2"
	// diskProjectID = "YOUR_DISK_PROJECT_ID"

	ctx := context.Background()

	snapshotsClient, err := compute.NewSnapshotsRESTClient(ctx)
	if err != nil {
		return fmt.Errorf("NewSnapshotsRESTClient: %w", err)
	}
	defer snapshotsClient.Close()

	if zone == "" && region == "" {
		return fmt.Errorf("you need to specify `zone` or `region` for this function to work")
	}

	if zone != "" && region != "" {
		return fmt.Errorf("you can't set both `zone` and `region` parameters")
	}

	if diskProjectID == "" {
		diskProjectID = projectID
	}

	disk := &computepb.Disk{}
	locations := []string{}
	if location != "" {
		locations = append(locations, location)
	}

	if zone != "" {
		disksClient, err := compute.NewDisksRESTClient(ctx)
		if err != nil {
			return fmt.Errorf("NewDisksRESTClient: %w", err)
		}
		defer disksClient.Close()

		getDiskReq := &computepb.GetDiskRequest{
			Project: projectID,
			Zone:    zone,
			Disk:    diskName,
		}

		disk, err = disksClient.Get(ctx, getDiskReq)
		if err != nil {
			return fmt.Errorf("unable to get disk: %w", err)
		}
	} else {
		regionDisksClient, err := compute.NewRegionDisksRESTClient(ctx)
		if err != nil {
			return fmt.Errorf("NewRegionDisksRESTClient: %w", err)
		}
		defer regionDisksClient.Close()

		getDiskReq := &computepb.GetRegionDiskRequest{
			Project: projectID,
			Region:  region,
			Disk:    diskName,
		}

		disk, err = regionDisksClient.Get(ctx, getDiskReq)
		if err != nil {
			return fmt.Errorf("unable to get disk: %w", err)
		}
	}

	req := &computepb.InsertSnapshotRequest{
		Project: projectID,
		SnapshotResource: &computepb.Snapshot{
			Name:             proto.String(snapshotName),
			SourceDisk:       proto.String(disk.GetSelfLink()),
			StorageLocations: locations,
		},
	}

	op, err := snapshotsClient.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to create snapshot: %w", err)
	}

	if err = op.Wait(ctx); err != nil {
		return fmt.Errorf("unable to wait for the operation: %w", err)
	}

	fmt.Fprintf(w, "Snapshot created\n")

	return nil
}

Java

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Javaהוראות ההגדרה שבמדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Java API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.RegionDisksClient;
import com.google.cloud.compute.v1.Snapshot;
import com.google.cloud.compute.v1.SnapshotsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateSnapshot {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // You need to pass `zone` or `region` parameter relevant to the disk you want to
    // snapshot, but not both. Pass `zone` parameter for zonal disks and `region` for
    // regional disks.

    // Project ID or project number of the Cloud project you want to use.
    String projectId = "YOUR_PROJECT_ID";

    // Name of the disk you want to create.
    String diskName = "YOUR_DISK_NAME";

    // Name of the snapshot that you want to create.
    String snapshotName = "YOUR_SNAPSHOT_NAME";

    // The zone of the source disk from which you create the snapshot (for zonal disks).
    String zone = "europe-central2-b";

    // The region of the source disk from which you create the snapshot (for regional disks).
    String region = "your-disk-region";

    // The Cloud Storage multi-region or the Cloud Storage region where you
    // want to store your snapshot.
    // You can specify only one storage location. Available locations:
    // https://cloud.google.com/storage/docs/locations#available-locations
    String location = "europe-central2";

    // Project ID or project number of the Cloud project that
    // hosts the disk you want to snapshot. If not provided, the value will be defaulted
    // to 'projectId' value.
    String diskProjectId = "YOUR_DISK_PROJECT_ID";

    createSnapshot(projectId, diskName, snapshotName, zone, region, location, diskProjectId);
  }

  // Creates a snapshot of a disk.
  public static void createSnapshot(String projectId, String diskName, String snapshotName,
      String zone, String region, String location, String diskProjectId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    // 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 `snapshotsClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (SnapshotsClient snapshotsClient = SnapshotsClient.create()) {

      if (zone.isEmpty() && region.isEmpty()) {
        throw new Error("You need to specify 'zone' or 'region' for this function to work");
      }

      if (!zone.isEmpty() && !region.isEmpty()) {
        throw new Error("You can't set both 'zone' and 'region' parameters");
      }

      // If Disk's project id is not specified, then the projectId parameter will be used.
      if (diskProjectId.isEmpty()) {
        diskProjectId = projectId;
      }

      // If zone is not empty, use the DisksClient to create a disk.
      // Else, use the RegionDisksClient.
      Disk disk;
      if (!zone.isEmpty()) {
        DisksClient disksClient = DisksClient.create();
        disk = disksClient.get(projectId, zone, diskName);
      } else {
        RegionDisksClient regionDisksClient = RegionDisksClient.create();
        disk = regionDisksClient.get(diskProjectId, region, diskName);
      }

      // Set the snapshot properties.
      Snapshot snapshotResource;
      if (!location.isEmpty()) {
        snapshotResource = Snapshot.newBuilder()
            .setName(snapshotName)
            .setSourceDisk(disk.getSelfLink())
            .addStorageLocations(location)
            .build();
      } else {
        snapshotResource = Snapshot.newBuilder()
            .setName(snapshotName)
            .setSourceDisk(disk.getSelfLink())
            .build();
      }

      // Wait for the operation to complete.
      Operation operation = snapshotsClient.insertAsync(projectId, snapshotResource)
          .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Snapshot creation failed!" + operation);
        return;
      }

      // Retrieve the created snapshot.
      Snapshot snapshot = snapshotsClient.get(projectId, snapshotName);
      System.out.printf("Snapshot created: %s", snapshot.getName());

    }
  }
}

Node.js

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה שבמדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Node.js API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const diskName = 'YOUR_DISK_NAME';
// const snapshotName = 'YOUR_SNAPSHOT_NAME';
// const zone = 'europe-central2-b';
// const region = '';
// const location = 'europe-central2';
// let diskProjectId = 'YOUR_DISK_PROJECT_ID';

const compute = require('@google-cloud/compute');

async function createSnapshot() {
  const snapshotsClient = new compute.SnapshotsClient();

  let disk;

  if (!zone && !region) {
    throw new Error(
      'You need to specify `zone` or `region` for this function to work.'
    );
  }

  if (zone && region) {
    throw new Error("You can't set both `zone` and `region` parameters");
  }

  if (!diskProjectId) {
    diskProjectId = projectId;
  }

  if (zone) {
    const disksClient = new compute.DisksClient();
    [disk] = await disksClient.get({
      project: diskProjectId,
      zone,
      disk: diskName,
    });
  } else {
    const regionDisksClient = new compute.RegionDisksClient();
    [disk] = await regionDisksClient.get({
      project: diskProjectId,
      region,
      disk: diskName,
    });
  }

  const snapshotResource = {
    name: snapshotName,
    sourceDisk: disk.selfLink,
  };

  if (location) {
    snapshotResource.storageLocations = [location];
  }

  const [response] = await snapshotsClient.insert({
    project: projectId,
    snapshotResource,
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.GlobalOperationsClient();

  // Wait for the create snapshot operation to complete.
  while (operation.status !== 'DONE') {
    [operation] = await operationsClient.wait({
      operation: operation.name,
      project: projectId,
    });
  }

  console.log('Snapshot created.');
}

createSnapshot();

Python

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonהוראות ההגדרה שבמדריך למתחילים של Compute Engine באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Compute Engine Python API.

כדי לבצע אימות ב-Compute Engine, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def create_snapshot(
    project_id: str,
    disk_name: str,
    snapshot_name: str,
    *,
    zone: str | None = None,
    region: str | None = None,
    location: str | None = None,
    disk_project_id: str | None = None,
) -> compute_v1.Snapshot:
    """
    Create a snapshot of a disk.

    You need to pass `zone` or `region` parameter relevant to the disk you want to
    snapshot, but not both. Pass `zone` parameter for zonal disks and `region` for
    regional disks.

    Args:
        project_id: project ID or project number of the Cloud project you want
            to use to store the snapshot.
        disk_name: name of the disk you want to snapshot.
        snapshot_name: name of the snapshot to be created.
        zone: name of the zone in which is the disk you want to snapshot (for zonal disks).
        region: name of the region in which is the disk you want to snapshot (for regional disks).
        location: The Cloud Storage multi-region or the Cloud Storage region where you
            want to store your snapshot.
            You can specify only one storage location. Available locations:
            https://cloud.google.com/storage/docs/locations#available-locations
        disk_project_id: project ID or project number of the Cloud project that
            hosts the disk you want to snapshot. If not provided, will look for
            the disk in the `project_id` project.

    Returns:
        The new snapshot instance.
    """
    if zone is None and region is None:
        raise RuntimeError(
            "You need to specify `zone` or `region` for this function to work."
        )
    if zone is not None and region is not None:
        raise RuntimeError("You can't set both `zone` and `region` parameters.")

    if disk_project_id is None:
        disk_project_id = project_id

    if zone is not None:
        disk_client = compute_v1.DisksClient()
        disk = disk_client.get(project=disk_project_id, zone=zone, disk=disk_name)
    else:
        regio_disk_client = compute_v1.RegionDisksClient()
        disk = regio_disk_client.get(
            project=disk_project_id, region=region, disk=disk_name
        )

    snapshot = compute_v1.Snapshot()
    snapshot.source_disk = disk.self_link
    snapshot.name = snapshot_name
    if location:
        snapshot.storage_locations = [location]

    snapshot_client = compute_v1.SnapshotsClient()
    operation = snapshot_client.insert(project=project_id, snapshot_resource=snapshot)

    wait_for_extended_operation(operation, "snapshot creation")

    return snapshot_client.get(project=project_id, snapshot=snapshot_name)

REST

אפשר ליצור תמונת מצב באמצעות הנתונים של דיסק המקור או באמצעות נקודת שחזור של העתק שלו.

מנתוני דיסק

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

  • כדי ליצור snapshot במיקום ברירת המחדל המוגדר מראש או בהתאמה אישית בהגדרות ה-snapshot, שולחים בקשת POST אל ה-method‏ snapshots.insert:

    POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots
    {
      "name": "SNAPSHOT_NAME",
      "sourceDisk": "projects/SOURCE_PROJECT_ID/regions/SOURCE_REGION/disks/SOURCE_DISK_NAME",
      "snapshotType": "SNAPSHOT_TYPE"
    }
    
  • לחלופין, כדי לשנות את הגדרות התמונה ולשמור אותה במיקום אחסון מותאם אישית, שולחים בקשת POST אל snapshots.insert וכוללים את המאפיין storageLocations בבקשה:

    POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots
    {
      "name": "SNAPSHOT_NAME",
      "sourceDisk": "projects/SOURCE_PROJECT_ID/regions/SOURCE_REGION/disks/SOURCE_DISK_NAME",
      "snapshotType": "SNAPSHOT_TYPE",
      "storageLocations": [
          "STORAGE_LOCATION"
      ],
    }
    
  • (תצוגה מקדימה) כדי ליצור snapshot בהיקף אזורי באזור מותר, שולחים בקשת POST אל ה-method‏ snapshots.insert ומגדירים את אזור היצירה:

    POST https://compute.googleapis.com/compute/beta/projects/DESTINATION_PROJECT_ID/regions/SNAPSHOT_SCOPE_REGION/snapshots
    {
      "name": "SNAPSHOT_NAME",
      "sourceDisk": "projects/SOURCE_PROJECT_ID/regions/SOURCE_REGION/disks/SOURCE_DISK_NAME",
      "snapshotType": "SNAPSHOT_TYPE",
    }
    

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

  • DESTINATION_PROJECT_ID: מזהה הפרויקט שבו רוצים ליצור את התמונה.
  • SNAPSHOT_NAME: שם לקובץ ה-snapshot.
  • SOURCE_PROJECT_ID: מזהה הפרויקט של דיסק המקור.
  • SOURCE_REGION: האזור של דיסק המקור.
  • SOURCE_DISK_NAME: השם של הדיסק האזורי המתמיד או של נפח האחסון Hyperdisk Balanced High Availability שממנו רוצים ליצור קובץ snapshot.
  • SNAPSHOT_TYPE: סוג ה-snapshot, ‏ STANDARD או ARCHIVE. אם לא מציינים סוג של snapshot, נוצר STANDARD snapshot.
  • STORAGE_LOCATION: אופציונלי: בשביל תמונות מצב בהיקף גלובלי, אזור Cloud Storage או אזור Cloud Storage שבו רוצים לאחסן את תמונת המצב. אפשר לציין רק מיקום אחסון אחד.

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

  • SNAPSHOT_SCOPE_REGION: אופציונלי: אם מדובר בקובץ snapshot בהיקף אזורי, מציינים את האזור שה-snapshot מוגבל אליו. אם כוללים את הפרמטר הזה, אי אפשר להשתמש בפרמטר storageLocations. הדומיין STORAGE_LOCATION מוגדר אוטומטית ל-SNAPSHOT_SCOPE_REGION.

מנקודת הביקורת

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

כדי ליצור snapshot באמצעות נקודת הבדיקה לשחזור הרפליקה, שולחים בקשת POST אל ה-method‏ snapshots.insert. צריך להחריג את הפרמטר sourceDisk ולכלול במקומו את הפרמטר sourceDiskForRecoveryCheckpoint כדי לציין שרוצים ליצור את התמונה באמצעות נקודת הבדיקה.

POST https://compute.googleapis.com/compute/v1/projects/DESTINATION_PROJECT_ID/global/snapshots

{
  "name": "SNAPSHOT_NAME",
  "sourceDiskForRecoveryCheckpoint": "projects/SOURCE_PROJECT_ID/regions/SOURCE_REGION/disks/SOURCE_DISK_NAME",
  "storageLocations": "STORAGE_LOCATION",
  "snapshotType": "SNAPSHOT_TYPE"
}

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

  • DESTINATION_PROJECT_ID: מזהה הפרויקט שבו רוצים ליצור את התמונה.
  • SNAPSHOT_NAME: שם לקובץ ה-snapshot.
  • SOURCE_PROJECT_ID: מזהה הפרויקט של דיסק המקור שרוצים להשתמש בנקודת הבדיקה שלו כדי ליצור את ה-Snapshot.
  • SOURCE_REGION: האזור של דיסק המקור שרוצים להשתמש בנקודת הבדיקה שלו כדי ליצור את ה-snapshot.
  • SOURCE_DISK_NAME: השם של דיסק המקור שאתם רוצים להשתמש בנקודת הבדיקה שלו כדי ליצור את ה-snapshot.
  • STORAGE_LOCATION: אופציונלי: אזור Cloud Storage מרובה אזורים או אזור Cloud Storage שבו רוצים לאחסן את ה-snapshot. אפשר לציין רק מיקום אחסון אחד.
    משתמשים בפרמטר storageLocations רק אם רוצים לשנות את מיקום האחסון שמוגדר כברירת מחדל או בהתאמה אישית בהגדרות של התמונה.
  • SNAPSHOT_TYPE: סוג ה-snapshot, ‏ STANDARD או ARCHIVE. אם לא מציינים סוג תמונת מצב, נוצרת תמונת מצב STANDARD.

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

The device is fully replicated and should not create snapshots out of a recovery checkpoint. Please
create regular snapshots instead.

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