보관처리 스냅샷 및 표준 디스크 스냅샷 만들기


표준 스냅샷을 만들어 다음 유형의 디스크에서 데이터를 주기적으로 백업합니다.

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

시작하기 전에

  • 아직 인증을 설정하지 않았다면 설정합니다. 인증은 Google Cloud 서비스 및 API에 액세스하기 위해 ID를 확인하는 프로세스입니다. 로컬 개발 환경에서 코드 또는 샘플을 실행하려면 다음과 같이 Compute Engine에 인증하면 됩니다.

    이 페이지의 샘플 사용 방법에 대한 탭을 선택하세요.

    콘솔

    Google Cloud 콘솔을 사용하여 Google Cloud 서비스 및 API에 액세스할 때는 인증을 설정할 필요가 없습니다.

    gcloud

    1. Google Cloud CLI를 설치한 후 다음 명령어를 실행하여 초기화합니다.

      gcloud init
    2. 기본 리전 및 영역을 설정합니다.

    Terraform

    로컬 개발 환경에서 이 페이지의 Terraform 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 로컬 개발 환경의 인증 설정를 참조하세요.

    Go

    로컬 개발 환경에서 이 페이지의 Go 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 로컬 개발 환경의 인증 설정를 참조하세요.

    Java

    로컬 개발 환경에서 이 페이지의 Java 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 로컬 개발 환경의 인증 설정를 참조하세요.

    Node.js

    로컬 개발 환경에서 이 페이지의 Node.js 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 로컬 개발 환경의 인증 설정를 참조하세요.

    Python

    로컬 개발 환경에서 이 페이지의 Python 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

    1. Google Cloud CLI를 설치합니다.
    2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

      gcloud init
    3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

      gcloud auth application-default login

    자세한 내용은 로컬 개발 환경의 인증 설정를 참조하세요.

    REST

    로컬 개발 환경에서 이 페이지의 REST API 샘플을 사용하려면 gcloud CLI에 제공한 사용자 인증 정보를 사용합니다.

      Google Cloud CLI를 설치한 후 다음 명령어를 실행하여 초기화합니다.

      gcloud init

필수 역할 및 권한

표준 스냅샷을 만드는 데 필요한 권한을 얻으려면 관리자에게 프로젝트에 대한 다음 IAM 역할을 부여해 달라고 요청하세요.

역할 부여에 대한 자세한 내용은 액세스 관리를 참조하세요.

이러한 사전 정의된 역할에는 표준 스냅샷을 만드는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 펼치세요.

필수 권한

표준 스냅샷을 만들려면 다음 권한이 필요합니다.

  • 영역 디스크의 스냅샷 만들기:
    • 프로젝트에 대한 compute.snapshots.create 권한
    • 디스크에 대한 compute.disks.createSnapshot 권한
  • 디스크의 데이터를 사용하여 리전 디스크의 스냅샷 만들기:
    • 프로젝트에 대한 compute.snapshots.create 권한
    • 소스 VM에 대한 compute.instances.useReadOnly 권한
    • 디스크에 대한 compute.disks.createSnapshot 권한
  • 복제본 복구 체크포인트에서 리전 디스크의 스냅샷 만들기:
    • 프로젝트에 대한 compute.snapshots.create 권한
    • 디스크에 대한 compute.disks.createSnapshot 권한

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

스냅샷 생성 준비

Persistent Disk 또는 하이퍼디스크 스냅샷을 만들려면 다음을 수행합니다.

  • 디스크의 스냅샷을 준비하려면 Compute Engine 디스크 스냅샷에 대한 권장사항을 검토하세요.

  • 모든 새 스냅샷의 기본 스토리지 위치를 맞춤설정하려면 프로젝트의 스냅샷 설정을 업데이트합니다. 스냅샷 설정을 처음 업데이트할 때까지 Google Cloud에서 사전 정의된 기본 스토리지 위치 값을 유지합니다. 이 사전 정의된 위치는 소스 디스크에 가장 가까운 멀티 리전입니다.

  • 스냅샷 일정을 만들고 디스크에 연결하는 방법에 대해 알아보려면 디스크 스냅샷 일정 만들기를 검토하세요. 디스크를 예약된 스냅샷으로 정기적으로 백업하면 예기치 않은 데이터 손실 위험을 줄일 수 있습니다.

Persistent Disk 볼륨의 스냅샷 만들기

영역 Persistent Disk의 스냅샷을 만드는지 또는 영역 Persistent Disk의 스냅샷을 만드는지에 따라 Persistent Disk 볼륨의 스냅샷을 만드는 방법이 다릅니다.

영역 Persistent Disk의 스냅샷 만들기

콘솔

  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

