使用快照備份資料

本頁說明如何建立快照,備份儲存在 Vertex AI Workbench 使用者管理型筆記本執行個體中的資料。

執行個體中的資料會儲存在區域永久磁碟中。您可以建立及使用這個磁碟的快照來備份資料、建立定期備份排程,以及將資料還原至新的執行個體。

建立快照

您甚至可以為已連結到執行中執行個體的磁碟建立快照。快照是全球資源,因此可用於將資料還原至同一專案中的新磁碟或執行個體。您也可以跨專案共用快照

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往「VM instances」(VM 執行個體) 頁面
    其餘步驟會自動顯示在 Google Cloud 控制台。

  2. 選取含有 VM 執行個體的專案。
  3. 在「Name」(名稱) 欄中,按一下要備份磁碟的 VM 名稱。
  4. 「Storage」(儲存空間) 中執行下列操作:
    • 如要備份開機磁碟,請按一下「Boot disk」(開機磁碟) 區段中的開機磁碟「Name」(名稱)
    • 如要備份已連接的資料磁碟,請在「Additional disks」(其他磁碟) 中點選磁碟「Name」(名稱)
  5. 按一下「Create snapshot」(建立快照)
  6. 在「Name」(名稱) 中輸入不重複的名稱,以利區分快照用途,例如:
    • boot-disk-snapshot
    • attached-data-disk-snapshot
  7. 在「Type」(類型) 中,預設為標準快照。標準快照最適合用於長期備份和災難復原。

    選擇「Archive snapshot」(封存快照),即可建立比標準快照更具成本效益的備份,但資料復原時間會較長。

    詳情請參閱「快照類型比較」。

  8. 在「Location」(位置) 部分,選擇快照儲存位置。系統會自動選取快照設定中指定的預先定義或自訂預設位置。如要覆寫快照設定,將快照儲存在自訂儲存位置,請執行下列步驟:

    1. 選擇快照的儲存位置類型。

    2. 在「Select location」(選取位置) 欄位,選擇要使用的特定區域或多區域。如要使用最接近來源磁碟的區域或多區域,請從「Based on disk's location」(以磁碟位置為準) 專區選擇位置。

  9. 如要建立快照,請按一下「Create」(建立)

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 使用快照設定定義的儲存位置政策建立快照,或使用您選擇的替代儲存位置。詳情請參閱選擇快照儲存位置。 您必須指定快照名稱。名稱長度必須介於 1 至 63 個字元之間,且符合 RFC 1035

    • 如要在快照設定中指定的預先定義或自訂預設位置,建立永久磁碟磁碟區的快照,請使用 gcloud compute snapshots create 指令

      gcloud compute snapshots create SNAPSHOT_NAME \
          --source-disk SOURCE_DISK \
          --snapshot-type SNAPSHOT_TYPE \
          --source-disk-zone SOURCE_DISK_ZONE
      

    • 或者,如要覆寫快照設定,在自訂儲存位置建立快照,請加入 --storage-location 旗標來指示快照的儲存位置:

      gcloud compute snapshots create SNAPSHOT_NAME \
        --source-disk SOURCE_DISK \
        --source-disk-zone SOURCE_DISK_ZONE \
        --storage-location STORAGE_LOCATION \
        --snapshot-type SNAPSHOT_TYPE

      更改下列內容:

      • SNAPSHOT_NAME:快照的名稱。
      • SOURCE_DISK:要用來建立快照的區域永久磁碟磁碟區名稱。
      • SNAPSHOT_TYPE:快照類型,可以是 STANDARDARCHIVE。如果未指定快照類型,系統會建立 STANDARD 快照。選擇「封存」可更有效率地保留資料。
      • SOURCE_DISK_ZONE:您要用來建立快照的區域永久磁碟磁碟區所在區域。

      只有在想覆寫快照設定中預先定義或自訂的預設儲存位置時,才使用 --storage-location 標記。

    gcloud CLI 會等到作業傳回 READYFAILED 狀態之後,或是等到作業達到逾時時間上限,並傳回已知的最新快照詳細資料之後,才會開始運作。

