Restaurar desde una instantánea


Un disco es un disco de arranque que se usa para iniciar y ejecutar el sistema operativo en una instancia informática o un disco que no es de arranque y que una instancia usa solo para almacenamiento de datos.

Puede utilizar instantáneas para realizar copias de seguridad y restaurar datos del disco de las siguientes maneras:

Antes de comenzar

Roles requeridos

Para obtener los permisos que necesita restaurar a partir de una instantánea, solicite a su administrador que le otorgue el rol de IAM de Administrador de instancia informática (v1) ( roles/compute.instanceAdmin.v1 ) en el proyecto. Para obtener más información sobre cómo otorgar roles, consulte Administrar el acceso a proyectos, carpetas y organizaciones .

Esta función predefinida contiene los permisos necesarios para restaurar desde una instantánea. Para ver los permisos exactos que se requieren, expanda la sección Permisos requeridos :

Permisos requeridos

Se requieren los siguientes permisos para restaurar desde una instantánea:

  • Para crear un disco a partir de una instantánea de ámbito global (predeterminado):
    • compute.disks.create en el proyecto.
    • compute.instances.attachDisk en la instancia
    • compute.disks.use en el disco para adjuntar
    • compute.snapshots.useReadOnly , compute.snapshots.create o compute.disks.createSnapshot en el proyecto.
  • ( Vista previa ) Para crear un disco a partir de una instantánea de ámbito regional:
    • compute.disks.create en el proyecto.
    • compute.instances.attachDisk en la instancia
    • compute.disks.use en el disco para adjuntar
    • compute.snapshots.useReadOnly en el proyecto
  • Para crear una instancia a partir de una instantánea de un disco de arranque y de un disco que no sea de arranque, necesita como mínimo los siguientes permisos:
    • compute.instances.create en el proyecto.
    • compute.snapshots.useReadOnly en la instantánea
    • compute.disks.create en el proyecto.
    • compute.disks.use en el disco
    • compute.instances.attachDisk en la instancia

Es posible que también pueda obtener estos permisos con roles personalizados u otros roles predefinidos .

Limitaciones

  • El nuevo disco debe tener al menos el mismo tamaño que el disco de origen original de la instantánea. Si crea un disco que es más grande que el disco de origen original para la instantánea, debe cambiar el tamaño del sistema de archivos en ese disco para incluir el espacio adicional en el disco. Dependiendo de su sistema operativo y tipo de sistema de archivos, es posible que necesite utilizar una herramienta de cambio de tamaño del sistema de archivos diferente. Para obtener más información, consulte la documentación de su sistema operativo.

  • Puede crear nuevos discos zonales o regionales a partir de una instantánea determinada como máximo una vez cada diez minutos. Si desea emitir una ráfaga de solicitudes para tomar instantáneas de sus discos, puede emitir como máximo 6 solicitudes en 60 minutos. Este límite no se aplica al crear discos regionales a partir de una instantánea. Para obtener más información, consulte Límites de frecuencia de instantáneas .

Cree un disco a partir de una instantánea y, opcionalmente, adjuntelo a una instancia

Si realizó una copia de seguridad de un disco de arranque o de otro disco con una instantánea, puede crear un disco nuevo basado en la instantánea.

Consola

  1. En la consola de Google Cloud, vaya a la página Instantáneas .

    Ir a instantáneas

  2. Busque el nombre de la instantánea que desea restaurar.

  3. Vaya a la página Discos .

    Ir a la página de Discos

  4. Haga clic en Crear nuevo disco .

  5. Especifique los siguientes parámetros de configuración:

    • Un nombre para el disco.
    • Un tipo para el disco.
    • Opcionalmente, puede anular la selección de zona y región predeterminada. Puede seleccionar cualquier región y zona, independientemente de la ubicación de almacenamiento de la instantánea de origen.
  6. En Tipo de fuente , haga clic en Instantánea .

  7. Seleccione el nombre de la instantánea para restaurar.

  8. Seleccione el tamaño del nuevo disco, en gigabytes. Este número debe ser igual o mayor que el disco de origen original de la instantánea.

  9. Haga clic en Crear para crear el disco.

Opcionalmente, puede adjuntar un disco que no sea de arranque a una instancia .

nube de gcloud

  1. Usa el comando gcloud compute snapshots list para buscar el nombre de la instantánea que deseas restaurar:

    gcloud compute snapshots list
    
  2. Usa el comando gcloud compute snapshots describe para encontrar el tamaño de la instantánea que deseas restaurar:

    gcloud compute snapshots describe SNAPSHOT_NAME
    

    Reemplace SNAPSHOT_NAME con el nombre de la instantánea que se está restaurando.

  3. Usa el comando gcloud compute disks create para crear un nuevo disco regional o zonal a partir de tu instantánea. Puede incluir el indicador --type para especificar el tipo de disco que se creará.

    • Para crear un disco zonal a partir de una instantánea de ámbito global:
    gcloud compute disks create DISK_NAME \
        --zone=ZONE \
        --size=DISK_SIZE \
        --source-snapshot=SNAPSHOT_NAME \
        --type=DISK_TYPE
    
    • ( Vista previa ) Para crear un disco zonal a partir de una instantánea de ámbito regional:
    gcloud beta compute disks create DISK_NAME \
        --zone=ZONE \
        --source-snapshot=SNAPSHOT_NAME \
        --source-snapshot-region=SOURCE_REGION \
        --type=DISK_TYPE
    
    • Para crear un disco regional a partir de una instantánea de ámbito global:
    gcloud beta compute disks create DISK_NAME \
        --size=DISK_SIZE \
        --source-snapshot=SNAPSHOT_NAME \
        --type=DISK_TYPE \
        --region=REGION \
        --replica-zones=ZONE1,ZONE2
    
    • ( Vista previa ) Para crear un disco regional a partir de una instantánea de ámbito regional:
    gcloud beta compute disks create DISK_NAME \
        --size=DISK_SIZE \
        --source-snapshot=SNAPSHOT_NAME \
        --source-snapshot-region=SOURCE_REGION \
        --type=DISK_TYPE \
        --region=REGION \
        --replica-zones=ZONE1,ZONE2
    

    Reemplace lo siguiente:

    • DISK_NAME : el nombre del nuevo disco
    • DISK_SIZE : el tamaño del nuevo disco, en gibibytes (GiB). Este número debe ser igual o mayor que el disco de origen original de la instantánea.
    • SNAPSHOT_NAME : el nombre de la instantánea que se está restaurando
    • DISK_TYPE : el tipo de disco, por ejemplo,pd-ssd , hyperdisk-throughput o hyperdisk-balanced-high-availability
    • REGION : la región en la que residirá el disco regional, por ejemplo: europe-west1
    • SOURCE_REGION : la región a la que pertenece la instantánea de origen
    • ZONE : la zona donde residirá el nuevo disco
    • ZONE1,ZONE2 : las zonas dentro de la región donde se encuentran las dos réplicas de disco, por ejemplo: europe-west1-b y europe-west1-c
  4. Opcional: conecta el nuevo disco a una instancia existente mediante el comando gcloud compute instances attach-disk :

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

    Reemplace lo siguiente:

    • INSTANCE_NAME : el nombre de la instancia
    • DISK_NAME : el nombre del disco creado a partir de tu instantánea