스냅샷 설정에 따라 또는 선택한 대체 스토리지 위치를 사용해서 정의된 스토리지 위치 정책으로 스냅샷을 만들 수 있습니다. 자세한 내용은 스냅샷 스토리지 위치 선택을 참조하세요.

  • 스냅샷 설정에 구성된 사전 정의되었거나 맞춤설정된 기본 위치에 스냅샷을 만들려면 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
    

    다음을 바꿉니다.

    • SNAPSHOT_NAME: 스냅샷의 이름입니다.
    • SOURCE_ZONE: 소스 디스크의 영역
    • SOURCE_DISK_NAME: 스냅샷을 만들려는 Persistent Disk 볼륨의 이름
    • SNAPSHOT_TYPE: 스냅샷 유형(STANDARD 또는 ARCHIVE). 스냅샷 유형을 지정하지 않으면 STANDARD 스냅샷이 생성됩니다.
    • STORAGE_LOCATION: (선택사항) 스냅샷을 저장할 Cloud Storage 멀티 리전 또는 Cloud Storage 리전. 스토리지 위치는 하나만 지정할 수 있습니다.

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

Terraform

영역 Persistent Disk의 스냅샷을 만들려면 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 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Compute Engine Go API 참조 문서를 확인하세요.

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

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
	"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

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

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 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Compute Engine Node.js API 참조 문서를 확인하세요.

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 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Compute Engine Python API 참조 문서를 확인하세요.

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)

REST

스냅샷 설정에 따라 또는 선택한 대체 스토리지 위치를 사용해서 정의된 스토리지 위치 정책으로 스냅샷을 만들 수 있습니다. 자세한 내용은 스냅샷 스토리지 위치 선택을 참조하세요.

  • 스냅샷 설정에 구성된 사전 정의되었거나 맞춤설정된 기본 위치에 스냅샷을 만들려면 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"
    }
    
  • 또는 스냅샷 설정을 재정의하고 커스텀 스토리지 위치에 스냅샷을 만들려면 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: 스냅샷을 만들려는 Persistent Disk 볼륨의 이름
  • SNAPSHOT_TYPE: 스냅샷 유형(STANDARD 또는 ARCHIVE). 스냅샷 유형을 지정하지 않으면 STANDARD 스냅샷이 생성됩니다.
  • STORAGE_LOCATION: (선택사항) 스냅샷을 저장할 Cloud Storage 멀티 리전 또는 Cloud Storage 리전. 스토리지 위치는 하나만 지정할 수 있습니다.

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

리전 Persistent Disk의 스냅샷 만들기

다음 방법 중 하나로 리전 Persistent Disk 볼륨의 스냅샷을 만들 수 있습니다.

  • 소스 디스크의 데이터를 사용합니다. 이 스냅샷 생성 메서드를 사용하려면 동기화된 영역 복제본을 사용할 수 있어야 합니다.
  • 성능 저하된 디스크의 복제본 복구 체크포인트를 사용합니다. Google Cloud CLI 또는 REST를 사용하여 체크포인트에서만 스냅샷을 만들 수 있습니다.

디스크가 준비되면 스냅샷을 만들 수 있습니다. 리전 Persistent Disk의 스냅샷을 생성할 때 소스 디스크가 있는 리전을 지정해야 합니다.

콘솔

  1. Google Cloud 콘솔의 스냅샷 만들기 페이지로 이동합니다.

    스냅샷 만들기 페이지로 이동
  2. 스냅샷 이름을 입력합니다.
  3. 스냅샷 유형을 선택합니다. 기본값은 장기 백업 및 재해 복구에 가장 적합한 STANDARD 스냅샷입니다.

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

  4. 선택사항: 스냅샷에 대한 설명을 입력합니다.
  5. 소스 디스크에서 스냅샷을 만들려는 기존 디스크를 선택합니다.
  6. 위치 섹션에서 스냅샷 스토리지 위치를 선택합니다.

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

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

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

gcloud

소스 디스크의 데이터 또는 복제본 복구 체크포인트를 사용하여 스냅샷을 만들 수 있습니다.

디스크 데이터

스냅샷 설정에 정의된 스토리지 위치 정책 또는 자신이 선택한 다른 스토리지 위치를 사용해 디스크의 데이터에서 스냅샷을 만들 수 있습니다. 자세한 내용은 스냅샷 스토리지 위치 선택을 참조하세요.

  • 스냅샷 설정에 구성된 사전 정의되었거나 맞춤설정된 기본 위치에 스냅샷을 만들려면 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
    

    다음을 바꿉니다.

    • SNAPSHOT_NAME: 스냅샷의 이름입니다.
    • SOURCE_REGION: 소스 디스크의 리전
    • SOURCE_DISK_NAME: 스냅샷을 만들려는 리전 Persistent Disk 볼륨의 이름
    • SNAPSHOT_TYPE: 스냅샷 유형(STANDARD 또는 ARCHIVE). 스냅샷 유형을 지정하지 않으면 STANDARD 스냅샷이 생성됩니다.
    • STORAGE_LOCATION: (선택사항) 스냅샷을 저장할 Cloud Storage 멀티 리전 또는 Cloud Storage 리전. 스토리지 위치는 하나만 지정할 수 있습니다.

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