Terraform

如要建立區域永久磁碟的快照,請使用 google_compute_snapshot 資源。

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

如要瞭解如何套用或移除 Terraform 設定,請參閱「基本 Terraform 指令」。

API

快照設定定義的儲存位置政策中建立快照,或使用您選擇的替代儲存位置。詳情請參閱選擇快照儲存位置

  • 如要在快照設定中指定的預先定義或自訂預設位置建立快照,請對 snapshots.insert 方法發出 POST 要求:

    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
    }
    

    更改下列內容:

    • DESTINATION_PROJECT_ID:要在其中建立快照的專案 ID。
    • SNAPSHOT_NAME:快照的名稱。
    • SOURCE_PROJECT_ID:來源磁碟專案的 ID。
    • SOURCE_ZONE:來源磁碟的可用區。
    • SOURCE_DISK_NAME:要用來建立快照的永久磁碟名稱。
    • SNAPSHOT_TYPE:快照類型,可以是 STANDARDARCHIVE。如果未指定快照類型,系統會建立 STANDARD 快照。
  • 或者,如要覆寫快照設定,在自訂儲存位置建立快照,請對 snapshots.insert 方法發出 POST 要求,並在要求中納入 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
    }
    

    更改下列內容:

    • DESTINATION_PROJECT_ID:要在其中建立快照的專案 ID。
    • SNAPSHOT_NAME:快照的名稱。
    • SOURCE_PROJECT_ID:來源磁碟專案的 ID。
    • SOURCE_ZONE:來源磁碟的可用區。
    • SOURCE_DISK_NAME:要用來建立快照的永久磁碟名稱。
    • SNAPSHOT_TYPE:快照類型,可以是 STANDARDARCHIVE。如果未指定快照類型,系統會建立 STANDARD 快照。
    • STORAGE_LOCATION:您要儲存快照的 Cloud Storage 多地區Cloud Storage 地區。您只能指定一個儲存位置。

      只有在想覆寫快照設定中預先定義或自訂的預設儲存位置時,才使用 storageLocations 參數。

Go

Go

在試用這個範例之前,請先按照這篇 Compute Engine 快速入門指南的操作說明,使用用戶端程式庫進行設定。

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證」。

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

在試用這個範例之前,請先按照這篇 Compute Engine 快速入門指南的操作說明,使用用戶端程式庫進行設定。

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證」。


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

在試用這個範例之前,請先按照這篇 Compute Engine 快速入門指南的操作說明,使用用戶端程式庫進行設定。

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證」。

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

在試用這個範例之前,請先按照這篇 Compute Engine 快速入門指南的操作說明,使用用戶端程式庫進行設定。

如要向 Compute Engine 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證」。

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)

排定週期性備份

建立快照排程時,您會建立資源政策,並套用至一或多個永久磁碟。您可以透過下列方式建立快照排程:

快照排程包含以下屬性:

  • 排程名稱
  • 排程說明
  • 快照頻率 (每小時、每日、每週)
  • 快照開始時間
  • 可以使用快照排程的地區
  • 來源磁碟刪除政策,在來源磁碟遭到刪除時用來處理自動產生的快照
  • 保留政策:定義快照排程所產生的快照應保留多久

限制

  • 每個永久磁碟一次最多只能附加 10 個快照排程。
  • 您無法使用快照排程建立封存快照。
  • 每個區域最多可建立 1,000 個使用中的快照排程。
  • 快照時間表只會套用至建立時使用的專案。快照排程無法用於其他專案或機構。
  • 如果在您的地區中,您需要更多資源,可能需要透過主控台申請增加資源配額
  • 如果快照排程已附加至磁碟,就無法加以刪除。您必須先從所有磁碟卸離排程,才能刪除該排程。
  • 您可以更新現有的快照排程,變更說明、排程和標籤。如要更新快照排程的其他值,則必須先刪除快照排程,接著再建立新的快照排程。
  • 如果永久磁碟使用客戶提供的加密金鑰 (CSEK),您就無法建立快照排程。
  • 如果永久磁碟使用客戶自行管理的加密金鑰 (CMEK),透過快照排程建立的所有快照都會自動以相同金鑰加密。