Ir

Go

Antes de probar este ejemplo, sigue las instrucciones de configuración Go en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API Go de Compute Engine .

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar la autenticación para un entorno de desarrollo local .

import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

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

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

	return nil
}

Java

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración Java en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API Java de Compute Engine .

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar 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.InsertDiskRequest;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateDiskFromSnapshot {

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

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

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

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

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

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

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

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

  // Creates a new disk in a project in given zone, using a snapshot.
  public static void createDiskFromSnapshot(String projectId, String zone, String diskName,
      String diskType, long diskSizeGb, String snapshotLink)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `disksClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (DisksClient disksClient = DisksClient.create()) {

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

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

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

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

Nodo.js

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración de Node.js en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API de Compute Engine Node.js

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar la autenticación para un entorno de desarrollo local .

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

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

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

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

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

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

createDiskFromSnapshot();

Pitón

Python

Antes de probar este ejemplo, sigue las instrucciones de configuración Python en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API Python de Compute Engine .

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar 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_snapshot(
    project_id: str,
    zone: str,
    disk_name: str,
    disk_type: str,
    disk_size_gb: int,
    snapshot_link: str,
) -> compute_v1.Disk:
    """
    Creates a new disk in a project in given zone.

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

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

    wait_for_extended_operation(operation, "disk creation")

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

DESCANSAR

  1. Cree una solicitud GET para snapshots.list para mostrar la lista de instantáneas en su proyecto.

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

    Reemplace PROJECT_ID con su ID de proyecto.

  2. Construya una solicitud POST para crear un disco zonal o un disco regional usando el método disks.insert respectivo:

    Incluya las propiedades name , sizeGb y type . Para restaurar un disco usando una instantánea, debe incluir la propiedad sourceSnapshot .

    • Para crear un disco zonal a partir de una instantánea de ámbito global:
    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/disks
    {
      "name": "DISK_NAME",
      "sourceSnapshot": "SNAPSHOT_NAME",
      "sizeGb": "DISK_SIZE",
      "type": "zones/ZONE/diskTypes/DISK_TYPE"
    }
    
    • ( Vista previa ) Para crear un disco zonal a partir de una instantánea de ámbito regional:
    POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/zones/ZONE/disks
    {
      "name": "DISK_NAME",
      "sourceSnapshot": "projects/PROJECT_ID/regions/SOURCE_REGION/snapshots/SNAPSHOT_NAME",
      "sizeGb": "DISK_SIZE",
      "type": "projects/PROJECT_ID/zones/ZONE/diskTypes/DISK_TYPE",
      "zone": "projects/PROJECT_ID/zones/ZONE"
    }
    
    • Para crear un disco regional a partir de una instantánea de ámbito global:
    POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/regions/REGION/disks
    {
      "name": "DISK_NAME",
      "sourceSnapshot": "SNAPSHOT_NAME",
      "region": "projects/PROJECT_ID/regions/REGION",
      "replicaZones": [
         "projects/PROJECT_ID/zones/ZONE1",
         "projects/PROJECT_ID/zones/ZONE2"
      ],
      "sizeGb": "DISK_SIZE",
      "type": "zones/ZONE/diskTypes/DISK_TYPE"
    }
    
    • ( Vista previa ) Para crear un disco regional a partir de una instantánea de ámbito regional:
    POST https://compute.googleapis.com/compute/beta/projects/PROJECT_ID/regions/REGION/disks
    {
      "name": "DISK_NAME",
      "sourceSnapshot": "projects/PROJECT_ID/regions/SOURCE_REGION/snapshots/SNAPSHOT_NAME",
      "replicaZones": [
         "projects/PROJECT_ID/zones/ZONE1",
         "projects/PROJECT_ID/zones/ZONE2"
      ],
      "sizeGb": "DISK_SIZE",
      "type": "projects/PROJECT_ID/regions/REGION/diskTypes/DISK_TYPE"
    }
    

    Reemplace lo siguiente:

    • PROJECT_ID : ID de tu proyecto
    • ZONE : la zona donde se encuentran su instancia y su nuevo disco
    • DISK_NAME : el nombre del nuevo disco
    • SNAPSHOT_NAME : la instantánea de origen del disco que estás restaurando
    • REGION : la región en la que residirá el disco regional, por ejemplo: europe-west1
    • SOURCE_REGION : la región a la que pertenece la instantánea de origen
    • ZONE1 , ZONE2 : las zonas donde se deben ubicar las réplicas del nuevo disco
    • DISK_SIZE : el tamaño del nuevo disco, en gibibytes (GiB). Este número debe ser igual o mayor que el disco de origen original de la instantánea.
    • DISK_TYPE : URL completa o parcial para el tipo de disco, por ejemplo,PROJECT_ID /zones/ ZONE /diskTypes/pd-ssd ,PROJECT_ID /zones/ ZONE /diskTypes/hyperdisk-balanced o PROJECT_ID /zones/ ZONE /diskTypes/hyperdisk-balanced-high-availability
  3. Opcional. Adjunte el nuevo disco a una instancia existente.

    Cree una solicitud POST para el método instances.attachDisk e incluya la URL del disco que acaba de crear a partir de su instantánea.

    Para discos zonales:

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

    Para discos regionales:

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

    Reemplace lo siguiente:

    • PROJECT_ID : ID de tu proyecto
    • ZONE : la zona donde se encuentran su instancia y su nuevo disco
    • REGION : la región donde se encuentra el disco regional. Debe ser la misma región en la que se encuentra la instancia informática.
    • INSTANCE_NAME : el nombre de la instancia donde estás agregando el nuevo disco
    • DISK_NAME : el nombre del nuevo disco

Después de crear y adjuntar un nuevo disco a una instancia, debe montar el disco para que el sistema operativo pueda utilizar el espacio de almacenamiento disponible.

Crear una instancia a partir de discos existentes

Puede crear discos de arranque y discos de datos a partir de instantáneas y luego adjuntar estos discos a una nueva instancia informática.

Ir

Go

Antes de probar este ejemplo, sigue las instrucciones de configuración Go en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API Go de Compute Engine .

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar la autenticación para un entorno de desarrollo local .

import (
	"context"
	"fmt"
	"io"

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

// createWithExistingDisks create a new VM instance using selected disks.
// The first disk in diskNames will be used as boot disk.
func createWithExistingDisks(
	w io.Writer,
	projectID, zone, instanceName string,
	diskNames []string,
) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// diskNames := []string{"boot_disk", "disk1", "disk2"}

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

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

	disks := [](*computepb.Disk){}

	for _, diskName := range diskNames {
		reqDisk := &computepb.GetDiskRequest{
			Project: projectID,
			Zone:    zone,
			Disk:    diskName,
		}

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

		disks = append(disks, disk)
	}

	attachedDisks := [](*computepb.AttachedDisk){}

	for _, disk := range disks {
		attachedDisk := &computepb.AttachedDisk{
			Source: proto.String(disk.GetSelfLink()),
		}
		attachedDisks = append(attachedDisks, attachedDisk)
	}

	attachedDisks[0].Boot = proto.Bool(true)

	instanceResource := &computepb.Instance{
		Name:        proto.String(instanceName),
		Disks:       attachedDisks,
		MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/n1-standard-1", zone)),
		NetworkInterfaces: []*computepb.NetworkInterface{
			{
				Name: proto.String("global/networks/default"),
			},
		},
	}

	req := &computepb.InsertInstanceRequest{
		Project:          projectID,
		Zone:             zone,
		InstanceResource: instanceResource,
	}

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

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

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

	return nil
}

Java

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración Java en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API Java de Compute Engine .

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar la autenticación para un entorno de desarrollo local .


import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.Disk;
import com.google.cloud.compute.v1.DisksClient;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateInstanceWithExistingDisks {

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

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

    // Name of the zone to create the instance in. For example: "us-west3-b"
    String zone = "europe-central2-b";

    // Name of the new virtual machine (VM) instance.
    String instanceName = "YOUR_INSTANCE_NAME";

    // Array of disk names to be attached to the new virtual machine.
    // First disk in this list will be used as the boot disk.
    List<String> diskNames = List.of("your-boot-disk", "another-disk1", "another-disk2");

    createInstanceWithExistingDisks(projectId, zone, instanceName, diskNames);
  }

  // Create a new VM instance using the selected disks.
  // The first disk in diskNames will be used as the boot disk.
  public static void createInstanceWithExistingDisks(String projectId, String zone,
      String instanceName, List<String> diskNames)
      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 `instancesClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (InstancesClient instancesClient = InstancesClient.create();
        DisksClient disksClient = DisksClient.create()) {

      if (diskNames.size() == 0) {
        throw new Error("At least one disk should be provided");
      }

      // Create the list of attached disks to be used in instance creation.
      List<AttachedDisk> attachedDisks = new ArrayList<>();
      for (int i = 0; i < diskNames.size(); i++) {
        String diskName = diskNames.get(i);
        Disk disk = disksClient.get(projectId, zone, diskName);
        AttachedDisk attDisk = null;

        if (i == 0) {
          // Make the first disk in the list as the boot disk.
          attDisk = AttachedDisk.newBuilder()
              .setSource(disk.getSelfLink())
              .setBoot(true)
              .build();
        } else {
          attDisk = AttachedDisk.newBuilder()
              .setSource(disk.getSelfLink())
              .build();
        }
        attachedDisks.add(attDisk);
      }

      // Create the instance.
      Instance instance = Instance.newBuilder()
          .setName(instanceName)
          // Add the attached disks to the instance.
          .addAllDisks(attachedDisks)
          .setMachineType(String.format("zones/%s/machineTypes/n1-standard-1", zone))
          .addNetworkInterfaces(
              NetworkInterface.newBuilder().setName("global/networks/default").build())
          .build();

      // Create the insert instance request.
      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setInstanceResource(instance)
          .build();

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

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

    }
  }
}

