Crear un disco persistente a partir de una fuente de datos


Puedes usar un disco persistente como un disco de arranque para una instancia de máquina virtual (VM) o como un disco de datos que conectes a una VM. Cuando creas un disco persistente, puedes crear un disco persistente en blanco o crear un disco desde un origen para que el disco nuevo contenga datos de ese origen.

Fuente de datos

Puedes crear discos persistentes a partir de las siguientes fuentes de datos:

Antes de comenzar

  • Configura la autenticación si aún no lo hiciste. La autenticación es el proceso mediante el cual se verifica tu identidad para acceder a los servicios y las API de Google Cloud. Para ejecutar un código o muestras desde un entorno de desarrollo local, puedes autenticarte en Compute Engine de la siguiente manera.

    Selecciona la pestaña para saber cómo planeas usar las muestras en esta página:

    Consola

    Cuando usas la consola de Google Cloud para acceder a los servicios y las APIs de Google Cloud, no necesitas configurar la autenticación.

    gcloud

    1. Instala Google Cloud CLI y, luego, inicializa la ejecución del siguiente comando:

      gcloud init
    2. Configura una región y una zona predeterminadas.

    Terraform

    Para usar las muestras de Terraform de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

    Go

    Para usar las muestras de Go de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

    Java

    Para usar las muestras de Java de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

    Python

    Para usar las muestras de Python de esta página desde un entorno de desarrollo local, instala e inicializa la CLI de gcloud y, luego, configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.

    1. Instala Google Cloud CLI.
    2. Para inicializar la CLI de gcloud, ejecuta el siguiente comando:

      gcloud init
    3. Crea credenciales de autenticación locales para tu Cuenta de Google:

      gcloud auth application-default login

    Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

    REST

    Para usar las muestras de la API de REST en esta página en un entorno de desarrollo local, debes usar las credenciales que proporcionas a la CLI de gcloud.

      Instala Google Cloud CLI y, luego, inicializa la ejecución del siguiente comando:

      gcloud init

Crea un clon de disco a partir de un disco existente

Puedes crear un clon de un disco persistente nuevo a partir de un disco persistente existente, incluso si el disco existente está conectado a una instancia de VM. Cuando clonas un disco, creas un disco nuevo que contiene todos los datos del disco de origen. Puedes modificar las propiedades en ese clon, como el tamaño. También puedes borrar el disco de origen sin que haya ningún riesgo de borrar el clon.

La capacidad de clonar discos es útil si deseas duplicar los datos de producción para depurar sin interrumpir la producción, duplicar discos mientras escalas horizontalmente tus VM y crear réplicas para la verificación de la copia de seguridad de la base de datos. También puedes clonar discos para transferir datos de discos que no son de arranque a un proyecto nuevo. En los casos en donde la protección de datos se requiera para lograr una resiliencia adicional, como las copias de seguridad y la recuperación ante desastres, recomendamos usar instantáneas estándar en lugar de clones de disco.

Si deseas capturar el estado de un disco en intervalos diferentes, pero no necesitas un disco nuevo que se pueda conectar cada vez, considera usar instantáneas.

Aunque no son adecuadas para la recuperación ante desastres, las instantáneas pueden ser más eficientes en cuanto al almacenamiento que crear clonaciones múltiples del mismo disco. Esto se debe a que las instantáneas son copias de seguridad incrementales.

Si necesitas duplicar un disco con rapidez, por ejemplo, para una depuración rápida, usa una clonación de disco.

Obtén más información sobre otras opciones de copia de seguridad de datos en Compute Engine.

Restricciones

  • El tipo de disco del clon debe coincidir con el del disco de origen.
  • No puedes crear un clon de un disco zonal a partir de un disco regional.
  • No puedes crear un clon de un disco zonal existente en una zona diferente.
  • El tamaño del clon debe ser al menos el tamaño del disco de origen. Si creas un clon mediante la consola de Google Cloud, no puedes especificar un tamaño de disco, y el clon se crea con el mismo tamaño que tiene el disco de origen.
  • Si usas una clave de encriptación proporcionada por el cliente o una clave de encriptación administrada por el cliente para encriptar el disco de origen, debes usar la misma clave a fin de encriptar el clon. Para obtener más información, consulta Crea un clon de un disco de origen encriptado.
  • Puedes crear, como máximo, una clonación de un disco de origen determinado o sus clonaciones cada 30 segundos.
  • Puedes tener, como máximo, 1,000 clones de disco simultáneos de un disco de origen determinado o sus clonaciones. Si superas este límite, se muestra un internalError. Sin embargo, si creas un clon de un disco y lo borras más tarde, el clon del disco borrado no se incluye en este límite.
  • Una vez que se clona un disco, las clonaciones posteriores de ese disco o sus clonaciones se cuentan en el límite de 1,000 clonaciones de disco simultáneas para el disco fuente original y se cuentan en el límite de crear como máximo una clonación cada 30 segundos.