建立排程

使用 Google Cloud 控制台、Google Cloud CLI 或 Compute Engine API,為永久磁碟建立快照排程。您必須在與永久磁碟相同的地區中建立快照排程。舉例來說,如果永久磁碟位於 us-west1-a 區域,快照排程也必須位於 us-west1 地區。詳情請參閱「選擇儲存位置」。

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往「VM instances」(VM 執行個體)
    其餘步驟會自動顯示在 Google Cloud 控制台。

  2. 選取含有 VM 執行個體的專案。
  3. 在「Name」(名稱) 欄中,按一下要建立快照排程的永久磁碟所在的 VM 名稱。
  4. 「Storage」(儲存空間),按一下要建立快照排程的「Boot disk」(開機磁碟) 或「Additional disk」(其他磁碟) 名稱。
  5. 按一下「編輯」。你可能需要按一下 「更多動作」選單,然後點選「編輯」
  6. 在「Snapshot schedule」(快照排程) 中選擇「Create a schedule」(建立排程)
  7. 在「Name」(名稱) 中,為快照排程輸入下列其中一個名稱:
    • boot-disk-snapshot-schedule
    • attached-persistent-disk-snapshot-schedule
  8. 在「Location」(位置) 部分,選擇快照儲存位置。系統會自動選取快照設定中指定的預先定義或自訂預設位置。如要覆寫快照設定,將快照儲存在自訂儲存位置,請執行下列步驟:

    1. 選擇快照的儲存位置類型。

    2. 在「Select location」(選取位置) 欄位,選擇要使用的特定區域或多區域。如要使用離來源磁碟最近的區域或多區域,請選取「Based on disk's location」(以磁碟位置為準)

  9. 按一下「Create」(建立) 即可完成快照排程建立作業。
  10. 如要將這個快照排程附加至永久磁碟,請按一下「Save」(儲存)

gcloud

如要為永久磁碟建立快照排程,請使用 compute resource-policies create snapshot-schedule gcloud 指令,並將排程頻率設定為每小時、每日或每週。

  gcloud compute resource-policies create snapshot-schedule [SCHEDULE_NAME] \
      --description "[SCHEDULE_DESCRIPTION]" \
      --max-retention-days [MAX_RETENTION_DAYS] \
      --start-time [START_TIME] \
      --hourly-schedule [SNAPSHOT_INTERVAL] \
      --daily-schedule \
      --weekly-schedule [SNAPSHOT_INTERVAL] \
      --weekly-schedule-from-file [FILE_NAME] \
      --on-source-disk-delete [DELETION_OPTION]

