스냅샷을 사용하여 데이터 백업

이 페이지에서는 스냅샷을 만들어 Vertex AI Workbench 사용자 관리형 노트북 인스턴스에 저장된 데이터를 백업하는 방법을 보여줍니다.

인스턴스의 데이터는 영역 영구 디스크에 저장됩니다. 사용자는 이 디스크의 스냅샷을 만들고 사용하여 데이터를 백업하고, 반복 백업 일정을 만들고, 데이터를 새 인스턴스로 복원할 수 있습니다.

스냅샷 만들기

실행 중인 인스턴스에 연결된 상태에서도 디스크에서 스냅샷을 만들 수 있습니다. 스냅샷은 전역 리소스이므로 동일한 프로젝트 내의 새로운 디스크 또는 인스턴스로 데이터를 복원하는 데 사용할 수 있습니다. 또한 프로젝트 간에 스냅샷을 공유할 수 있습니다.

콘솔

  1. Google Cloud 콘솔에서 VM 인스턴스 페이지로 이동합니다.

    VM 인스턴스로 이동
    남은 단계가 Google Cloud 콘솔에 자동으로 표시됩니다.

  2. VM 인스턴스가 포함된 프로젝트를 선택합니다.
  3. 이름 열에서 백업할 영구 디스크가 있는 VM의 이름을 클릭합니다.
  4. 스토리지:
    • 부팅 디스크를 백업하려면 부팅 디스크 섹션에서 부팅 디스크 이름을 클릭합니다.
    • 연결된 영구 디스크를 백업하려면 추가 디스크에서 연결된 영구 디스크의 이름을 클릭합니다.
  5. 스냅샷 만들기를 클릭합니다.
  6. 이름에 스냅샷 목적을 식별하는 데 도움이 되는 고유한 이름을 입력합니다. 예를 들면 다음과 같습니다.
    • boot-disk-snapshot
    • attached-persistent-disk-snapshot
  7. 유형에서 기본값은 장기 백업 및 재해 복구에 가장 적합한 일반 스냅샷입니다.

    비용 효율적인 데이터 보관을 위해서는 보관처리 스냅샷을 선택합니다.

  8. 위치 섹션에서 스냅샷 스토리지 위치를 선택합니다. 스냅샷 설정에 정의된 사전 정의되었거나 맞춤설정된 기본 위치가 자동으로 선택됩니다. 선택적으로 다음을 수행해서 스냅샷 설정을 무효화하고 커스텀 스토리지 위치에 스냅샷을 저장할 수 있습니다.

    1. 스냅샷에 대해 원하는 스토리지 위치 유형을 선택합니다.

      • 더 높은 가용성을 위해서는 더 높은 비용으로 멀티 리전을 선택합니다.
      • 더 낮은 비용으로 데이터의 물리적 위치를 세부적으로 제어하려면 리전 스냅샷을 선택합니다.
    2. 위치 선택 필드에서 사용하려는 특정 리전 또는 멀티 리전을 선택합니다. 소스 디스크에 가장 가까운 리전 또는 멀티 리전을 사용하려면 디스크 위치 기준을 선택합니다.

  9. 수동 스냅샷을 만들려면 만들기를 클릭합니다.