Mensajes de error

Si excedes los límites de frecuencia de clonación, la solicitud falla con el siguiente mensaje de error:

RATE LIMIT: ERROR: (gcloud.compute.disks.create) Could not fetch resource:
 - Operation rate exceeded for resource RESOURCE. Too frequent operations from the source resource.

Crea un clon de un disco

Puedes clonar un disco existente en un disco nuevo mediante la consola de Google Cloud, Google Cloud CLI o la API de Compute Engine

Console

  1. En la consola de Google Cloud, ve a la página Discos.

    Ir a Discos

  2. En la lista de discos persistentes zonales, busca el disco que deseas clonar.

  3. Haz clic en el botón de menú en Acciones (Actions) y selecciona Clonar disco (Clone disk).

    Crear disco

  4. En el panel Clonar disco (Clone disk), especifica un nombre para el disco nuevo.

  5. En Propiedades, revisa otros detalles del disco nuevo.

  6. Haz clic en Guardar.

gcloud

En la CLI de gcloud, usa el comando disks create y especifica el --source-disk. En el siguiente ejemplo, se clona el disco de origen en un disco nuevo dentro de un proyecto diferente.

gcloud compute disks create projects/TARGET_PROJECT_ID/zones/ZONE/disks/TARGET_DISK_NAME \
    --description="cloned disk" \
    --source-disk=projects/SOURCE_PROJECT_ID/zones/ZONE/disks/SOURCE_DISK_NAME

Reemplaza lo siguiente:

  • TARGET_PROJECT_ID: Es el ID del proyecto del disco nuevo.
  • ZONE: Es la zona del disco de origen y nuevo.
  • TARGET_DISK_NAME: Es el nombre del disco nuevo.
  • SOURCE_PROJECT_ID: Es el ID del proyecto del disco de origen.
  • SOURCE_DISK_NAME: Es el nombre del disco de origen.

Terraform

Para crear una clonación de un disco, usa el recurso google_compute_disk.

resource "google_compute_disk" "default" {
  name  = "disk-name1"
  type  = "pd-ssd"
  zone  = "us-central1-a"
  image = "debian-11-bullseye-v20220719"
  labels = {
    environment = "dev"
  }
  physical_block_size_bytes = 4096
}

Si deseas obtener más información para aplicar o quitar una configuración de Terraform, consulta los comandos básicos de Terraform.

Go

Go

Antes de probar esta muestra, sigue las instrucciones de configuración de Go en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Go de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

// createDiskFromDisk creates a new disk with the contents of
// an already existitng disk. Type, and size and zone may differ.
func createDiskFromDisk(
	w io.Writer,
	projectID, zone, diskName, diskType, sourceDiskLink 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"
	// sourceDiskLink := "projects/your_project_id/global/disks/disk_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),
			SourceDisk: proto.String(sourceDiskLink),
			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

Antes de probar esta muestra, sigue las instrucciones de configuración de Java en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Java de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DisksClient;
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 CreateFromSource {

  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 project = "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.
    int diskSizeGb = 10;

    // A link to the disk you want to use as a source for the new disk.
    // This value uses the following format:
    // "projects/{project_name}/zones/{zone}/disks/{disk_name}"
    String diskLink = String.format("projects/%s/zones/%s/disks/%s", "PROJECT_NAME", "ZONE",
        "DISK_NAME");

    createDiskFromDisk(project, zone, diskName, diskType, diskSizeGb, diskLink);
  }

  // Creates a disk in a project in a given zone.
  public static void createDiskFromDisk(String project, String zone, String diskName,
      String diskType, int diskSizeGb, String diskLink)
      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()) {

      // Create the disk.
      Disk disk = Disk.newBuilder()
          .setZone(zone)
          .setSizeGb(diskSizeGb)
          .setSourceDisk(diskLink)
          .setType(diskType)
          .setName(diskName)
          .build();

      // Wait for the insert instance operation to complete.
      Operation operation = disksClient.insertAsync(project, zone, disk)
          .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Disk creation failed!");
        throw new Error(operation.getError().toString());
      }
      System.out.println(
          "Disk created from source. Operation Status: " + operation.getStatus());
    }
  }
}

Python

Python