其中:

  • [SCHEDULE_NAME] 是新快照排程的名稱。
  • "[SCHEDULE_DESCRIPTION]" 是快照排程的說明。請在說明內容的前後加上引號。
  • [MAX_RETENTION_DAYS] 是快照的保留天數。假如設定為 3,則代表快照會在保留 3 天後刪除。保留政策至少須設為 1 天。
  • [START_TIME] 是世界標準時間的開始時間。時間必須從每個小時的整點開始, 例如:
    • 太平洋標準時間下午 2:00 是 22:00
    • 假如您將開始時間設為 22:13,則會收到錯誤訊息。
  • [SNAPSHOT_INTERVAL] 定義建立快照的時間間隔。請使用介於 1 到 23 的整數設定每小時排程,並選擇一個能夠將 24 整除的數字。例如,將 --hourly-schedule 設為 12,即代表系統每 12 個小時會產生一次快照。如為每週排程,請定義當週要執行快照的日子。您必須填入星期幾,但不必區分大小寫。快照頻率旗標 hourly-scheduledaily-scheduleweekly-schedule 是相互排斥的,您只能為快照排程選取其中一項設定。

  • [FILE_NAME] 是包含每週快照排程的檔案名稱 (如果您選擇透過此格式提供排程)。請注意,您可以透過檔案來指定每週排程在不同的日子和時間執行 (但是您無法直接在指令列上指定多個每週排程)。舉例來說,您的檔案可能會指定在星期一和星期三建立快照的排程:[{"day": "MONDAY", "startTime": "04:00"}, {"day": "WEDNESDAY", "startTime": "02:00"}]。如果檔案中包含開始時間,則不需要設定 --start-time 旗標。排程採用世界標準時間標準。

  • [DELETION_OPTION] 決定在來源磁碟遭到刪除時,系統會如何處理快照。您可以省略這個旗標以選擇預設的 keep-auto-snapshots,或是使用 apply-retention-policy 來套用保留政策。

以下列出更多快照排程的設定範例,在所有範例中:

  • 磁碟刪除規則皆包含在內。--on-source-disk-delete 旗標的預設值設為 keep-auto-snapshots,會永久保留所有自動產生的快照。另一種做法則是將這個旗標設為 apply-retention-policy,即可使用您的快照保留政策。
  • 儲存位置設為 US,因此所有產生的快照都會儲存在美國多地區位置。
  • 標籤 env=devmedia=images 會套用至所有產生的快照。
  • 保留政策的設定為 10 天。

每小時排程:在本範例中,快照排程會在世界標準時間 22:00 開始作業,而且每 4 個小時執行一次。

  gcloud compute resource-policies create snapshot-schedule SCHEDULE_NAME \
      --description "MY HOURLY SNAPSHOT SCHEDULE" \
      --max-retention-days 10 \
      --start-time 22:00 \
      --hourly-schedule 4 \
      --region us-west1 \
      --on-source-disk-delete keep-auto-snapshots \
      --snapshot-labels env=dev,media=images \
      --storage-location US

每日排程:在本範例中,快照排程會在世界標準時間 22:00 開始作業,而且會在每天的同一時間執行。--daily-schedule 旗標必須存在,但不設定任何內容。

gcloud compute resource-policies create snapshot-schedule SCHEDULE_NAME \
    --description "MY DAILY SNAPSHOT SCHEDULE" \
    --max-retention-days 10 \
    --start-time 22:00 \
    --daily-schedule \
    --region us-west1 \
    --on-source-disk-delete keep-auto-snapshots \
    --snapshot-labels env=dev,media=images \
    --storage-location US

每週排程:在本範例中,快照排程會在世界標準時間 22:00 開始作業,而且會在每週的星期二和星期四執行。

gcloud compute resource-policies create snapshot-schedule SCHEDULE_NAME \
    --description "MY WEEKLY SNAPSHOT SCHEDULE" \
    --max-retention-days 10 \
    --start-time 22:00 \
    --weekly-schedule tuesday,thursday \
    --region us-west1 \
    --on-source-disk-delete keep-auto-snapshots \
    --snapshot-labels env=dev,media=images \
    --storage-location US

API

在 API 中,建構目標為 resourcePolicies.insertPOST 要求,以建立快照排程。您至少必須在要求中納入快照排程名稱、快照儲存地區位置和快照頻率。

根據預設,onSourceDiskDelete 參數設定為 keepAutoSnapshots。這代表如果來源磁碟遭到刪除,系統會無限期保留該磁碟自動產生的快照。或者,您也可以將旗標設為 applyRetentionPolicy,以套用您的保留政策。

下列範例設定的每日快照排程每天會在世界標準時間 12:00 開始作業。此外,此範例同時設定了 5 天的保留政策,因此系統會在 5 天後自動移除快照。