gcloud

  1. Google Cloud 콘솔에서 Cloud Shell을 활성화합니다.

    Cloud Shell 활성화

    Google Cloud 콘솔 하단에서 Cloud Shell 세션이 시작되고 명령줄 프롬프트가 표시됩니다. Cloud Shell은 Google Cloud CLI가 사전 설치된 셸 환경으로, 현재 프로젝트의 값이 이미 설정되어 있습니다. 세션이 초기화되는 데 몇 초 정도 걸릴 수 있습니다.

  2. 스냅샷 설정에서 또는 선택한 대체 스토리지 위치를 사용하여 정의한 스토리지 위치 정책을 사용해 스냅샷을 만듭니다. 자세한 내용은 스냅샷 스토리지 위치 선택을 참조하세요. 스냅샷 이름을 지정해야 합니다. 이름은 1~63자(영문 기준)여야 하며 RFC 1035를 준수해야 합니다.

    • 스냅샷 설정에 구성된 사전 정의되었거나 맞춤 설정된 기본 위치에 Persistent Disk 볼륨 스냅샷을 만들려면 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: 스냅샷을 만들려는 영역 Persistent Disk 볼륨의 이름
      • SNAPSHOT_TYPE: 스냅샷 유형(STANDARD 또는 ARCHIVE). 스냅샷 유형을 지정하지 않으면 STANDARD 스냅샷이 생성됩니다. 비용 효율적인 데이터 보관을 위해서는 보관처리 스냅샷을 선택합니다.
      • SOURCE_DISK_ZONE: 스냅샷을 만들려는 영역 Persistent Disk 볼륨의 영역

      스냅샷 설정에 구성된 사전 정의되었거나 맞춤 설정된 기본 스토리지 위치를 무효화하려는 경우에만 --storage-location 플래그를 사용합니다.

    gcloud CLI는 작업이 READY 또는 FAILED 상태를 반환할 때까지 기다립니다. 또는 최대 제한 시간에 도달한 후 스냅샷에 대해 마지막으로 알려진 세부정보를 반환합니다.

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 http://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: 스냅샷 유형(STANDARD 또는 ARCHIVE). 스냅샷 유형을 지정하지 않으면 STANDARD 스냅샷이 생성됩니다.
  • 또는 스냅샷 설정을 무효화하고 커스텀 스토리지 위치에 스냅샷을 만들려면 snapshots.insert 메서드에 대해 POST 요청을 수행하고 요청에 storageLocations 속성을 포함합니다.

    POST http://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: 스냅샷 유형(STANDARD 또는 ARCHIVE). 스냅샷 유형을 지정하지 않으면 STANDARD 스냅샷이 생성됩니다.
    • STORAGE_LOCATION: 스냅샷을 저장할 Cloud Storage 멀티 리전 또는 Cloud Storage 리전. 스토리지 위치는 하나만 지정할 수 있습니다.

      스냅샷 설정에 구성된 사전 정의되었거나 맞춤 설정된 기본 스토리지 위치를 무효화하려는 경우에만 storageLocations 매개변수를 사용합니다.

Go

Go

이 샘플을 사용해 보기 전에 Compute Engine 빠른 시작: 클라이언트 라이브러리 사용의 설정 안내를 따르세요.

Compute Engine에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	compute "cloud.go888ogle.com.fqhub.com/go/compute/apiv1"
	computepb "cloud.go888ogle.com.fqhub.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:
    // http://cloud.go888ogle.com.fqhub.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:
            http://cloud.go888ogle.com.fqhub.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 인스턴스 페이지로 이동합니다.

    VM 인스턴스로 이동
    남은 단계가 Google Cloud 콘솔에 자동으로 표시됩니다.

  2. VM 인스턴스가 포함된 프로젝트를 선택합니다.
  3. 이름 열에서 스냅샷 일정을 만들 영구 디스크가 있는 VM의 이름을 클릭합니다.
  4. 스토리지에서 스냅샷 일정을 만들 부팅 디스크 또는 추가 디스크의 이름을 클릭합니다.
  5. 수정을 클릭합니다. 작업 더보기 메뉴를 클릭한 후 수정을 클릭해야 할 수 있습니다.
  6. 스냅샷 일정에서 일정 만들기를 선택합니다.
  7. 이름에 다음의 스냅샷 일정 이름 중 하나를 입력합니다.
    • boot-disk-snapshot-schedule
    • attached-persistent-disk-snapshot-schedule
  8. 위치 섹션에서 스냅샷 스토리지 위치를 선택합니다. 스냅샷 설정에 정의된 사전 정의되었거나 맞춤설정된 기본 위치가 자동으로 선택됩니다. 선택적으로 다음을 수행해서 스냅샷 설정을 무효화하고 커스텀 스토리지 위치에 스냅샷을 저장할 수 있습니다.

    1. 스냅샷에 대해 원하는 스토리지 위치 유형을 선택합니다.

      • 더 높은 가용성을 위해서는 더 높은 비용으로 멀티 리전을 선택합니다.
      • 리전 스냅샷을 선택하여 저렴한 비용으로 데이터의 물리적 위치를 더 세부적으로 제어합니다.
    2. 위치 선택 필드에서 사용하려는 특정 리전 또는 멀티 리전을 선택합니다. 소스 디스크에 가장 가까운 리전 또는 다중 리전을 사용하려면 디스크 위치 기준을 선택합니다.

  9. 스냅샷 일정 만들기를 완료하려면 만들기를 클릭합니다.
  10. 이 스냅샷 일정을 영구 디스크에 연결하려면 저장을 클릭합니다.