Antes de probar esta muestra, sigue las instrucciones de configuración de Python en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Python de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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_disk(
    project_id: str,
    zone: str,
    disk_name: str,
    disk_type: str,
    disk_size_gb: int,
    disk_link: str,
) -> compute_v1.Disk:
    """
    Creates a disk in a project in a 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
        disk_link: a link to the disk you want to use as a source for the new disk.
            This value uses the following format: "projects/{project_name}/zones/{zone}/disks/{disk_name}"

    Returns:
        An attachable disk.
    """
    disk_client = compute_v1.DisksClient()
    disk = compute_v1.Disk()
    disk.zone = zone
    disk.size_gb = disk_size_gb
    disk.source_disk = disk_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)

REST

En la API, realiza una solicitud POST para el método compute.disks.insert. En el cuerpo de la solicitud, especifica los parámetros name y sourceDisk. El clon hereda todas las propiedades omitidas del disco de origen. En el siguiente ejemplo, se clona el disco de origen en un disco nuevo dentro de un proyecto diferente.

POST https://compute.googleapis.com/compute/v1/projects/TARGET_PROJECT_ID/zones/ZONE/disks

{
  "name": "TARGET_DISK_NAME"
  "sourceDisk": "projects/SOURCE_PROJECT_ID/zones/ZONE/disks/SOURCE_DISK_NAME"
}

Reemplaza lo siguiente:

  • TARGET_PROJECT_ID: Es el ID del proyecto del disco nuevo.
  • ZONE: Es la zona del disco de origen y nuevo.
  • TARGET_DISK_NAME: Es el nombre del disco nuevo.
  • SOURCE_PROJECT_ID: Es el ID del proyecto del disco de origen.
  • SOURCE_DISK_NAME: Es el nombre del disco de origen.

Crea un clon de un disco regional a partir un disco zonal

Si quieres crear un disco regional nuevo, clona un disco zonal existente. Para migrar un disco zonal a un disco regional, Google recomienda esta opción en lugar de crear una instantánea del disco zonal y restablecer la instantánea a un disco regional nuevo.

Restricciones

+ Para crear un clon del disco regional a partir de un disco zonal de origen, una de las zonas de réplica del clon debe coincidir con la zona del disco de origen.

  • Después de la creación, el clon del disco regional se puede usar en promedio en 3 minutos. Sin embargo, el disco puede tardar decenas de minutos en replicarse por completo y alcanzar un estado en el que el objetivo de punto de recuperación (RPO) se acerque a cero.

  • La velocidad a la que puedes clonar el espacio en el disco es limitada. Puedes crear, como máximo, 1 TB de disco clonado cada 15 minutos, con un límite de solicitudes de aumento de actividad de 257 TB.

Console

  1. En la consola de Google Cloud, ve a la página Discos.

    Ir a Discos

  2. En la lista de discos persistentes zonales, busca el disco que deseas clonar.

  3. Haz clic en el botón de menú en Acciones (Actions) y selecciona Clonar disco (Clone disk).

    Crear disco

  4. En el panel Clonar disco (Clone disk), especifica un nombre para el disco nuevo.

  5. En Ubicación, selecciona Regional y selecciona dos zonas de réplica para el disco regional nuevo.

  6. En Propiedades, revisa otros detalles del disco nuevo.

  7. Haz clic en Guardar.

gcloud

Crea un clon de un disco regional a partir de un disco zonal y proporciona el disco de origen y dos zonas de réplica para el disco regional nuevo mediante el siguiente comando de gcloud compute disks create. En el siguiente ejemplo, se supone que los discos de origen y de destino están en el mismo proyecto.

gcloud compute disks create TARGET_DISK_NAME \
  --description="zonal to regional cloned disk" \
  --region=REGION_1 \
  --source-disk=SOURCE_DISK_NAME \
  --source-disk-zone=REGION_1_ZONE_1 \
  --replica-zones=REGION_1_ZONE_1,REGION_1_ZONE_2 \
  --project=PROJECT_ID

Reemplaza lo siguiente:

  • TARGET_DISK_NAME: Es el nombre del disco regional nuevo.
  • REGION_1: Es la región del disco regional nuevo.
  • SOURCE_DISK_NAME: Es el nombre del disco zonal que se clonará.
  • REGION_1_ZONE_1: Es una de las dos zonas de réplica para el disco regional nuevo.
  • REGION_1_ZONE_2: Es la otra zona de réplica para el disco regional nuevo.
  • PROJECT_ID: es el ID del proyecto

Terraform

Si quieres crear una clonación de un disco regional a partir de un disco zonal, puedes crear de manera opcional una instantánea del disco zonal y, luego, clonar la instantánea. Para ello, usa los siguientes recursos:

resource "google_compute_region_disk" "regiondisk" {
  name                      = "region-disk-name"
  snapshot                  = google_compute_snapshot.snapdisk.id
  type                      = "pd-ssd"
  region                    = "us-central1"
  physical_block_size_bytes = 4096
  size                      = 11

  replica_zones = ["us-central1-a", "us-central1-f"]
}

Si deseas obtener más información para aplicar o quitar una configuración de Terraform, consulta los comandos básicos de Terraform.

Go

Go

Antes de probar esta muestra, sigue las instrucciones de configuración de Go en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Go de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

// createRegionalDiskFromDisk creates a new regional disk with the contents of
// an already existitng zonal disk. Disk type and size may differ.
func createRegionalDiskFromDisk(
	w io.Writer,
	projectID, region string, replicaZones []string,
	diskName, diskType, sourceDiskLink string,
	diskSizeGb int64,
) error {
	// projectID := "your_project_id"
	// region := "us-west3" // should match diskType below
	// diskName := "your_disk_name"
	// diskType := "regions/us-west3/diskTypes/pd-ssd"
	// sourceDiskLink := "projects/your_project_id/global/disks/disk_name"
	// diskSizeGb := 120

	// Exactly two replica zones must be specified
	replicaZoneURLs := []string{
		fmt.Sprintf("projects/%s/zones/%s", projectID, replicaZones[0]),
		fmt.Sprintf("projects/%s/zones/%s", projectID, replicaZones[1]),
	}

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

	req := &computepb.InsertRegionDiskRequest{
		Project: projectID,
		Region:  region,
		DiskResource: &computepb.Disk{
			Name:         proto.String(diskName),
			Region:       proto.String(region),
			Type:         proto.String(diskType),
			SourceDisk:   proto.String(sourceDiskLink),
			SizeGb:       proto.Int64(diskSizeGb),
			ReplicaZones: replicaZoneURLs,
		},
	}

	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

Antes de probar esta muestra, sigue las instrucciones de configuración de Java en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Java de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.RegionDisksClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RegionalCreateFromSource {

  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 project = "YOUR_PROJECT_ID";

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

    // An iterable collection of zone names in which you want to keep
    // the new disks' replicas. One of the replica zones of the clone must match
    // the zone of the source disk.
    List<String> replicaZones = new ArrayList<>();

    // 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_NAME");

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

    // A link to the disk you want to use as a source for the new disk.
    // This value uses the following format:
    // "projects/{project_name}/zones/{zone}/disks/{disk_name}"
    String diskLink = String.format("projects/%s/zones/%s/disks/%s", "PROJECT_NAME", "ZONE",
        "DISK_NAME");

    // 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}"
    String snapshotLink = String.format("projects/%s/global/snapshots/%s", "PROJECT_NAME",
        "SNAPSHOT_NAME");

    createRegionalDisk(project, region, replicaZones, diskName, diskType, diskSizeGb,
        Optional.ofNullable(diskLink), Optional.ofNullable(snapshotLink));
  }

  // Creates a regional disk from an existing zonal disk in a given project.
  public static void createRegionalDisk(
      String project, String region, List<String> replicaZones, String diskName, String diskType,
      int diskSizeGb, Optional<String> diskLink, Optional<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 `regionDisksClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (RegionDisksClient regionDisksClient = RegionDisksClient.create()) {

      Disk.Builder diskBuilder = Disk.newBuilder()
          .addAllReplicaZones(replicaZones)
          .setName(diskName)
          .setType(diskType)
          .setSizeGb(diskSizeGb)
          .setRegion(region);

      // Set source disk if diskLink is not empty.
      diskLink.ifPresent(diskBuilder::setSourceDisk);

      // Set source snapshot if the snapshot link is not empty.
      snapshotLink.ifPresent(diskBuilder::setSourceSnapshot);

      // Wait for the operation to complete.
      Operation operation = regionDisksClient.insertAsync(project, region, diskBuilder.build())
          .get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Disk creation failed!");
        throw new Error(operation.getError().toString());
      }
      System.out.println(
          "Regional disk created. Operation Status: " + operation.getStatus());
    }
  }
}

Python

Python

Antes de probar esta muestra, sigue las instrucciones de configuración de Python en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Python de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

from __future__ import annotations

from collections.abc import Iterable
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_regional_disk(
    project_id: str,
    region: str,
    replica_zones: Iterable[str],
    disk_name: str,
    disk_type: str,
    disk_size_gb: int,
    disk_link: str | None = None,
    snapshot_link: str | None = None,
) -> compute_v1.Disk:
    """
    Creates a regional disk from an existing zonal disk in a given project.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        region: name of the region in which you want to create the disk.
        replica_zones: an iterable collection of zone names in which you want to keep
            the new disks' replicas. One of the replica zones of the clone must match
            the zone of the source 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:
            "regions/{region}/diskTypes/(pd-standard|pd-ssd|pd-balanced|pd-extreme)".
            For example: "regions/us-west3/diskTypes/pd-ssd"
        disk_size_gb: size of the new disk in gigabytes
        disk_link: a link to the disk you want to use as a source for the new disk.
            This value uses the following format: "projects/{project_name}/zones/{zone}/disks/{disk_name}"
        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 attachable regional disk.
    """
    disk_client = compute_v1.RegionDisksClient()
    disk = compute_v1.Disk()
    disk.replica_zones = replica_zones
    disk.size_gb = disk_size_gb
    if disk_link:
        disk.source_disk = disk_link
    if snapshot_link:
        disk.source_snapshot = snapshot_link
    disk.type_ = disk_type
    disk.region = region
    disk.name = disk_name
    operation = disk_client.insert(
        project=project_id, region=region, disk_resource=disk
    )

    wait_for_extended_operation(operation, "disk creation")

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

REST

Proporciona el disco de origen y dos zonas de réplica para el disco regional nuevo. En el siguiente ejemplo, se supone que los discos de origen y de destino están en el mismo proyecto.

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION_1/disks

{
  "name": "TARGET_DISK_NAME"
  "sourceDisk": "projects/PROJECT_ID/zones/REGION_1_ZONE_1/disks/SOURCE_DISK_NAME"
  "replicaZone": "REGION_1_ZONE_1,REGION_1_ZONE_2"
}

Reemplaza lo siguiente:

  • PROJECT_ID: es el ID del proyecto
  • REGION_1: Es la región del disco regional nuevo.
  • TARGET_DISK_NAME: Es el nombre del disco regional nuevo.
  • REGION_1_ZONE_1: Es una de las dos zonas de réplica para el disco regional nuevo.
  • SOURCE_DISK_NAME: Es el nombre del disco zonal que se clonará.
  • REGION_1_ZONE_2: Es la otra zona de réplica para el disco regional nuevo.

Crea un clon de un disco de origen encriptado

Si usas una clave de encriptación proporcionada por el cliente a fin de encriptar el disco de origen, también debes usar la misma clave para encriptar el clon.

Console

  1. En la consola de Google Cloud, ve a la página Discos.

    Ir a Discos

  2. En la lista de discos persistentes zonales, busca el disco que deseas clonar.

  3. Haz clic en el botón de menú en Acciones (Actions) y selecciona Clonar disco (Clone disk).

    Crear disco

  4. En el panel Clonar disco (Clone disk), especifica un nombre para el disco nuevo.

  5. Proporciona la clave de encriptación del disco de origen en Desencriptación y encriptación.

  6. En Propiedades, revisa otros detalles del disco nuevo.

  7. Haz clic en Guardar.

gcloud

Proporciona la clave de encriptación del disco de origen mediante la marca --csek-key-file cuando crees el clon del disco. Si usas una clave unida con RSA, utiliza el componente gcloud beta:

gcloud beta compute disks create projects/TARGET_PROJECT_ID/zones/ZONE/disks/TARGET_DISK_NAME \
  --description="cloned disk" \
  --source-disk=projects/SOURCE_PROJECT_ID/zones/ZONE/disks/SOURCE_DISK_NAME \
  --csek-key-file example-key-file.json

Reemplaza lo siguiente:

  • TARGET_PROJECT_ID: Es el ID del proyecto del disco nuevo.
  • ZONE: Es la zona del disco de origen y nuevo.
  • TARGET_DISK_NAME: Es el nombre del disco nuevo.
  • SOURCE_PROJECT_ID: Es el ID del proyecto del disco de origen.
  • SOURCE_DISK_NAME: Es el nombre del disco de origen.

Go

Go

Antes de probar esta muestra, sigue las instrucciones de configuración de Go en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Go de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

// Creates a zonal non-boot persistent disk in a project with the copy of data from an existing disk.
// The encryption key must be the same for the source disk and the new disk.
// The disk type and size may differ.
func createDiskFromCustomerEncryptedDisk(
	w io.Writer,
	projectID, zone, diskName, diskType string,
	diskSizeGb int64,
	diskLink, encryptionKey string,
) error {
	// projectID := "your_project_id"
	// zone := "us-west3-b" // should match diskType below
	// diskName := "your_disk_name"
	// diskType := "zones/us-west3/diskTypes/pd-ssd"
	// diskSizeGb := 120
	// diskLink := "projects/your_project_id/global/disks/disk_name"
	// encryptionKey := "SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=" // in base64

	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),
			SizeGb:     proto.Int64(diskSizeGb),
			SourceDisk: proto.String(diskLink),
			DiskEncryptionKey: &computepb.CustomerEncryptionKey{
				RawKey: &encryptionKey,
			},
		},
	}

	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

Antes de probar esta muestra, sigue las instrucciones de configuración de Java en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Java de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.cloud.compute.v1.CustomerEncryptionKey;
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 com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CloneEncryptedDisk {

  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 project = "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.
    int diskSizeGb = 10;

    // A link to the disk you want to use as a source for the new disk.
    // This value uses the following format:
    // "projects/{project_name}/zones/{zone}/disks/{disk_name}"
    String diskLink = String.format("projects/%s/zones/%s/disks/%s", "PROJECT_NAME", "ZONE",
        "DISK_NAME");

    // Customer-supplied encryption key used for encrypting data in the source disk.
    // The data will be encrypted with the same key in the new disk.
    byte[] encryptionKey = null;

    createDiskFromCustomerEncryptedKey(project, zone, diskName, diskType, diskSizeGb, diskLink,
        encryptionKey);
  }

  // Creates a zonal non-boot persistent disk in a project with the copy of data
  // from an existing disk.
  // The encryption key must be the same for the source disk and the new disk.
  public static void createDiskFromCustomerEncryptedKey(String project, String zone,
      String diskName, String diskType, int diskSizeGb, String diskLink, byte[] encryptionKey)
      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()) {

      // Create a disk and set the encryption key.
      Disk disk = Disk.newBuilder()
          .setZone(zone)
          .setName(diskName)
          .setType(diskType)
          .setSizeGb(diskSizeGb)
          .setSourceDisk(diskLink)
          .setDiskEncryptionKey(CustomerEncryptionKey
              .newBuilder()
              .setRawKeyBytes(ByteString.copyFrom(encryptionKey))
              .build())
          .build();

      // Wait for the insert disk operation to complete.
      Operation operation = disksClient.insertAsync(
          InsertDiskRequest.newBuilder()
              .setProject(project)
              .setZone(zone)
              .setDiskResource(disk)
              .build()).get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Disk creation failed!");
        throw new Error(operation.getError().toString());
      }
      System.out.println(
          "Disk cloned with customer encryption key. Operation Status: " + operation.getStatus());
    }
  }
}

Python

Python

Antes de probar esta muestra, sigue las instrucciones de configuración de Python en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Python de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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_customer_encrypted_disk(
    project_id: str,
    zone: str,
    disk_name: str,
    disk_type: str,
    disk_size_gb: int,
    disk_link: str,
    encryption_key: bytes,
) -> compute_v1.Disk:
    """
    Creates a zonal non-boot persistent disk in a project with the copy of data from an existing disk.

    The encryption key must be the same for the source disk and the new disk.

    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
        disk_link: a link to the disk you want to use as a source for the new disk.
            This value uses the following format: "projects/{project_name}/zones/{zone}/disks/{disk_name}"
        encryption_key: customer-supplied encryption key used for encrypting
            data in the source disk. The data will be encrypted with the same key
            in the new disk.

    Returns:
        An attachable copy of an existing disk.
    """
    disk_client = compute_v1.DisksClient()
    disk = compute_v1.Disk()
    disk.zone = zone
    disk.size_gb = disk_size_gb
    disk.source_disk = disk_link
    disk.type_ = disk_type
    disk.name = disk_name
    disk.disk_encryption_key = compute_v1.CustomerEncryptionKey()
    disk.disk_encryption_key.raw_key = encryption_key
    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)

REST

Proporciona la clave de encriptación del disco de origen con la propiedad diskEncryptionKey.

POST https://compute.googleapis.com/compute/beta/projects/TARGET_PROJECT_ID/zones/ZONE/disks

{
  "name": "TARGET_DISK_NAME"
  "sourceDisk": "projects/SOURCE_PROJECT_ID/zones/ZONE/disks/SOURCE_DISK_NAME"
  "diskEncryptionKey": {
    "rsaEncryptedKey": "ieCx/NcW06PcT7Ep1X6LUTc/hLvUDYyzSZPPVCVPTVEohpeHASqC8uw5TzyO9U+Fka9JFHz0mBibXUInrC/jEk014kCK/NPjYgEMOyssZ4ZINPKxlUh2zn1bV+MCaTICrdmuSBTWlUUiFoDD6PYznLwh8ZNdaheCeZ8ewEXgFQ8V+sDroLaN3Xs3MDTXQEMMoNUXMCZEIpg9Vtp9x2oeQ5lAbtt7bYAAHf5l+gJWw3sUfs0/Glw5fpdjT8Uggrr+RMZezGrltJEF293rvTIjWOEB3z5OHyHwQkvdrPDFcTqsLfh+8Hr8g+mf+7zVPEC8nEbqpdl3GPv3A7AwpFp7MA=="
  },
}

Reemplaza lo siguiente:

  • TARGET_PROJECT_ID: Es el ID del proyecto del disco nuevo.
  • ZONE: Es la zona del disco de origen y nuevo.
  • TARGET_DISK_NAME: Es el nombre del disco nuevo.
  • SOURCE_PROJECT_ID: Es el ID del proyecto del disco de origen.
  • SOURCE_DISK_NAME: Es el nombre del disco de origen.

Si usas una clave de encriptación administrada por el cliente para encriptar tu disco de origen, debes usar la misma clave a fin de encriptar el clon.

Console

Compute Engine encripta de forma automática el clon mediante la clave de encriptación del disco de origen.

gcloud

Proporciona la clave para el disco de origen con la marca --kms-key cuando crees el clon del disco. Si usas una clave unida con RSA, utiliza el componente gcloud beta:

gcloud beta compute disks create projects/TARGET_PROJECT_ID/zones/ZONE/disks/TARGET_DISK_NAME \
  --description="cloned disk" \
  --source-disk=projects/SOURCE_PROJECT_ID/zones/ZONE/disks/SOURCE_DISK_NAME \
  --kms-key projects/KMS_PROJECT_ID/locations/REGION/keyRings/KEY_RING/cryptoKeys/KEY

Reemplaza lo siguiente:

  • TARGET_PROJECT_ID: Es el ID del proyecto del disco nuevo.
  • ZONE: Es la zona del disco de origen y nuevo.
  • TARGET_DISK_NAME: Es el nombre del disco nuevo.
  • SOURCE_PROJECT_ID: Es el ID del proyecto del disco de origen.
  • SOURCE_DISK_NAME: Es el nombre del disco de origen.
  • KMS_PROJECT_ID: Es el ID del proyecto de la clave de encriptación.
  • REGION: Es la región de la clave de encriptación.
  • KEY_RING: Es el llavero de claves de la clave de encriptación.
  • KEY: Es el nombre de la clave de encriptación.

Go

Go

Antes de probar esta muestra, sigue las instrucciones de configuración de Go en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Go de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

// Creates a zonal non-boot persistent disk in a project with the copy of data from an existing disk.
// The encryption key must be the same for the source disk and the new disk.
// The disk type and size may differ.
func createDiskFromKmsEncryptedDisk(
	w io.Writer,
	projectID, zone, diskName, diskType string,
	diskSizeGb int64,
	diskLink, kmsKeyLink string,
) error {
	// projectID := "your_project_id"
	// zone := "us-west3-b" // should match diskType below
	// diskName := "your_disk_name"
	// diskType := "zones/us-west3/diskTypes/pd-ssd"
	// diskSizeGb := 120
	// diskLink := "projects/your_project_id/global/disks/disk_name"
	// kmsKeyLink := "projects/your_kms_project_id/locations/us-central1/keyRings/your_key_ring/cryptoKeys/your_key"

	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),
			SizeGb:     proto.Int64(diskSizeGb),
			SourceDisk: proto.String(diskLink),
			DiskEncryptionKey: &computepb.CustomerEncryptionKey{
				KmsKeyName: &kmsKeyLink,
			},
		},
	}

	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

Antes de probar esta muestra, sigue las instrucciones de configuración de Java en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Java de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.cloud.compute.v1.CustomerEncryptionKey;
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 CloneEncryptedDiskManagedKey {

  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 project = "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.
    int diskSizeGb = 10;

    // A link to the disk you want to use as a source for the new disk.
    // This value uses the following format:
    // "projects/{project_name}/zones/{zone}/disks/{disk_name}"
    String diskLink = String.format("projects/%s/zones/%s/disks/%s", "PROJECT_NAME", "ZONE",
        "DISK_NAME");

    // URL of the key from KMS. The key might be from another project, as
    // long as you have access to it. The data will be encrypted with the same key
    // in the new disk. This value uses following format:
    // "projects/{kms_project_id}/locations/{region}/keyRings/{key_ring}/cryptoKeys/{key}"
    String kmsKeyName = "kms-key-name";

    createDiskFromKmsEncryptedDisk(project, zone, diskName, diskType, diskSizeGb, diskLink,
        kmsKeyName);
  }

  // Creates a zonal non-boot disk in a project with the copy of data from an existing disk.
  // The encryption key must be the same for the source disk and the new disk.
  public static void createDiskFromKmsEncryptedDisk(String project, String zone, String diskName,
      String diskType, int diskSizeGb, String diskLink, String kmsKeyName)
      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()) {

      // Create a disk and set the KMS encryption key name.
      Disk disk = Disk.newBuilder()
          .setZone(zone)
          .setName(diskName)
          .setType(diskType)
          .setSizeGb(diskSizeGb)
          .setSourceDisk(diskLink)
          .setDiskEncryptionKey(CustomerEncryptionKey.newBuilder()
              .setKmsKeyName(kmsKeyName)
              .build())
          .build();

      // Wait for the insert disk operation to complete.
      Operation operation = disksClient.insertAsync(
          InsertDiskRequest.newBuilder()
              .setProject(project)
              .setZone(zone)
              .setDiskResource(disk)
              .build()).get(3, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.println("Disk creation failed!");
        throw new Error(operation.getError().toString());
      }
      System.out.println(
          "Disk cloned with KMS encryption key. Operation Status: " + operation.getStatus());
    }
  }
}

Python

Python

Antes de probar esta muestra, sigue las instrucciones de configuración de Python en la Guía de inicio rápido de Compute Engine: Usa las bibliotecas cliente. Si quieres obtener más información, consulta la documentación de referencia de la API de Python de Compute Engine.

Para autenticarte en Compute Engine, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

from __future__ import annotations

import sys
from typing import Any

from google.api_core.exceptions import BadRequest
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_kms_encrypted_disk(
    project_id: str,
    zone: str,
    disk_name: str,
    disk_type: str,
    disk_size_gb: int,
    disk_link: str,
    kms_key_name: str,
) -> compute_v1.Disk:
    """
    Creates a zonal non-boot disk in a project with the copy of data from an existing disk.

    The encryption key must be the same for the source disk and the new disk.

    To run this method, the service-<project_id>@compute-system.iam.gserviceaccount.com
    service account needs to have the cloudkms.cryptoKeyEncrypterDecrypter role,
    as described in documentation:
    https://cloud.google.com/compute/docs/disks/customer-managed-encryption#before_you_begin

    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
        disk_link: a link to the disk you want to use as a source for the new disk.
            This value uses the following format: "projects/{project_name}/zones/{zone}/disks/{disk_name}"
        kms_key_name: URL of the key from KMS. The key might be from another project, as
            long as you have access to it. The data will be encrypted with the same key
            in the new disk. This value uses following format:
            "projects/{kms_project_id}/locations/{region}/keyRings/{key_ring}/cryptoKeys/{key}"

    Returns:
        An attachable copy of an existing disk.
    """
    disk_client = compute_v1.DisksClient()
    disk = compute_v1.Disk()
    disk.zone = zone
    disk.size_gb = disk_size_gb
    disk.source_disk = disk_link
    disk.type_ = disk_type
    disk.name = disk_name
    disk.disk_encryption_key = compute_v1.CustomerEncryptionKey()
    disk.disk_encryption_key.kms_key_name = kms_key_name
    try:
        operation = disk_client.insert(
            project=project_id, zone=zone, disk_resource=disk
        )
    except BadRequest as err:
        if "Permission 'cloudkms.cryptoKeyVersions.useToEncrypt' denied" in err.message:
            print(
                f"Please provide the cloudkms.cryptoKeyEncrypterDecrypter role to"
                f"service-{project_id}@compute-system.iam.gserviceaccount.com"
            )
        raise err

    wait_for_extended_operation(operation, "disk creation")

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

REST

Proporciona la clave para el disco de origen con la propiedad kmsKeyName cuando crees el clon del disco.

POST https://compute.googleapis.com/compute/beta/projects/TARGET_PROJECT_ID/zones/ZONE/disks

{
  "name": "TARGET_DISK_NAME"
  "sourceDisk": "projects/SOURCE_PROJECT_ID/zones/ZONE/disks/SOURCE_DISK_NAME"
  "diskEncryptionKey": {
    "kmsKeyName": "projects/KMS_PROJECT_ID/locations/REGION/keyRings/KEY_RING/cryptoKeys/KEY"
  },
}

Reemplaza lo siguiente:

  • TARGET_DISK_NAME: Es el nombre del disco nuevo.
  • SOURCE_PROJECT_ID: Es el ID del proyecto del disco de origen.
  • ZONE: Es la zona del disco de origen y nuevo.
  • SOURCE_DISK_NAME: Es el nombre del disco de origen.
  • KMS_PROJECT_ID: Es el ID del proyecto de la clave de encriptación.
  • REGION: Es la región de la clave de encriptación.
  • KEY_RING: Es el llavero de claves de la clave de encriptación.
  • KEY: Es el nombre de la clave de encriptación.

¿Qué sigue?