您也可以在要求中包含快照位置選項快照標籤,以確保快照儲存在您選擇的位置。

POST https://compute.googleapis.com/compute/v1/projects/[PROJECT_ID]/regions/[REGION]/resourcePolicies

{
 "name": "[SCHEDULE_NAME]",
 "description": "[SCHEDULE_DESCRIPTION]",
 "snapshotSchedulePolicy": {
   "schedule": {
     "dailySchedule": {
       "startTime": "12:00",
       "daysInCycle": "1"
     }
   },
   "retentionPolicy": {
     "maxRetentionDays": "5"
   },
   "snapshotProperties": {
     "guestFlush": "False",
     "labels": {
       "env": "dev",
       "media": "images"
     },
     "storageLocations": ["US"]
   }
 }
}

其中:

  • [PROJECT_ID] 是專案名稱。
  • [REGION] 是快照排程資源政策的位置。
  • [SCHEDULE_DESCRIPTION] 是快照排程的說明。
  • [SCHEDULE_NAME] 是快照排程的名稱。

同樣地,您可以建立每週或每月排程。如要進一步瞭解每週或每月排程的設定,請參閱 API 參考資料

舉例來說,下列要求建立的每週排程會在星期二的 9:00 和星期四的 2:00 進行作業。

POST https://compute.googleapis.com/compute/v1/projects/[PROJECT_ID]/regions/[REGION]/resourcePolicies

{
 "name": "[SCHEDULE_NAME]",
 "description": "[SCHEDULE_DESCRIPTION]",
 "snapshotSchedulePolicy": {
   "schedule": {
     "weeklySchedule": {
       "dayOfWeeks": [
       {
         "day": "Monday",
         "startTime": "9:00"
       },
       {
         "day": "Thursday",
         "startTime": "2:00"
       }
       ]
     }
   },
  "retentionPolicy": {
    "maxRetentionDays": "5"
  },
  "snapshotProperties": {
    "guestFlush": "False",
    "labels": {
      "production": "webserver"
    },
    "storageLocations": ["US"]
  }
 }
}

將快照排程附加至磁碟

建立排程之後,請將排程附加至現有的磁碟。您可以使用主控台、gcloud 指令或 Compute Engine API 方法來完成這項操作。

主控台

將快照排程附加至現有的磁碟。

  1. 前往 Google Cloud 控制台的「Disks」(磁碟) 頁面。

    前往「Disks」(磁碟) 頁面

  2. 選取要附加快照排程的磁碟名稱。系統隨即會開啟「管理磁碟」頁面。
  3. 在「管理磁碟」頁面中,將游標懸停在「更多動作」選單上,然後選取「編輯」
  4. 使用「Snapshot schedule」(快照排程) 下拉式選單,將排程加入磁碟,或是建立新的排程。
  5. 如要建立新的排程,請按一下 [Create] (建立)
  6. 按一下 [Save] (儲存) 來完成工作。

gcloud

如要將快照排程附加至磁碟,請使用 disks add-resource-policies gcloud 指令。

gcloud compute disks add-resource-policies [DISK_NAME] \
    --resource-policies [SCHEDULE_NAME] \
    --zone [ZONE]

其中:

  • [DISK_NAME] 是現有磁碟的名稱。
  • [SCHEDULE_NAME] 是快照排程的名稱。
  • [ZONE] 是磁碟的位置。

API

在 API 中,建構目標為 disks.addResourcePoliciesPOST 要求,以將快照排程附加至現有磁碟。

POST https://compute.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/disks/[DISK_NAME]/addResourcePolicies

{
  "resourcePolicies": [
    "regions/[REGION]/resourcePolicies/[SCHEDULE_NAME]"
  ]
}