체크포인트

성능 저하된 디스크의 복제본 복구 체크포인트(미리보기)를 사용하여 스냅샷을 만들 수 있습니다. 불완전한 복제본을 사용할 수 있는 한 스냅샷이 생성됩니다.

복제본 복구 체크포인트를 사용하여 스냅샷을 만들려면 gcloud compute snapshots create 명령어를 사용합니다. 복제본 복구 체크포인트를 사용해서 스냅샷을 만들도록 지정하려면 --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: 스냅샷을 만들려는 프로젝트의 ID입니다.
  • SNAPSHOT_NAME: 스냅샷의 이름입니다.
  • SOURCE_PROJECT_ID: 스냅샷을 만드는 데 사용할 소스 디스크의 프로젝트 ID입니다.
  • SOURCE_REGION: 스냅샷을 만드는 데 사용할 소스 디스크의 리전입니다.
  • SOURCE_DISK_NAME: 스냅샷을 만드는 데 사용할 소스 디스크의 이름입니다.
  • STORAGE_LOCATION: (선택사항) 스냅샷을 저장할 Cloud Storagemulti-region 또는 Cloud Storageregion입니다. 스토리지 위치는 하나만 지정할 수 있습니다.
    스냅샷 설정에 구성된 사전 정의되었거나 맞춤 설정된 기본 스토리지 위치를 재정의하려는 경우에만 사용합니다.
  • SNAPSHOT_TYPE: 스냅샷 유형(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

Google Cloud용 Terraform 공급업체는 리전 Persistent Disk 볼륨의 스냅샷 만들기를 지원하지 않습니다. 이 제한사항을 추적하려면 GitHub의 문제를 참조하세요.

Go

Go

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

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

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
	"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

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

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 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Compute Engine Node.js API 참조 문서를 확인하세요.

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 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Compute Engine Python API 참조 문서를 확인하세요.

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)

REST

소스 디스크의 데이터 또는 복제본 복구 체크포인트를 사용하여 스냅샷을 만들 수 있습니다.

디스크 데이터

스냅샷 설정에 정의된 스토리지 위치 정책 또는 자신이 선택한 다른 스토리지 위치를 사용해 디스크의 데이터에서 스냅샷을 만들 수 있습니다. 자세한 내용은 스냅샷 스토리지 위치 선택을 참조하세요.

  • 스냅샷 설정에 구성된 사전 정의되었거나 맞춤설정된 기본 위치에 스냅샷을 만들려면 snapshots.insert 메서드에 POST 요청을 수행하세요.

    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"
    }
    
  • 또는 스냅샷 설정을 재정의하고 커스텀 스토리지 위치에 스냅샷을 만들려면 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/regions/SOURCE_REGION/disks/SOURCE_DISK_NAME",
      "snapshotType": "SNAPSHOT_TYPE",
      "storageLocations": [
          "STORAGE_LOCATION"
      ],
    }
    

다음을 바꿉니다.

  • DESTINATION_PROJECT_ID: 스냅샷을 만들려는 프로젝트의 ID
  • SNAPSHOT_NAME: 스냅샷의 이름입니다.
  • SOURCE_PROJECT_ID: 소스 디스크 프로젝트의 ID
  • SOURCE_REGION: 소스 디스크의 리전
  • SOURCE_DISK_NAME: 스냅샷을 만들려는 리전 Persistent Disk 볼륨의 이름
  • SNAPSHOT_TYPE: 스냅샷 유형(STANDARD 또는 ARCHIVE). 스냅샷 유형을 지정하지 않으면 STANDARD 스냅샷이 생성됩니다.
  • STORAGE_LOCATION: (선택사항) 스냅샷을 저장할 Cloud Storage 멀티 리전 또는 Cloud Storage 리전. 스토리지 위치는 하나만 지정할 수 있습니다.

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

체크포인트

또는 성능 저하된 디스크의 복제본 복구 체크포인트를 사용하여 스냅샷을 만들 수 있습니다. 불완전한 복제본을 사용할 수 있는 한 스냅샷이 생성됩니다.