gcloud

영구 디스크의 스냅샷 일정을 만들려면 compute resource-policies create snapshot-schedulegcloud 명령어를 사용합니다. 일정 빈도를 시간, 일 또는 주 단위로 설정합니다.

  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]은 UTC 시작 시간입니다. 시작 시간은 정시에 시작해야 합니다. 예를 들면 다음과 같습니다.
    • 태평양 표준시(PST 기준) 오후 2시는 22:00입니다.
    • 시작 시간을 22:13으로 설정하면 오류가 발생합니다.
  • [SNAPSHOT_INTERVAL]은 스냅샷 실행 간격을 정의합니다. 1~23 사이의 정수를 사용하여 시간 단위 일정을 설정합니다. 24로 균등하게 나누어지는 시간 단위 숫자를 선택하세요. 예를 들어 --hourly-schedule을 12로 설정하면 스냅샷이 12시간마다 생성됩니다. 주간 단위 일정의 경우 스냅샷을 만들 요일을 정의합니다. 요일을 정확히 입력해야 하며 대소문자를 구분하지 않습니다. 스냅샷 빈도 플래그 hourly-schedule, daily-schedule, weekly-schedule을 함께 사용할 수 없습니다. 스냅샷 일정으로 한 가지만 선택해야 합니다.

  • [FILE_NAME]은 스냅샷 일정이 포함된 파일 이름입니다(이 형식으로 일정을 제공하려는 경우). 파일을 사용하여 다른 요일과 다른 시간으로 주 단위 일정을 지정할 수 있지만 명령줄에서 여러 주 단위 일정을 직접 지정할 수는 없습니다. 예를 들어 파일에 다음과 같이 월요일과 수요일에 스냅샷 일정을 지정할 수 있습니다([{"day": "MONDAY", "startTime": "04:00"}, {"day": "WEDNESDAY", "startTime": "02:00"}]). 파일에 시작 시간을 포함하면 --start-time 플래그를 설정하지 않아도 됩니다. 일정은 UTC 표준시를 사용합니다.

  • [DELETION_OPTION]을 통해 소스 디스크가 삭제된 경우 스냅샷 처리 방식을 결정합니다. 이 플래그를 생략하여 기본 keep-auto-snapshots을 선택하거나 apply-retention-policy를 사용하여 보관 정책을 적용하세요.

다음은 스냅샷 일정을 설정하는 추가 예제입니다. 모든 예시에는 다음 사항이 적용됩니다.

  • 디스크 삭제 규칙이 포함됩니다. --on-source-disk-delete 플래그가 기본 keep-auto-snapshots으로 설정되어 자동 생성된 모든 스냅샷을 무기한 유지합니다. 다른 방법으로는 이 플래그를 apply-retention-policy로 설정하여 스냅샷 보관 정책을 사용합니다.
  • 스토리지 위치가 US로 설정되어 생성된 모든 스냅샷이 US 멀티 리전에 저장됩니다.
  • env=devmedia=images 라벨이 생성된 모든 스냅샷에 적용됩니다.
  • 보관 정책이 10일로 설정됩니다.

시간 단위 일정:이 예시에서 스냅샷 일정은 UTC 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

일 단위 일정:이 예시에서 스냅샷 일정은 UTC 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

주 단위 일정: 이 예시에서 스냅샷 일정은 UTC 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.insert에 대한 POST 요청을 작성합니다. 최소한 스냅샷 일정 이름, 스냅샷 스토리지 리전 위치, 스냅샷 빈도는 포함되어야 합니다.

기본적으로 onSourceDiskDelete 매개변수가 keepAutoSnapshots으로 설정됩니다. 즉, 소스 디스크가 삭제되면 해당 디스크의 자동 생성된 스냅샷이 무기한 보관됩니다. 또는 플래그를 applyRetentionPolicy로 설정하여 보관 정책을 적용할 수 있습니다.