其中:

  • [PROJECT_ID] 是專案名稱。
  • [ZONE] 是磁碟的位置。
  • [REGION] 是快照排程的位置。
  • [DISK_NAME] 是磁碟名稱。
  • [SCHEDULE_NAME] 是該地區中要套用到這個磁碟的快照排程名稱。

從快照還原資料

如果您使用快照備份開機或非開機磁碟,可以根據快照建立新磁碟。

限制

  • 新磁碟的大小必須至少與快照的原始來源磁碟大小相同。如果您建立的磁碟大於快照的原始來源磁碟,則必須調整永久磁碟上的檔案系統大小,以便納入額外的磁碟空間。根據您的作業系統和檔案系統類型,您可能需要使用不同的檔案系統大小調整工具。詳情請參閱作業系統說明文件。

從快照建立磁碟,並將其附加至 VM

主控台

  1. 前往 Google Cloud 控制台的「快照」頁面。

    前往「快照」

  2. 尋找您要還原的快照名稱。

  3. 前往「Disks」(磁碟) 頁面。

    前往「Disks」(磁碟) 頁面

  4. 按一下「建立新磁碟」

  5. 指定下列設定參數:

    • 磁碟名稱。
    • 磁碟類型。
    • 您也可以選擇覆寫預設地區和區域選取項目。 您可以選取任何地區和區域,無論來源快照的儲存位置為何。
  6. 在 [Source type] (來源類型) 下方,按一下 [Snapshot] (快照)

  7. 選取要還原的快照名稱。

  8. 選取新磁碟的大小 (以 GB 為單位)。這個數字必須等於或大於快照原始來源磁碟的大小。

  9. 按一下 [Create] (建立) 來建立磁碟。

然後將新磁碟附加至現有執行個體。

  1. 前往「VM instances」(VM 執行個體) 頁面。

    前往「VM instances」(VM 執行個體) 頁面

  2. 按一下您要還原非開機磁碟的執行個體名稱。
  3. 在執行個體詳細資料頁面的頂端,按一下 [Edit] (編輯)
  4. 在「Additional Disks」(其他磁碟) 下方,按一下 [+ Attach existing disk] (+ 連接現有的磁碟)
  5. 選取透過快照建立的新磁碟名稱。
  6. 按一下「完成」即可連結磁碟。
  7. 在執行個體詳細資料頁面的底部,按一下 [Save] (儲存) 將變更套用到執行個體。

gcloud

  1. 使用 gcloud compute snapshots list 指令尋找要還原的快照名稱:

    gcloud compute snapshots list
    
  2. 使用 gcloud compute snapshots describe 指令尋找要還原的快照大小:

    gcloud compute snapshots describe SNAPSHOT_NAME
    

    SNAPSHOT_NAME 替換為要還原的快照名稱。

  3. 使用 gcloud compute disks create 指令從快照建立新的地區區域磁碟。如果您需要 SSD 永久磁碟以獲得額外的總處理量或 IOPS,請加上 --type 標記並指定 pd-ssd

    gcloud compute disks create DISK_NAME \
        --size=DISK_SIZE \
        --source-snapshot=SNAPSHOT_NAME \
        --type=DISK_TYPE
    

    更改下列內容:

    • DISK_NAME:新磁碟的名稱。
    • DISK_SIZE:新磁碟的大小 (以 GB 為單位)。這個數字必須等於或大於快照原始來源磁碟的大小。
    • SNAPSHOT_NAME:要還原的快照名稱。
    • DISK_TYPE:磁碟類型的完整或部分網址。例如:https://www.googleapis.com/compute/v1/projects/PROJECT_ID /zones/ZONE/diskTypes/pd-ssd
  4. 使用 gcloud compute instances attach-disk 指令,將新磁碟連結至現有執行個體:

    gcloud compute instances attach-disk INSTANCE_NAME \
        --disk DISK_NAME
    

    更改下列內容:

    • INSTANCE_NAME 是執行個體的名稱。
    • DISK_NAME 是透過快照建立的磁碟名稱。