복제본 복구 체크포인트를 사용하여 스냅샷을 만들려면 snapshots.insert 메서드에 대해 POST 요청을 수행합니다. 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: 스냅샷을 만들려는 프로젝트의 ID입니다.
  • SNAPSHOT_NAME: 스냅샷의 이름입니다.
  • SOURCE_PROJECT_ID: 스냅샷을 만드는 데 사용할 소스 디스크의 프로젝트 ID입니다.
  • SOURCE_REGION: 스냅샷을 만드는 데 사용할 소스 디스크의 리전입니다.
  • SOURCE_DISK_NAME: 스냅샷을 만드는 데 사용할 소스 디스크의 이름입니다.
  • STORAGE_LOCATION: (선택사항) 스냅샷을 저장할 Cloud Storagemulti-region 또는 Cloud Storageregion입니다. 스토리지 위치는 하나만 지정할 수 있습니다.
    스냅샷 설정에 구성된 사전 정의되었거나 맞춤 설정된 기본 스토리지 위치를 무효화하려는 경우에만 storageLocations 매개변수를 사용합니다.
  • SNAPSHOT_TYPE: 스냅샷 유형(STANDARD 또는 ARCHIVE). 스냅샷 유형을 지정하지 않으면 STANDARD 스냅샷이 생성됩니다.

복제본 복구 체크포인트를 사용하여 성능 저하된 디스크에서만 스냅샷을 만들 수 있습니다. 기기가 완전히 복제되었을 때 복제본 복구 체크포인트에서 스냅샷을 만들려고 시도하면 다음 오류 메시지가 표시됩니다.

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

하이퍼디스크의 스냅샷 만들기

콘솔

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

    VM 인스턴스로 이동

  2. VM 인스턴스가 포함된 프로젝트를 선택합니다.

  3. 이름 열에서 하이퍼디스크가 백업된 VM의 이름을 클릭합니다.

  4. 스토리지추가 디스크에서 연결된 하이퍼디스크의 이름을 클릭합니다.

  5. 스냅샷 만들기를 클릭합니다.

  6. 이름에 스냅샷 목적을 식별하는 데 도움이 되는 고유한 이름을 입력합니다. 예를 들면 hyperdisk-data-snapshot과 같습니다.

  7. 유형에서 기본값은 장기 백업 및 재해 복구에 가장 적합한 일반 스냅샷입니다.

  8. 위치 섹션에서 스냅샷 스토리지 위치를 선택합니다.

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

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

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

  9. 만들기를 클릭합니다.

gcloud

스냅샷 설정에 따라 또는 선택한 대체 스토리지 위치를 사용해서 정의된 스토리지 위치 정책으로 스냅샷을 만들 수 있습니다. 자세한 내용은 스냅샷 스토리지 위치 선택을 참조하세요.

스냅샷 이름을 지정해야 합니다. 이름은 1~63자(영문 기준)여야 하며 RFC 1035를 준수해야 합니다.

  • 스냅샷 설정에 구성된 사전 정의되었거나 맞춤설정된 기본 위치에 스냅샷을 만들려면 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
    

    다음을 바꿉니다.

    • SNAPSHOT_NAME: 스냅샷의 이름입니다.
    • SOURCE_ZONE: 소스 디스크의 영역
    • SOURCE_DISK_NAME: 스냅샷을 만들려는 하이퍼디스크 볼륨의 이름입니다.
    • SNAPSHOT_TYPE: 스냅샷 유형(STANDARD 또는 ARCHIVE). 스냅샷 유형을 지정하지 않으면 STANDARD 스냅샷이 생성됩니다.
    • STORAGE_LOCATION: (선택사항) 스냅샷을 저장할 Cloud Storage 멀티 리전 또는 Cloud Storage 리전. 스토리지 위치는 하나만 지정할 수 있습니다.

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

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

REST

스냅샷 설정에 따라 또는 선택한 대체 스토리지 위치를 사용해서 정의된 스토리지 위치 정책으로 스냅샷을 만들 수 있습니다. 자세한 내용은 스냅샷 스토리지 위치 선택을 참조하세요.

스냅샷 이름을 지정해야 합니다. 이름은 1~63자(영문 기준)여야 하며 RFC 1035를 준수해야 합니다.

  • 스냅샷 설정에 구성된 사전 정의되었거나 맞춤설정된 기본 위치에 스냅샷을 만들려면 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"
    }
    
  • 또는 스냅샷 설정을 재정의하고 커스텀 스토리지 위치에 스냅샷을 만들려면 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: 스냅샷 유형(STANDARD 또는 ARCHIVE). 스냅샷 유형을 지정하지 않으면 STANDARD 스냅샷이 생성됩니다.
  • STORAGE_LOCATION: (선택사항) 스냅샷을 저장할 Cloud Storage 멀티 리전 또는 Cloud Storage 리전. 스토리지 위치는 하나만 지정할 수 있습니다.

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

다음 단계