다음 예시는 UTC 12:00에 시작하여 매일 반복되는 일 단위 스냅샷 일정을 설정합니다. 또한 이 예시에서는 보관 정책을 5일로 설정하여 스냅샷이 5일 후에 자동으로 삭제됩니다.

요청에 스냅샷 지역 옵션스냅샷 라벨을 포함하여 스냅샷이 원하는 위치에 저장되도록 할 수도 있습니다.

POST http://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 http://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 콘솔에서 디스크 페이지로 이동합니다.

    디스크 페이지로 이동

  2. 스냅샷 일정을 연결할 디스크의 이름을 선택합니다. 그러면 디스크 관리 페이지가 열립니다.
  3. 디스크 관리 페이지에 커서를 가져가 작업 더보기 메뉴를 클릭하고 수정을 선택합니다.
  4. 스냅샷 일정 드롭다운 메뉴를 사용하여 디스크에 일정을 추가하거나 새 일정을 만듭니다.
  5. 새 일정을 만드는 경우 만들기를 클릭합니다.
  6. 저장을 클릭하여 작업을 완료합니다.

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.addResourcePolicies에 대한 POST 요청을 작성합니다.

POST http://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. 디스크 페이지로 이동합니다.

    디스크 페이지로 이동

  4. 새 디스크 만들기를 클릭합니다.

  5. 다음 구성 매개변수를 지정합니다.

    • 디스크의 이름
    • 디스크의 유형
    • 원할 경우 기본 리전 및 영역 선택을 재정의할 수 있습니다. 소스 스냅샷의 스토리지 위치에 관계없이 모든 리전과 영역을 선택할 수 있습니다.
  6. 소스 유형에서 스냅샷을 클릭합니다.

  7. 복원할 스냅샷의 이름을 선택합니다.

  8. 새 디스크의 크기(GB)를 선택합니다. 이 값은 스냅샷의 원래 소스 디스크보다 크거나 같아야 합니다.

  9. 만들기를 클릭하여 디스크를 만듭니다.

그런 후 새 디스크를 기존 인스턴스에 연결할 수 있습니다.

  1. VM 인스턴스 페이지로 이동합니다.

    VM 인스턴스 페이지로 이동

  2. 비부팅 디스크를 복원할 인스턴스의 이름을 클릭합니다.
  3. 인스턴스 세부정보 페이지의 상단에서 수정을 클릭합니다.
  4. 추가 디스크에서 기존 디스크 연결을 클릭합니다.
  5. 스냅샷에서 만든 새 디스크의 이름을 선택합니다.
  6. 완료를 클릭하여 디스크를 연결합니다.
  7. 인스턴스 세부정보 페이지 하단에 있는 저장을 클릭해 변경사항을 인스턴스에 적용합니다.

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 명령어를 사용하여 새 리전 또는 영역 디스크를 만듭니다. 추가 처리량 또는 IOPS에 사용할 SSD 영구 디스크가 필요한 경우에는 --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: 디스크 유형의 전체 또는 부분 URL. 예를 들면 http://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.list에 대한 GET 요청을 작성하여 프로젝트에 스냅샷 목록을 표시합니다.

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

    PROJECT_ID를 프로젝트 ID로 바꿉니다.

  2. disks.insert 메서드로 POST 요청을 작성하여 영역 디스크를 만듭니다. name, sizeGb, type 속성을 포함합니다. 스냅샷을 사용해 디스크를 복원하려면 sourceSnapshot 속성을 추가해야 합니다.

    POST http://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: 디스크 유형의 전체 또는 부분 URL. 예를 들면 http://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ ZONE/diskTypes/pd-ssd입니다.
    • SNAPSHOT_NAME: 복원할 디스크의 소스 스냅샷입니다.
  3. 그런 다음에 instances.attachDisk 메서드에 대한 POST 요청을 작성하고 스냅샷에서 방금 만든 영역 디스크의 URL을 포함하여 새 디스크를 기존 인스턴스에 연결할 수 있습니다.

    POST http://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

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Vertex AI Go API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	compute "cloud.go888ogle.com.fqhub.com/go/compute/apiv1"
	computepb "cloud.go888ogle.com.fqhub.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

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 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

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 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
    

다음 단계