API

  1. 建構對 snapshots.listGET 要求,以顯示專案中的快照清單。

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/snapshots

    PROJECT_ID 替換為您的專案 ID。

  2. 使用 disks.insert 方法建構 POST 要求,以建立區域磁碟。請包含 namesizeGbtype 屬性。如要使用快照還原磁碟,就必須包含 sourceSnapshot 屬性。

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/disks
    
    {
     "name": "DISK_NAME",
     "sizeGb": "DISK_SIZE",
     "type": "zones/ZONE/diskTypes/DISK_TYPE"
     "sourceSnapshot": "SNAPSHOT_NAME"
    }
    

    更改下列內容:

    • PROJECT_ID:您的專案 ID。
    • ZONE 是執行個體和新磁碟的所在區域。
    • DISK_NAME:新磁碟的名稱。
    • DISK_SIZE:新磁碟的大小 (以 GB 為單位)。這個數字必須等於或大於快照原始來源磁碟的大小。
    • DISK_TYPE:磁碟類型的完整或部分網址。例如 https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ ZONE/diskTypes/pd-ssd
    • SNAPSHOT_NAME:您要還原磁碟的來源快照。
  3. 接著,您可以對 instances.attachDisk 方法建構 POST 要求,並加入您剛從快照建立的區域磁碟網址,將新磁碟附加至現有執行個體。

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME/attachDisk
    
    {
     "source": "/compute/v1/projects/PROJECT_ID/zones/ZONE/disks/DISK_NAME"
    }
    

    更改下列內容:

    • PROJECT_ID 是您的專案 ID。
    • ZONE 是執行個體和新磁碟的所在區域。
    • INSTANCE_NAME 是要新增磁碟的執行個體名稱。
    • DISK_NAME 是新磁碟的名稱。

Go

Go

在試用這個範例之前,請先按照Go使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Go API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"fmt"
	"io"

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

// createDiskFromSnapshot creates a new disk in a project in given zone.
func createDiskFromSnapshot(
	w io.Writer,
	projectID, zone, diskName, diskType, snapshotLink string,
	diskSizeGb int64,
) error {
	// projectID := "your_project_id"
	// zone := "us-west3-b" // should match diskType below
	// diskName := "your_disk_name"
	// diskType := "zones/us-west3-b/diskTypes/pd-ssd"
	// snapshotLink := "projects/your_project_id/global/snapshots/snapshot_name"
	// diskSizeGb := 120

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

	req := &computepb.InsertDiskRequest{
		Project: projectID,
		Zone:    zone,
		DiskResource: &computepb.Disk{
			Name:           proto.String(diskName),
			Zone:           proto.String(zone),
			Type:           proto.String(diskType),
			SourceSnapshot: proto.String(snapshotLink),
			SizeGb:         proto.Int64(diskSizeGb),
		},
	}

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

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

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

	return nil
}

Java

Java

在試用這個範例之前,請先按照Java使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Java API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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

public class CreateDiskFromSnapshot {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.

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

    // Name of the zone in which you want to create the disk.
    String zone = "europe-central2-b";

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

    // The type of disk you want to create. This value uses the following format:
    // "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
    // For example: "zones/us-west3-b/diskTypes/pd-ssd"
    String diskType = String.format("zones/%s/diskTypes/pd-ssd", zone);

    // Size of the new disk in gigabytes.
    long diskSizeGb = 10;

    // The full path and name of the snapshot that you want to use as the source for the new disk.
    // This value uses the following format:
    // "projects/{projectName}/global/snapshots/{snapshotName}"
    String snapshotLink = String.format("projects/%s/global/snapshots/%s", projectId,
        "SNAPSHOT_NAME");