Nodo.js

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración de Node.js en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API de Compute Engine Node.js

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar la autenticación para un entorno de desarrollo local .

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'europe-central2-b';
// const instanceName = 'YOUR_INSTANCE_NAME';
// const diskNames = ['boot_disk', 'disk1', 'disk2'];

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

async function createWithExistingDisks() {
  const instancesClient = new compute.InstancesClient();
  const disksClient = new compute.DisksClient();

  if (diskNames.length < 1) {
    throw new Error('At least one disk should be provided');
  }

  const disks = [];
  for (const diskName of diskNames) {
    const [disk] = await disksClient.get({
      project: projectId,
      zone,
      disk: diskName,
    });
    disks.push(disk);
  }

  const attachedDisks = [];

  for (const disk of disks) {
    attachedDisks.push({
      source: disk.selfLink,
    });
  }

  attachedDisks[0].boot = true;

  const [response] = await instancesClient.insert({
    project: projectId,
    zone,
    instanceResource: {
      name: instanceName,
      disks: attachedDisks,
      machineType: `zones/${zone}/machineTypes/n1-standard-1`,
      networkInterfaces: [
        {
          name: 'global/networks/default',
        },
      ],
    },
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

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

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

createWithExistingDisks();

Pitón

Python

Antes de probar este ejemplo, sigue las instrucciones de configuración Python en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API Python de Compute Engine .

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar la autenticación para un entorno de desarrollo local .

from __future__ import annotations

import re
import sys
from typing import Any
import warnings

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


def get_disk(project_id: str, zone: str, disk_name: str) -> compute_v1.Disk:
    """
    Gets a disk from a project.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone where the disk exists.
        disk_name: name of the disk you want to retrieve.
    """
    disk_client = compute_v1.DisksClient()
    return disk_client.get(project=project_id, zone=zone, disk=disk_name)


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_instance(
    project_id: str,
    zone: str,
    instance_name: str,
    disks: list[compute_v1.AttachedDisk],
    machine_type: str = "n1-standard-1",
    network_link: str = "global/networks/default",
    subnetwork_link: str = None,
    internal_ip: str = None,
    external_access: bool = False,
    external_ipv4: str = None,
    accelerators: list[compute_v1.AcceleratorConfig] = None,
    preemptible: bool = False,
    spot: bool = False,
    instance_termination_action: str = "STOP",
    custom_hostname: str = None,
    delete_protection: bool = False,
) -> compute_v1.Instance:
    """
    Send an instance creation request to the Compute Engine API and wait for it to complete.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone to create the instance in. For example: "us-west3-b"
        instance_name: name of the new virtual machine (VM) instance.
        disks: a list of compute_v1.AttachedDisk objects describing the disks
            you want to attach to your new instance.
        machine_type: machine type of the VM being created. This value uses the
            following format: "zones/{zone}/machineTypes/{type_name}".
            For example: "zones/europe-west3-c/machineTypes/f1-micro"
        network_link: name of the network you want the new instance to use.
            For example: "global/networks/default" represents the network
            named "default", which is created automatically for each project.
        subnetwork_link: name of the subnetwork you want the new instance to use.
            This value uses the following format:
            "regions/{region}/subnetworks/{subnetwork_name}"
        internal_ip: internal IP address you want to assign to the new instance.
            By default, a free address from the pool of available internal IP addresses of
            used subnet will be used.
        external_access: boolean flag indicating if the instance should have an external IPv4
            address assigned.
        external_ipv4: external IPv4 address to be assigned to this instance. If you specify
            an external IP address, it must live in the same region as the zone of the instance.
            This setting requires `external_access` to be set to True to work.
        accelerators: a list of AcceleratorConfig objects describing the accelerators that will
            be attached to the new instance.
        preemptible: boolean value indicating if the new instance should be preemptible
            or not. Preemptible VMs have been deprecated and you should now use Spot VMs.
        spot: boolean value indicating if the new instance should be a Spot VM or not.
        instance_termination_action: What action should be taken once a Spot VM is terminated.
            Possible values: "STOP", "DELETE"
        custom_hostname: Custom hostname of the new VM instance.
            Custom hostnames must conform to RFC 1035 requirements for valid hostnames.
        delete_protection: boolean value indicating if the new virtual machine should be
            protected against deletion or not.
    Returns:
        Instance object.
    """
    instance_client = compute_v1.InstancesClient()

    # Use the network interface provided in the network_link argument.
    network_interface = compute_v1.NetworkInterface()
    network_interface.network = network_link
    if subnetwork_link:
        network_interface.subnetwork = subnetwork_link

    if internal_ip:
        network_interface.network_i_p = internal_ip

    if external_access:
        access = compute_v1.AccessConfig()
        access.type_ = compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT.name
        access.name = "External NAT"
        access.network_tier = access.NetworkTier.PREMIUM.name
        if external_ipv4:
            access.nat_i_p = external_ipv4
        network_interface.access_configs = [access]

    # Collect information into the Instance object.
    instance = compute_v1.Instance()
    instance.network_interfaces = [network_interface]
    instance.name = instance_name
    instance.disks = disks
    if re.match(r"^zones/[a-z\d\-]+/machineTypes/[a-z\d\-]+$", machine_type):
        instance.machine_type = machine_type
    else:
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"

    instance.scheduling = compute_v1.Scheduling()
    if accelerators:
        instance.guest_accelerators = accelerators
        instance.scheduling.on_host_maintenance = (
            compute_v1.Scheduling.OnHostMaintenance.TERMINATE.name
        )

    if preemptible:
        # Set the preemptible setting
        warnings.warn(
            "Preemptible VMs are being replaced by Spot VMs.", DeprecationWarning
        )
        instance.scheduling = compute_v1.Scheduling()
        instance.scheduling.preemptible = True

    if spot:
        # Set the Spot VM setting
        instance.scheduling.provisioning_model = (
            compute_v1.Scheduling.ProvisioningModel.SPOT.name
        )
        instance.scheduling.instance_termination_action = instance_termination_action

    if custom_hostname is not None:
        # Set the custom hostname for the instance
        instance.hostname = custom_hostname

    if delete_protection:
        # Set the delete protection bit
        instance.deletion_protection = True

    # Prepare the request to insert an instance.
    request = compute_v1.InsertInstanceRequest()
    request.zone = zone
    request.project = project_id
    request.instance_resource = instance

    # Wait for the create operation to complete.
    print(f"Creating the {instance_name} instance in {zone}...")

    operation = instance_client.insert(request=request)

    wait_for_extended_operation(operation, "instance creation")

    print(f"Instance {instance_name} created.")
    return instance_client.get(project=project_id, zone=zone, instance=instance_name)


def create_with_existing_disks(
    project_id: str, zone: str, instance_name: str, disk_names: list[str]
) -> compute_v1.Instance:
    """
    Create a new VM instance using selected disks. The first disk in disk_names will
    be used as boot disk.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone to create the instance in. For example: "us-west3-b"
        instance_name: name of the new virtual machine (VM) instance.
        disk_names: list of disk names to be attached to the new virtual machine.
            First disk in this list will be used as the boot device.

    Returns:
        Instance object.
    """
    assert len(disk_names) >= 1
    disks = [get_disk(project_id, zone, disk_name) for disk_name in disk_names]
    attached_disks = []
    for disk in disks:
        adisk = compute_v1.AttachedDisk()
        adisk.source = disk.self_link
        attached_disks.append(adisk)
    attached_disks[0].boot = True
    instance = create_instance(project_id, zone, instance_name, attached_disks)
    return instance

Crear una instancia a partir de una instantánea del disco de arranque

Si creó una instantánea del disco de arranque de una instancia informática, puede usar esa instantánea para crear una nueva instancia.

Para crear rápidamente más de una instancia con el mismo disco de arranque, cree una imagen personalizada y luego cree instancias a partir de esa imagen en lugar de usar una instantánea.

Para crear una instancia informática con un disco de arranque regional creado a partir de una instantánea, utilice la CLI o REST de Google Cloud.

Consola

  1. En la consola de Google Cloud, vaya a la página Crear una instancia .

    Ir a Crear una instancia

    Si se le solicita, seleccione su proyecto y haga clic en Continuar . Aparece la página Crear una instancia y muestra el panel de configuración de la máquina .

  2. En el panel de configuración de la máquina , haga lo siguiente:

    1. En el campo Nombre , especifique un nombre para su instancia. Para obtener más información, consulte Convención de nomenclatura de recursos .
    2. Opcional: en el campo Zona , seleccione una zona para esta instancia.

      La selección predeterminada es Cualquiera . Si no cambia esta selección predeterminada, Google elegirá automáticamente una zona según el tipo de máquina y la disponibilidad.

    3. Seleccione la familia de máquinas para su instancia. Luego, la consola de Google Cloud muestra la serie de máquinas que están disponibles para la familia de máquinas seleccionada. Están disponibles las siguientes opciones de familia de máquinas:

      • Propósito general
      • Computación optimizada
      • Memoria optimizada
      • Almacenamiento optimizado
      • GPU

    4. En la columna Serie , seleccione la serie de máquinas para su instancia.

      Si seleccionó GPU como familia de máquinas en el paso anterior, seleccione el tipo de GPU que desee. Luego, la serie de máquinas se selecciona automáticamente para el tipo de GPU seleccionado.

    5. En la sección Tipo de máquina , seleccione el tipo de máquina para su instancia.

  3. En el menú de navegación, haga clic en SO y almacenamiento . En el panel Sistema operativo y almacenamiento que aparece, configure su disco de arranque haciendo lo siguiente:

    1. Haga clic en Cambiar . Aparece el panel Disco de arranque y muestra la pestaña Imágenes públicas .
    2. Haga clic en Instantáneas . Aparece la pestaña Instantánea .
    3. En la lista Instantánea , seleccione la instantánea que desea utilizar.
    4. En la lista Tipo de disco de arranque , seleccione el tipo de disco de arranque.
    5. En el campo Tamaño (GB) , especifique el tamaño del disco de arranque.
    6. Opcional: para opciones de configuración avanzadas, expanda la sección Mostrar configuraciones avanzadas .
    7. Para confirmar las opciones de su disco de arranque y regresar al panel Sistema operativo y almacenamiento , haga clic en Seleccionar .
  4. En el menú de navegación, haga clic en Redes . En el panel Redes que aparece, haga lo siguiente:

    1. Vaya a la sección Cortafuegos .
    2. Para permitir el tráfico HTTP o HTTPS a la instancia, seleccione Permitir tráfico HTTP o Permitir tráfico HTTPS .

    La consola de Google Cloud agrega una etiqueta de red a su instancia y crea la regla de firewall de ingreso correspondiente que permite todo el tráfico entrante en tcp:80 (HTTP) o tcp:443 (HTTPS). La etiqueta de red asocia la regla de firewall con la instancia. Para obtener más información, consulte Descripción general de las reglas de firewall en la documentación de Virtual Private Cloud.

  5. Opcional: especifique otras opciones de configuración. Para obtener más información, consulte Opciones de configuración durante la creación de instancias .

  6. Para crear e iniciar la instancia, haga clic en Crear .

nube de gcloud

Disco de arranque zonal

Utilice el comando gcloud compute instances create e incluya la marca --source-snapshot .

   gcloud compute instances create INSTANCE_NAME  
--source-snapshot=BOOT_SNAPSHOT_NAME
--boot-disk-size=BOOT_DISK_SIZE
--boot-disk-type=BOOT_DISK_TYPE
--boot-disk-device-name=BOOT_DISK_NAME

Reemplace lo siguiente:

  • INSTANCE_NAME : nombre de la nueva instancia
  • BOOT_SNAPSHOT_NAME : nombre de la instantánea del disco de inicio que desea restaurar en el disco de inicio de la nueva instancia
  • BOOT_DISK_SIZE : Opcional: tamaño, en GiB, del nuevo disco de arranque

    El tamaño debe ser igual o mayor que el tamaño del disco de origen desde el que se realizó la instantánea.

  • BOOT_DISK_TYPE : Opcional: tipo de disco de arranque, por ejemplo PROJECT_ID /zones/ ZONE /diskTypes/pd-ssd o PROJECT_ID /zones/ ZONE /diskTypes/hyperdisk-balanced

  • BOOT_DISK_NAME : nombre del nuevo disco de arranque para esta instancia

Disco de arranque regional

Utilice el comando gcloud compute instances create e incluya la marca --create-disk con las propiedades source-snapshot , replica-zones y boot .

  gcloud compute instances create INSTANCE_NAME 
--zone=ZONE
--create-disk=^:^name=DISK_NAME:source-snapshot=BOOT_SNAPSHOT_NAME:boot=true:type=BOOT_DISK_TYPE:replica-zones=ZONE,REMOTE_ZONE

Los caracteres ^:^ especifican que dos puntos : se utilizan como separador entre cada una de las propiedades del disco. Esto es necesario para que pueda utilizar una , al especificar las zonas para replica-zones .

Reemplace lo siguiente:

  • INSTANCE_NAME : nombre de la nueva instancia
  • ZONE : A la zona para crear la instancia en
  • DISK_NAME : Opcional: un nombre para el disco
  • BOOT_SNAPSHOT_NAME : nombre de la instantánea del disco de inicio que desea restaurar en el disco de inicio de la nueva instancia.
  • BOOT_DISK_TYPE : Opcional: tipo de disco de arranque, por ejemplo pd-ssd o hyperdisk-balanced-high-availability
  • REMOTE_ZONE : la región en la que se replica el disco de arranque. La propiedad replica-zones requiere dos zonas separadas por comas, y una de las zonas debe ser la misma que la zona de la instancia.

Ir

Go

Antes de probar este ejemplo, sigue las instrucciones de configuración Go en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API Go de Compute Engine .

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar la autenticación para un entorno de desarrollo local .

import (
	"context"
	"fmt"
	"io"

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

// createInstanceFromSnapshot creates a new VM instance with boot disk created from a snapshot.
func createInstanceFromSnapshot(w io.Writer, projectID, zone, instanceName, snapshotLink string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// snapshotLink := "projects/project_name/global/snapshots/snapshot_name"

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

	req := &computepb.InsertInstanceRequest{
		Project: projectID,
		Zone:    zone,
		InstanceResource: &computepb.Instance{
			Name: proto.String(instanceName),
			Disks: []*computepb.AttachedDisk{
				{
					InitializeParams: &computepb.AttachedDiskInitializeParams{
						DiskSizeGb:     proto.Int64(11),
						SourceSnapshot: proto.String(snapshotLink),
						DiskType:       proto.String(fmt.Sprintf("zones/%s/diskTypes/pd-standard", zone)),
					},
					AutoDelete: proto.Bool(true),
					Boot:       proto.Bool(true),
					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
				},
			},
			MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/n1-standard-1", zone)),
			NetworkInterfaces: []*computepb.NetworkInterface{
				{
					Name: proto.String("global/networks/default"),
				},
			},
		},
	}

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

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

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

	return nil
}

Java

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración Java en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API Java de Compute Engine .

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar la autenticación para un entorno de desarrollo local .


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDisk.Type;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.Image;
import com.google.cloud.compute.v1.ImagesClient;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import com.google.cloud.compute.v1.Operation;
import java.io.IOException;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateInstancesAdvanced {

  /**
   * @param diskType 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"
   * @param diskSizeGb size of the new disk in gigabytes
   * @param boot boolean flag indicating whether this disk should be used as a boot disk of an
   * instance
   * @param diskSnapshot disk snapshot to use when creating this disk. You must have read access to
   * this disk. This value uses the following format:
   * "projects/{project_name}/global/snapshots/{snapshot_name}"
   * @return AttachedDisk object configured to be created using the specified snapshot.
   */
  private static AttachedDisk diskFromSnapshot(String diskType, int diskSizeGb, boolean boot,
      String diskSnapshot) {
    AttachedDisk disk =
        AttachedDisk.newBuilder()
            .setBoot(boot)
            // Remember to set auto_delete to True if you want the disk to be deleted when
            // you delete your VM instance.
            .setAutoDelete(true)
            .setType(Type.PERSISTENT.toString())
            .setInitializeParams(
                AttachedDiskInitializeParams.newBuilder()
                    .setSourceSnapshot(diskSnapshot)
                    .setDiskSizeGb(diskSizeGb)
                    .setDiskType(diskType)
                    .build())
            .build();
    return disk;
  }


  /**
   * Send an instance creation request to the Compute Engine API and wait for it to complete.
   *
   * @param project project ID or project number of the Cloud project you want to use.
   * @param zone name of the zone to create the instance in. For example: "us-west3-b"
   * @param instanceName name of the new virtual machine (VM) instance.
   * @param disks a list of compute_v1.AttachedDisk objects describing the disks you want to attach
   * to your new instance.
   * @param machineType machine type of the VM being created. This value uses the following format:
   * "zones/{zone}/machineTypes/{type_name}".
   * For example: "zones/europe-west3-c/machineTypes/f1-micro"
   * @param network name of the network you want the new instance to use. For example:
   * "global/networks/default" represents the network named "default", which is created
   * automatically for each project.
   * @param subnetwork name of the subnetwork you want the new instance to use. This value uses the
   * following format: "regions/{region}/subnetworks/{subnetwork_name}"
   * @return Instance object.
   */
  private static Instance createWithDisks(String project, String zone, String instanceName,
      Vector<AttachedDisk> disks, String machineType, String network, String subnetwork)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    try (InstancesClient instancesClient = InstancesClient.create()) {
      // Use the network interface provided in the networkName argument.
      NetworkInterface networkInterface;
      if (subnetwork != null) {
        networkInterface = NetworkInterface.newBuilder()
            .setName(network).setSubnetwork(subnetwork)
            .build();
      } else {
        networkInterface = NetworkInterface.newBuilder()
            .setName(network).build();
      }

      machineType = String.format("zones/%s/machineTypes/%s", zone, machineType);

      // Bind `instanceName`, `machineType`, `disk`, and `networkInterface` to an instance.
      Instance instanceResource =
          Instance.newBuilder()
              .setName(instanceName)
              .setMachineType(machineType)
              .addAllDisks(disks)
              .addNetworkInterfaces(networkInterface)
              .build();

      System.out.printf("Creating instance: %s at %s ", instanceName, zone);

      // Insert the instance in the specified project and zone.
      InsertInstanceRequest insertInstanceRequest = InsertInstanceRequest.newBuilder()
          .setProject(project)
          .setZone(zone)
          .setInstanceResource(instanceResource).build();

      OperationFuture<Operation, Operation> operation = instancesClient.insertAsync(
          insertInstanceRequest);

      // Wait for the operation to complete.
      Operation response = operation.get(3, TimeUnit.MINUTES);

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

      return instancesClient.get(project, zone, instanceName);
    }
  }

  /**
   * Create a new VM instance with boot disk created from a snapshot.
   *
   * @param project project ID or project number of the Cloud project you want to use.
   * @param zone name of the zone to create the instance in. For example: "us-west3-b"
   * @param instanceName name of the new virtual machine (VM) instance.
   * @param snapshotName link to the snapshot you want to use as the source of your boot disk in the
   * form of: "projects/{project_name}/global/snapshots/{snapshot_name}"
   * @return Instance object.
   */
  public static Instance createFromSnapshot(String project, String zone, String instanceName,
      String snapshotName)
      throws IOException, InterruptedException, ExecutionException, TimeoutException {
    String diskType = String.format("zones/%s/diskTypes/pd-standard", zone);
    Vector<AttachedDisk> disks = new Vector<>();
    disks.add(diskFromSnapshot(diskType, 11, true, snapshotName));
    return createWithDisks(project, zone, instanceName, disks, "n1-standard-1",
        "global/networks/default", null);
  }

Nodo.js

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración de Node.js en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API de Compute Engine Node.js

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar la autenticación para un entorno de desarrollo local .

/**
 * TODO(developer): Uncomment and replace these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'europe-central2-b';
// const instanceName = 'YOUR_INSTANCE_NAME';
// const snapshotLink = 'projects/YOUR_PROJECT/global/snapshots/YOUR_SNAPSHOT_NAME';

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

// Creates a new VM instance with boot disk created from a snapshot.
async function createInstanceFromSnapshot() {
  const instancesClient = new compute.InstancesClient();

  const [response] = await instancesClient.insert({
    project: projectId,
    zone,
    instanceResource: {
      name: instanceName,
      disks: [
        {
          initializeParams: {
            diskSizeGb: '11',
            sourceSnapshot: snapshotLink,
            diskType: `zones/${zone}/diskTypes/pd-standard`,
          },
          autoDelete: true,
          boot: true,
          type: 'PERSISTENT',
        },
      ],
      machineType: `zones/${zone}/machineTypes/n1-standard-1`,
      networkInterfaces: [
        {
          name: 'global/networks/default',
        },
      ],
    },
  });
  let operation = response.latestResponse;
  const operationsClient = new compute.ZoneOperationsClient();

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

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

createInstanceFromSnapshot();

Pitón

Python

Antes de probar este ejemplo, sigue las instrucciones de configuración Python en el inicio rápido de Compute Engine usando bibliotecas cliente . Para obtener más información, consulta la documentación de referencia de la API Python de Compute Engine .

Para autenticarse en Compute Engine, configure las credenciales predeterminadas de la aplicación. Para obtener más información, consulte Configurar la autenticación para un entorno de desarrollo local .

from __future__ import annotations

import re
import sys
from typing import Any
import warnings

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


def disk_from_snapshot(
    disk_type: str,
    disk_size_gb: int,
    boot: bool,
    source_snapshot: str,
    auto_delete: bool = True,
) -> compute_v1.AttachedDisk():
    """
    Create an AttachedDisk object to be used in VM instance creation. Uses a disk snapshot as the
    source for the new disk.

    Args:
         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
        boot: boolean flag indicating whether this disk should be used as a boot disk of an instance
        source_snapshot: disk snapshot to use when creating this disk. You must have read access to this disk.
            This value uses the following format: "projects/{project_name}/global/snapshots/{snapshot_name}"
        auto_delete: boolean flag indicating whether this disk should be deleted with the VM that uses it

    Returns:
        AttachedDisk object configured to be created using the specified snapshot.
    """
    disk = compute_v1.AttachedDisk()
    initialize_params = compute_v1.AttachedDiskInitializeParams()
    initialize_params.source_snapshot = source_snapshot
    initialize_params.disk_type = disk_type
    initialize_params.disk_size_gb = disk_size_gb
    disk.initialize_params = initialize_params
    # Remember to set auto_delete to True if you want the disk to be deleted when you delete
    # your VM instance.
    disk.auto_delete = auto_delete
    disk.boot = boot
    return disk


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_instance(
    project_id: str,
    zone: str,
    instance_name: str,
    disks: list[compute_v1.AttachedDisk],
    machine_type: str = "n1-standard-1",
    network_link: str = "global/networks/default",
    subnetwork_link: str = None,
    internal_ip: str = None,
    external_access: bool = False,
    external_ipv4: str = None,
    accelerators: list[compute_v1.AcceleratorConfig] = None,
    preemptible: bool = False,
    spot: bool = False,
    instance_termination_action: str = "STOP",
    custom_hostname: str = None,
    delete_protection: bool = False,
) -> compute_v1.Instance:
    """
    Send an instance creation request to the Compute Engine API and wait for it to complete.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone to create the instance in. For example: "us-west3-b"
        instance_name: name of the new virtual machine (VM) instance.
        disks: a list of compute_v1.AttachedDisk objects describing the disks
            you want to attach to your new instance.
        machine_type: machine type of the VM being created. This value uses the
            following format: "zones/{zone}/machineTypes/{type_name}".
            For example: "zones/europe-west3-c/machineTypes/f1-micro"
        network_link: name of the network you want the new instance to use.
            For example: "global/networks/default" represents the network
            named "default", which is created automatically for each project.
        subnetwork_link: name of the subnetwork you want the new instance to use.
            This value uses the following format:
            "regions/{region}/subnetworks/{subnetwork_name}"
        internal_ip: internal IP address you want to assign to the new instance.
            By default, a free address from the pool of available internal IP addresses of
            used subnet will be used.
        external_access: boolean flag indicating if the instance should have an external IPv4
            address assigned.
        external_ipv4: external IPv4 address to be assigned to this instance. If you specify
            an external IP address, it must live in the same region as the zone of the instance.
            This setting requires `external_access` to be set to True to work.
        accelerators: a list of AcceleratorConfig objects describing the accelerators that will
            be attached to the new instance.
        preemptible: boolean value indicating if the new instance should be preemptible
            or not. Preemptible VMs have been deprecated and you should now use Spot VMs.
        spot: boolean value indicating if the new instance should be a Spot VM or not.
        instance_termination_action: What action should be taken once a Spot VM is terminated.
            Possible values: "STOP", "DELETE"
        custom_hostname: Custom hostname of the new VM instance.
            Custom hostnames must conform to RFC 1035 requirements for valid hostnames.
        delete_protection: boolean value indicating if the new virtual machine should be
            protected against deletion or not.
    Returns:
        Instance object.
    """
    instance_client = compute_v1.InstancesClient()

    # Use the network interface provided in the network_link argument.
    network_interface = compute_v1.NetworkInterface()
    network_interface.network = network_link
    if subnetwork_link:
        network_interface.subnetwork = subnetwork_link

    if internal_ip:
        network_interface.network_i_p = internal_ip

    if external_access:
        access = compute_v1.AccessConfig()
        access.type_ = compute_v1.AccessConfig.Type.ONE_TO_ONE_NAT.name
        access.name = "External NAT"
        access.network_tier = access.NetworkTier.PREMIUM.name
        if external_ipv4:
            access.nat_i_p = external_ipv4
        network_interface.access_configs = [access]

    # Collect information into the Instance object.
    instance = compute_v1.Instance()
    instance.network_interfaces = [network_interface]
    instance.name = instance_name
    instance.disks = disks
    if re.match(r"^zones/[a-z\d\-]+/machineTypes/[a-z\d\-]+$", machine_type):
        instance.machine_type = machine_type
    else:
        instance.machine_type = f"zones/{zone}/machineTypes/{machine_type}"

    instance.scheduling = compute_v1.Scheduling()
    if accelerators:
        instance.guest_accelerators = accelerators
        instance.scheduling.on_host_maintenance = (
            compute_v1.Scheduling.OnHostMaintenance.TERMINATE.name
        )

    if preemptible:
        # Set the preemptible setting
        warnings.warn(
            "Preemptible VMs are being replaced by Spot VMs.", DeprecationWarning
        )
        instance.scheduling = compute_v1.Scheduling()
        instance.scheduling.preemptible = True

    if spot:
        # Set the Spot VM setting
        instance.scheduling.provisioning_model = (
            compute_v1.Scheduling.ProvisioningModel.SPOT.name
        )
        instance.scheduling.instance_termination_action = instance_termination_action

    if custom_hostname is not None:
        # Set the custom hostname for the instance
        instance.hostname = custom_hostname

    if delete_protection:
        # Set the delete protection bit
        instance.deletion_protection = True

    # Prepare the request to insert an instance.
    request = compute_v1.InsertInstanceRequest()
    request.zone = zone
    request.project = project_id
    request.instance_resource = instance

    # Wait for the create operation to complete.
    print(f"Creating the {instance_name} instance in {zone}...")

    operation = instance_client.insert(request=request)

    wait_for_extended_operation(operation, "instance creation")

    print(f"Instance {instance_name} created.")
    return instance_client.get(project=project_id, zone=zone, instance=instance_name)


def create_from_snapshot(
    project_id: str, zone: str, instance_name: str, snapshot_link: str
):
    """
    Create a new VM instance with boot disk created from a snapshot. The
    new boot disk will have 20 gigabytes.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        zone: name of the zone to create the instance in. For example: "us-west3-b"
        instance_name: name of the new virtual machine (VM) instance.
        snapshot_link: link to the snapshot you want to use as the source of your
            boot disk in the form of: "projects/{project_name}/global/snapshots/{snapshot_name}"

    Returns:
        Instance object.
    """
    disk_type = f"zones/{zone}/diskTypes/pd-standard"
    disks = [disk_from_snapshot(disk_type, 20, True, snapshot_link)]
    instance = create_instance(project_id, zone, instance_name, disks)
    return instance

DESCANSAR

Cuando utiliza la API para crear una instancia a partir de una instantánea, se aplican las siguientes restricciones:

  • Sólo se puede utilizar un disco como disco de arranque.
  • Debe adjuntar el disco de arranque como primer disco para esa instancia.
  • Si especifica la propiedad source , no puede especificar también la propiedad initializeParams . Proporcionar una source indica que el disco de inicio ya existe, pero la propiedad initializeParams indica que Compute Engine debe crear un nuevo disco de inicio.

Disco de arranque zonal

Para crear una instancia a partir de una instantánea del disco de arranque, utilice el método instances.insert y especifique el campo sourceSnapshot en la propiedad disks . Opcionalmente, puede especificar las propiedades diskSizeGb y diskType para el nuevo disco de inicio.
POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances
{
  "name": "INSTANCE_NAME",
  "machineType": "machineTypes/MACHINE_TYPE",
  "disks": [{
     "boot": true,
     "initializeParams": {
       "sourceSnapshot": "global/snapshots/BOOT_SNAPSHOT_NAME",
       "diskSizeGb": "BOOT_DISK_SIZE",
       "diskType": "BOOT_DISK_TYPE"
      }
   }],
  "networkInterfaces": [
    {
       "nicType": "GVNIC"
    }
  ]
}
Reemplace lo siguiente:
  • PROJECT_ID : ID de tu proyecto
  • ZONE : zona donde desea crear la nueva instancia
  • INSTANCE_NAME : nombre de la instancia en la que desea restaurar una instantánea
  • MACHINE_TYPE : tipo de máquina de la instancia
  • BOOT_SNAPSHOT_NAME : nombre de la instantánea que desea usar para crear el disco de arranque de la nueva instancia
  • BOOT_DISK_SIZE : Opcional: tamaño, en gibibytes (GiB), para el nuevo disco de arranque

    El tamaño debe ser igual o mayor que el tamaño del disco de origen desde el que se realizó la instantánea.

  • BOOT_DISK_TYPE : Opcional: tipo de disco de arranque, por ejemplo PROJECT_ID /zones/ ZONE /diskTypes/pd-ssd o PROJECT_ID /zones/ ZONE /diskTypes/hyperdisk-balanced

Disco de arranque regional

Para crear una instancia informática con un disco de arranque regional usando una instantánea del disco de arranque como origen, use el método instances.insert y especifique los campos sourceSnapshot y replicaZones en la propiedad disks .
   POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances
   {
     "name": "INSTANCE_NAME",
     "disks": [
       {
         "boot": true,
         "initializeParams": {
            "sourceSnapshot": "global/snapshots/BOOT_SNAPSHOT_NAME",
            "replicaZones": [
                "projects/PROJECT_ID/zones/ZONE",
                "projects/PROJECT_ID/zones/REMOTE_ZONE"
              ],
            "diskType": "BOOT_DISK_TYPE"
         }
       }
     ],
     "networkInterfaces": [
       {
         "nicType": "GVNIC"
       }
     ]
   }
   

Reemplace lo siguiente:

  • PROJECT_ID : ID de tu proyecto
  • ZONE : el nombre de la zona donde desea crear la instancia
  • INSTANCE_NAME `: un nombre para la instancia
  • BOOT_SNAPSHOT_NAME : el nombre de la instantánea del disco de arranque
  • REMOTE_ZONE : la zona remota para el disco regional
  • BOOT_DISK_TYPE : Opcional: tipo de disco de arranque, por ejemplo PROJECT_ID /zones/ ZONE /diskTypes/pd-ssd o PROJECT_ID /zones/ ZONE /diskTypes/hyperdisk-balanced-high-availability

Cree una instancia informática a partir de una instantánea del disco que no sea de arranque

Si realizó una copia de seguridad de un disco que no es de arranque con una instantánea, puede crear una instancia con un disco que no es de arranque adicional basado en la instantánea.

Consola

Al restaurar instantáneas que no son de arranque en una nueva instancia desde la consola, primero cree un disco a partir de cada instantánea. Luego, adjunte los nuevos discos cuando cree la instancia.

  1. Restaure cada instantánea que no sea de arranque en un disco nuevo.

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

      Ir a discos

    2. Haga clic en Crear disco .

    3. Especifique un nombre para su disco. Para obtener más información, consulte Convención de nomenclatura de recursos .

    4. Seleccione la Región y Zona para este disco. El disco y la instancia deben estar en la misma zona para discos zonales o región para discos regionales.

    5. Seleccione un tipo de disco.

    6. En Tipo de fuente , seleccione Instantánea .

    7. En el nuevo campo Instantánea de origen , seleccione una instantánea que no sea de arranque y que desee restaurar en el nuevo disco.

    8. Para crear el disco, haga clic en Crear .

    Repita estos pasos para crear un disco a partir de cada instantánea que desee restaurar.

  2. En la consola de Google Cloud, vaya a la página de instancias de VM .

    Ir a instancias de VM

  3. Seleccione su proyecto y haga clic en Continuar .

  4. Haga clic en Crear instancia .

  5. Especifique un nombre para su instancia. Para obtener más información, consulte Convención de nomenclatura de recursos .

  6. Seleccione la Región y Zona para esta instancia. El disco y la instancia deben estar en la misma zona para discos zonales o región para discos regionales.

  7. Seleccione un tipo de máquina para su instancia.

  8. Si desea permitir el tráfico externo entrante, cambie las reglas del Firewall para la instancia.

  9. Para adjuntar discos a la instancia, expanda la sección Opciones avanzadas y luego haga lo siguiente:

    1. Expanda la sección Discos .
    2. Haga clic en Adjuntar disco existente .
    3. En la lista Disco , seleccione un disco para adjuntarlo a esta instancia.
    4. En la sección Configuración de archivos adjuntos , seleccione el Modo de archivo adjunto del disco y la Regla de eliminación . Para obtener más información sobre cómo agregar nuevos discos, consulteAgregar un disco persistente oAgregar hiperdisco .
    5. Haga clic en Guardar .

    Repita estos pasos para cada disco que desee conectar.

  10. Para crear e iniciar la instancia, haga clic en Crear .

nube de gcloud

Crea una instancia mediante el comando gcloud compute instances create . Para cada instantánea que no sea de arranque y que desee restaurar, incluya la marca --create-disk y especifique una source-snapshot .

Por ejemplo, para restaurar dos instantáneas de discos que no son de arranque en una nueva instancia, use el siguiente comando:

gcloud compute instances create INSTANCE_NAME \
    --create-disk source-snapshot=SNAPSHOT_1_NAME,name=DISK_1_NAME,size=DISK_1_SIZE,type=DISK_1_TYPE \
    --create-disk source-snapshot=SNAPSHOT_2_NAME,name=DISK_2_NAME,size=DISK_2_SIZE,type=DISK_2_TYPE

Reemplace lo siguiente:

  • INSTANCE_NAME : nombre de la nueva instancia
  • SNAPSHOT_1_NAME y SNAPSHOT_2_NAME : nombres de las instantáneas del disco que no son de arranque que desea restaurar
  • DISK_1_NAME y DISK_2_NAME : nombres de los nuevos discos que no son de arranque para crear para esta instancia
  • DISK_1_SIZE y DISK_2_SIZE : opcional: tamaños, en gibibytes (GiB), de cada nuevo disco que no sea de arranque.

    Los tamaños deben ser iguales o mayores que los tamaños de los discos de origen a partir de los cuales se realizó la instantánea.

  • DISK_1_TYPE y DISK_2_TYPE : Opcional: los tipos de disco a crear, por ejemplopd-ssd o hyperdisk-balanced

DESCANSAR

Cuando se utiliza REST para restaurar una instantánea que no es de inicio en una nueva instancia, se aplican las siguientes restricciones:

  • Sólo un disco puede ser el disco de arranque.
  • Debe adjuntar el disco de arranque como primer disco para esa instancia.
  • Si especifica la propiedad source , no puede especificar también la propiedad initializeParams . Proporcionar una source indica que el disco de inicio ya existe, pero la propiedad initializeParams indica que Compute Engine debe crear un nuevo disco de inicio.

Cree una solicitud POST para el método instances.insert y especifique el campo sourceSnapshot en la propiedad initializeParams . Puede agregar varios discos que no sean de arranque repitiendo la propiedad initializeParams para cada disco que no sea de arranque que desee crear. Opcionalmente, puede especificar las propiedades diskSizeGb y diskType para cualquiera de los discos que cree.

Por ejemplo, para restaurar dos instantáneas de disco que no son de arranque en una nueva instancia, realice la siguiente solicitud:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances
{
  "name": "INSTANCE_NAME",
  "machineType": "machineTypes/MACHINE_TYPE",
  "networkInterfaces": [
    {
      "nicType": "GVNIC"
    }
  ],
  "disks": [
    {
      "autoDelete": "true",
      "boot": "true",
      "diskSizeGb": "BOOT_DISK_SIZE",
      "diskType": "BOOT_DISK_TYPE",
      "initializeParams": {
         "sourceImage": "projects/IMAGE_PROJECT/global/images/family/IMAGE_FAMILY"
      }
    },
    {
      "deviceName": "DEVICE_1_NAME",
      "initializeParams": {
         "sourceSnapshot": "global/snapshots/SNAPSHOT_1_NAME",
         "diskSizeGb": "DISK_1_SIZE",
         "diskType": "DISK_1_TYPE"
      }
    },
    {
      "deviceName": "DEVICE_2_NAME",
      "initializeParams": {
         "sourceSnapshot": "global/snapshots/SNAPSHOT_2_NAME",
         "diskSizeGb": "DISK_2_SIZE",
         "diskType": "DISK_2_TYPE"
      }
    }
  ]
}

Reemplace lo siguiente:

  • PROJECT_ID : ID de tu proyecto
  • ZONE : zona donde desea crear la instancia
  • INSTANCE_NAME : un nombre para la nueva instancia
  • MACHINE_TYPE : tipo de máquina de la instancia
  • DISK_SIZE : Opcional: tamaño, en gibibytes (GiB), del disco correspondiente

    Cuando se proporciona, esta propiedad debe ser igual o mayor que el tamaño del disco de origen desde el que se realizó la instantánea.

  • DISK_TYPE : Opcional: URL completa o parcial para el tipo de disco correspondiente, por ejemplo,PROJECT_ID /zones/ ZONE /diskTypes/pd-ssd o PROJECT_ID /zones/ ZONE /diskTypes/hyperdisk-balanced

  • IMAGE_PROJECT : el proyecto que contiene la imagen. Por ejemplo, debian-cloud

  • IMAGE_FAMILY : una familia de imágenes. Esto crea la instancia a partir de la imagen de sistema operativo no obsoleta más reciente de esa familia. Por ejemplo, si especifica "sourceImage": "projects/debian-cloud/global/images/family/debian-11" , Compute Engine crea una instancia utilizando la última versión de la imagen del sistema operativo en la familia de imágenes de Debian 11.

  • DEVICE_NAME : Opcional: el nombre del dispositivo que se muestra en el sistema operativo invitado de la instancia.

  • SNAPSHOT_NAME : los nombres de las instantáneas de disco correspondientes que no son de arranque y que desea restaurar en discos nuevos en la instancia.