    createDiskFromSnapshot(projectId, zone, diskName, diskType, diskSizeGb, snapshotLink);
  }

  // Creates a new disk in a project in given zone, using a snapshot.
  public static void createDiskFromSnapshot(String projectId, String zone, String diskName,
      String diskType, long diskSizeGb, String snapshotLink)
      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 `disksClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (DisksClient disksClient = DisksClient.create()) {

      // Set the disk properties and the source snapshot.
      Disk disk = Disk.newBuilder()
          .setName(diskName)
          .setZone(zone)
          .setSizeGb(diskSizeGb)
          .setType(diskType)
          .setSourceSnapshot(snapshotLink)
          .build();

      // Create the insert disk request.
      InsertDiskRequest insertDiskRequest = InsertDiskRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setDiskResource(disk)
          .build();

      // Wait for the create disk operation to complete.
      Operation response = disksClient.insertAsync(insertDiskRequest)
          .get(3, TimeUnit.MINUTES);

      if (response.hasError()) {
        System.out.println("Disk creation failed!" + response);
        return;
      }
      System.out.println("Disk created. Operation Status: " + response.getStatus());
    }
  }
}

Node.js

Node.js

在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Node.js API 參考說明文件

如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'europe-central2-b';
// const diskName = 'YOUR_DISK_NAME';
// const diskType = 'zones/us-west3-b/diskTypes/pd-ssd';
// const diskSizeGb = 10;
// const snapshotLink = 'projects/project_name/global/snapshots/snapshot_name';

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

async function createDiskFromSnapshot() {
  const disksClient = new compute.DisksClient();

  const [response] = await disksClient.insert({
    project: projectId,
    zone,
    diskResource: {
      sizeGb: diskSizeGb,
      name: diskName,
      zone,
      type: diskType,
      sourceSnapshot: snapshotLink,
    },
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

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

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

createDiskFromSnapshot();

Python

Python

如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 Python API 參考說明文件

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_disk_from_snapshot(
    project_id: str,
    zone: str,
    disk_name: str,
    disk_type: str,
    disk_size_gb: int,
    snapshot_link: str,
) -> compute_v1.Disk:
    """
    Creates a new disk in a project in given zone.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone in which you want to create the disk.
        disk_name: name of the disk you want to create.
        disk_type: the type of disk you want to create. This value uses the following format:
            "zones/{zone}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
            For example: "zones/us-west3-b/diskTypes/pd-ssd"
        disk_size_gb: size of the new disk in gigabytes
        snapshot_link: a link to the snapshot you want to use as a source for the new disk.
            This value uses the following format: "projects/{project_name}/global/snapshots/{snapshot_name}"

    Returns:
        An unattached Disk instance.
    """
    disk_client = compute_v1.DisksClient()
    disk = compute_v1.Disk()
    disk.zone = zone
    disk.size_gb = disk_size_gb
    disk.source_snapshot = snapshot_link
    disk.type_ = disk_type
    disk.name = disk_name
    operation = disk_client.insert(project=project_id, zone=zone, disk_resource=disk)

    wait_for_extended_operation(operation, "disk creation")

    return disk_client.get(project=project_id, zone=zone, disk=disk_name)

掛接磁碟

  1. 在終端機中,使用 lsblk 指令列出連接至執行個體的磁碟,並搜尋您要掛接的磁碟。

    $ sudo lsblk
    
    NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
    sda      8:0    0   10G  0 disk
    └─sda1   8:1    0   10G  0 part /
    sdb      8:16   0  250G  0 disk
    

    在本範例中,sdb 是新空白永久磁碟的裝置名稱。

  2. 使用掛接工具將磁碟掛接至執行個體,並啟用 discard 選項:

    $ sudo mount -o discard,defaults /dev/DEVICE_NAME /home/jupyter

    更改下列內容:

    • DEVICE_NAME:要掛接的磁碟裝置名稱。
  3. 設定磁碟的讀取與寫入權限。在本範例中,授予所有使用者對磁碟的寫入存取權。

    $ sudo chmod a+w /home/jupyter

後續步驟