Créer et gérer des VM Windows Server


Compute Engine fournit avec Windows Server des images publiques que vous pouvez utiliser pour créer des instances. Pour découvrir comment créer une instance Windows Server avec SQL Server préinstallé, consultez la page Créer des instances SQL Server.

Pour plus d'informations générales sur les instances Windows Server et les applications Windows que vous pouvez exécuter sur Compute Engine, consultez Windows sur Compute Engine.

Tarifs

Avant de commencer

  • Activer la facturation pour votre projet
  • Si ce n'est pas déjà fait, configurez l'authentification. L'authentification est le processus permettant de valider votre identité pour accéder aux services et aux API Google Cloud. Pour exécuter du code ou des exemples depuis un environnement de développement local, vous pouvez vous authentifier auprès de Compute Engine comme suit :

    Sélectionnez l'onglet correspondant à la façon dont vous prévoyez d'utiliser les exemples de cette page :

    Console

    Lorsque vous utilisez la console Google Cloud pour accéder aux services et aux API Google Cloud, vous n'avez pas besoin de configurer l'authentification.

    gcloud

    1. Installez Google Cloud CLI, puis initialisez-la en exécutant la commande suivante :

      gcloud init
    2. Définissez une région et une zone par défaut.

    Go

    Pour utiliser les exemples Go de cette page dans un environnement de développement local, installez et initialisez gcloud CLI, puis configurez le service Identifiants par défaut de l'application à l'aide de vos identifiants utilisateur.

    1. Installez Google Cloud CLI.
    2. Pour initialiser gcloudCLI, exécutez la commande suivante :

      gcloud init
    3. Créez des identifiants d'authentification locaux pour votre compte Google :

      gcloud auth application-default login

    Pour en savoir plus, consultez les sections sur Configurer l'authentification pour un environnement de développement local.

    Java

    Pour utiliser les exemples Java de cette page dans un environnement de développement local, installez et initialisez gcloud CLI, puis configurez le service Identifiants par défaut de l'application à l'aide de vos identifiants utilisateur.

    1. Installez Google Cloud CLI.
    2. Pour initialiser gcloudCLI, exécutez la commande suivante :

      gcloud init
    3. Créez des identifiants d'authentification locaux pour votre compte Google :

      gcloud auth application-default login

    Pour en savoir plus, consultez les sections sur Configurer l'authentification pour un environnement de développement local.

    Node.js

    Pour utiliser les exemples Node.js de cette page dans un environnement de développement local, installez et initialisez gcloud CLI, puis configurez le service Identifiants par défaut de l'application à l'aide de vos identifiants utilisateur.

    1. Installez Google Cloud CLI.
    2. Pour initialiser gcloudCLI, exécutez la commande suivante :

      gcloud init
    3. Créez des identifiants d'authentification locaux pour votre compte Google :

      gcloud auth application-default login

    Pour en savoir plus, consultez les sections sur Configurer l'authentification pour un environnement de développement local.

    Python

    Pour utiliser les exemples Python de cette page dans un environnement de développement local, installez et initialisez gcloud CLI, puis configurez le service Identifiants par défaut de l'application à l'aide de vos identifiants utilisateur.

    1. Installez Google Cloud CLI.
    2. Pour initialiser gcloudCLI, exécutez la commande suivante :

      gcloud init
    3. Créez des identifiants d'authentification locaux pour votre compte Google :

      gcloud auth application-default login

    Pour en savoir plus, consultez les sections sur Configurer l'authentification pour un environnement de développement local.

    REST

    Pour utiliser les exemples d'API REST de cette page dans un environnement de développement local, vous devez utiliser les identifiants que vous fournissez à gcloud CLI.

      Installez Google Cloud CLI, puis initialisez-la en exécutant la commande suivante :

      gcloud init

Créer une instance Windows Server

Pour créer une instance avec Windows Server, spécifiez la famille d'images correspondant à la version spécifique de Windows dont vous avez besoin. Compute Engine propose plusieurs versions de Windows Server, dont la plupart sont disponibles sous forme d'images de VM protégées. Les images de VM protégées offrent des fonctionnalités de sécurité telles qu'un micrologiciel compatible UEFI, le démarrage sécurisé et le démarrage mesuré protégé par vTPM. Pour obtenir une liste des familles d'images disponibles, consultez la section Images publiques.

Si vous avez besoin de plus de deux sessions simultanées de bureau à distance, vous devez acheter des licences d'accès client (CAL) aux sessions du Bureau à distance (RDS). Pour en savoir plus, consultez la section Gérer les licences de votre déploiement RDS avec des licences d'accès client (CAL).

Utiliser Microsoft Active Directory

Si vous prévoyez d'utiliser Microsoft Active Directory (AD) avec votre nouvelle instance, assurez-vous que le nom de l'instance ne dépasse pas 15 caractères afin de respecter les restrictions de longueur maximale des noms applicables au système.

AD utilise les noms NetBIOS des machines qui sont générés à partir du nom d'instance tronqué à 15 caractères. Par conséquent, vous pouvez rencontrer l'erreur suivante lorsque vous essayez de vous connecter en tant qu'utilisateur du domaine : The Security Database on the Server does not have a Computer Account for this Workstation Trust Relationship.

Créer une instance Windows Server utilisant une adresse IP externe pour l'activation

Cette section explique comment créer une instance Windows Server disposant d'une adresse IP externe. Votre réseau VPC doit être configuré pour autoriser l'accès à kms.windows.googlecloud.com.

Console

Pour créer une VM Windows de base :

  1. Accédez à la page Créer une instance dans Google Cloud Console.

    Accéder à la page Créer une instance

  2. Pour Disque de démarrage, sélectionnez Modifier, puis procédez comme suit :

    1. Dans l'onglet Images publiques, choisissez un système d'exploitation Windows Server.
    2. Cliquez sur Select (Sélectionner).
  3. Pour créer la VM, cliquez sur Créer.

Pour créer une instance Windows de VM protégée, procédez comme suit :

  1. Accédez à la page Créer une instance dans Google Cloud Console.

    Accéder à la page Créer une instance

  2. Pour Disque de démarrage, sélectionnez Modifier, puis procédez comme suit :

    1. Dans l'onglet Images publiques, choisissez un système d'exploitation Windows Server.
    2. Pour enregistrer la configuration de votre disque de démarrage, cliquez sur Sélectionner.
  3. Vous pouvez aussi modifier les paramètres de VM protégée de la VM en développant la section Options avancées. Ensuite, procédez comme suit :

    1. Développez la section Sécurité.
    2. Si vous souhaitez désactiver le démarrage sécurisé, décochez la case Activer le démarrage sécurisé. Le démarrage sécurisé permet de protéger vos instances de VM contre les logiciels malveillants et les rootkits opérant au niveau des secteurs de démarrage et du noyau. Pour plus d'informations, consultez la section Démarrage sécurisé.
    3. Si vous souhaitez désactiver le module vTPM (Virtual Trusted Platform Module), décochez la case Activer vTPM. Le module vTPM active le démarrage mesuré, ce qui permet de valider l'intégrité du pré-amorçage et du démarrage de la VM. Pour plus d'informations, consultez la section Module vTPM (Virtual Trusted Platform Module).

    4. Si vous souhaitez désactiver la surveillance de l'intégrité, décochez la case Activer la surveillance de l'intégrité. La surveillance de l'intégrité vous permet de surveiller l'intégrité du démarrage de vos VM protégées à l'aide de Cloud Monitoring. Pour plus d'informations, consultez la section Surveillance de l'intégrité.

  4. Pour créer la VM, cliquez sur Créer.

gcloud

Exécutez la commande compute images list pour afficher la liste des images Windows Server disponibles :

gcloud compute images list --project windows-cloud --no-standard-images

Pour déterminer si une image est compatible avec les fonctionnalités de VM protégées, exécutez la commande suivante et recherchez UEFI_COMPATIBLE dans le résultat :

gcloud compute images describe [IMAGE_NAME] --project windows-cloud

[IMAGE_NAME] est le nom de l'image à vérifier pour la compatibilité des fonctionnalités de VM protégées.

Exécutez la commande compute instances create pour créer une instance et spécifier la famille d'images pour l'une des images publiques Windows Server.

gcloud compute instances create [INSTANCE_NAME] \
    --image-project windows-cloud \
    --image-family [IMAGE_FAMILY] \
    --machine-type [MACHINE_TYPE] \
    --boot-disk-size [BOOT_DISK_SIZE] \
    --boot-disk-type [BOOT_DISK_TYPE]

où :

  • [INSTANCE_NAME] est le nom de la nouvelle instance.
  • [IMAGE_FAMILY] est l'une des familles d'images publiques pour les images Windows Server.
  • [MACHINE_TYPE] est l'un des types de machines disponibles.
  • [BOOT_DISK_SIZE] est la taille du disque de démarrage en Go. Les disques persistants plus volumineux présentent un débit plus élevé.
  • [BOOT_DISK_TYPE] est le type du disque de démarrage pour votre instance. Par exemple, pd-ssd.

Si vous avez choisi une image compatible avec les VM protégées, vous pouvez éventuellement modifier les paramètres de la VM protégée de l'instance à l'aide de l'un des indicateurs suivants :

  • --no-shielded-secure-boot : désactive le démarrage sécurisé. Le démarrage sécurisé permet de protéger vos instances de VM contre les logiciels malveillants et les rootkits opérant au niveau des secteurs de démarrage et du noyau. Pour plus d'informations, consultez la section Démarrage sécurisé.
  • --no-shielded-vtpm : désactive le module vTPM (Virtual Trusted Platform Module). Le module vTPM active le démarrage mesuré, ce qui permet de valider l'intégrité du pré-amorçage et du démarrage de la VM. Pour plus d'informations, consultez la section Module vTPM (Virtual Trusted Platform Module).

  • --no-shielded-integrity-monitoring : désactive la surveillance de l'intégrité. La surveillance de l'intégrité vous permet de surveiller l'intégrité du démarrage de vos instances de VM protégées à l'aide de Cloud Monitoring. Pour plus d'informations, consultez la section Surveillance de l'intégrité.

L'exemple suivant crée une instance de VM protégée Windows 2022 avec le démarrage sécurisé désactivé :

gcloud compute instances create my-instance \
    --image-family windows-2022 --image-project windows-cloud \
    --no-shielded-secure-boot

Go

import (
	"context"
	"fmt"
	"io"

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

// createWndowsServerInstanceExternalIP creates a new Windows Server instance
// that has an external IP address.
func createWndowsServerInstanceExternalIP(
	w io.Writer,
	projectID, zone, instanceName, machineType, sourceImageFamily string,
) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// machineType := "n1-standard-1"
	// sourceImageFamily := "windows-2022"

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

	disk := &computepb.AttachedDisk{
		// Describe the size and source image of the boot disk to attach to the instance.
		InitializeParams: &computepb.AttachedDiskInitializeParams{
			DiskSizeGb: proto.Int64(64),
			SourceImage: proto.String(
				fmt.Sprintf(
					"projects/windows-cloud/global/images/family/%s",
					sourceImageFamily,
				),
			),
		},
		AutoDelete: proto.Bool(true),
		Boot:       proto.Bool(true),
	}

	network := &computepb.NetworkInterface{
		// If you are using a custom VPC network it must be configured
		// to allow access to kms.windows.googlecloud.com.
		// https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server.
		Name: proto.String("global/networks/default"),
		AccessConfigs: []*computepb.AccessConfig{
			{
				Type: proto.String("ONE_TO_ONE_NAT"),
				Name: proto.String("External NAT"),
			},
		},
	}

	inst := &computepb.Instance{
		Name: proto.String(instanceName),
		Disks: []*computepb.AttachedDisk{
			disk,
		},
		MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/%s", zone, machineType)),
		NetworkInterfaces: []*computepb.NetworkInterface{
			network,
		},
		// If you chose an image that supports Shielded VM,
		// you can optionally change the instance's Shielded VM settings.
		// ShieldedInstanceConfig: &computepb.ShieldedInstanceConfig{
		// 	EnableSecureBoot: proto.Bool(true),
		// 	EnableVtpm: proto.Bool(true),
		// 	EnableIntegrityMonitoring: proto.Bool(true),
		// },
	}

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

	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


import com.google.cloud.compute.v1.AccessConfig;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
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.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateWindowsServerInstanceExternalIp {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // projectId - ID or number of the project you want to use.
    String projectId = "your-google-cloud-project-id";

    // zone - Name of the zone you want to use, for example: us-west3-b
    String zone = "europe-central2-b";

    // instanceName - Name of the new machine.
    String instanceName = "instance-name";

    createWindowsServerInstanceExternalIp(projectId, zone, instanceName);
  }

  // Creates a new Windows Server instance that has an external IP address.
  public static void createWindowsServerInstanceExternalIp(String projectId, String zone,
      String instanceName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    // machineType - Machine type you want to create in following format:
    //  *    "zones/{zone}/machineTypes/{type_name}". For example:
    //  *    "zones/europe-west3-c/machineTypes/f1-micro"
    //  *    You can find the list of available machine types using:
    //  *    https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/list
    String machineType = "n1-standard-1";
    // sourceImageFamily - Name of the public image family for Windows Server or SQL Server images.
    //  *    https://cloud.google.com/compute/docs/images#os-compute-support
    String sourceImageFamily = "windows-2022";

    // Instantiates a client.
    try (InstancesClient instancesClient = InstancesClient.create()) {

      AttachedDisk attachedDisk = AttachedDisk.newBuilder()
          // Describe the size and source image of the boot disk to attach to the instance.
          .setInitializeParams(AttachedDiskInitializeParams.newBuilder()
              .setDiskSizeGb(64)
              .setSourceImage(
                  String.format("projects/windows-cloud/global/images/family/%s",
                      sourceImageFamily))
              .build())
          .setAutoDelete(true)
          .setBoot(true)
          .setType(AttachedDisk.Type.PERSISTENT.toString())
          .build();

      Instance instance = Instance.newBuilder()
          .setName(instanceName)
          .setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType))
          .addDisks(attachedDisk)
          .addNetworkInterfaces(NetworkInterface.newBuilder()
              .addAccessConfigs(AccessConfig.newBuilder()
                  .setType("ONE_TO_ONE_NAT")
                  .setName("External NAT")
                  .build())
              // If you're going to use a custom VPC network, it must be configured
              // to allow access to kms.windows.googlecloud.com.
              // https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server.
              .setName("global/networks/default")
              .build())
          // If you chose an image that supports Shielded VM, you can optionally change the
          // instance's Shielded VM settings.
          // .setShieldedInstanceConfig(ShieldedInstanceConfig.newBuilder()
          //    .setEnableSecureBoot(true)
          //    .setEnableVtpm(true)
          //    .setEnableIntegrityMonitoring(true)
          //    .build())
          .build();

      InsertInstanceRequest request = InsertInstanceRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setInstanceResource(instance)
          .build();

      // Wait for the operation to complete.
      Operation operation = instancesClient.insertAsync(request).get(5, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.printf("Error in creating instance %s", operation.getError());
        return;
      }

      System.out.printf("Instance created %s", instanceName);
    }
  }
}

Node.js

/**
 * 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 machineType = 'n1-standard-1';
// const sourceImageFamily = 'windows-2022';

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

async function createWindowsServerInstanceExpernalIP() {
  const instancesClient = new compute.InstancesClient();

  const [response] = await instancesClient.insert({
    instanceResource: {
      name: instanceName,
      disks: [
        {
          // Describe the size and source image of the boot disk to attach to the instance.
          initializeParams: {
            diskSizeGb: '64',
            sourceImage: `projects/windows-cloud/global/images/family/${sourceImageFamily}/`,
          },
          autoDelete: true,
          boot: true,
          type: 'PERSISTENT',
        },
      ],
      machineType: `zones/${zone}/machineTypes/${machineType}`,
      networkInterfaces: [
        {
          accessConfigs: [
            {
              type: 'ONE_TO_ONE_NAT',
              name: 'External NAT',
            },
          ],
          // If you are using a custom VPC network it must be configured to allow access to kms.windows.googlecloud.com.
          // https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server.
          name: 'global/networks/default',
        },
      ],
      // If you chose an image that supports Shielded VM, you can optionally change the instance's Shielded VM settings.
      // "shieldedInstanceConfig": {
      //   "enableSecureBoot": true,
      //   "enableVtpm": true,
      //   "enableIntegrityMonitoring": true
      // },
    },
    project: projectId,
    zone,
  });
  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.');
}

createWindowsServerInstanceExpernalIP();

Python

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_image_from_family(project: str, family: str) -> compute_v1.Image:
    """
    Retrieve the newest image that is part of a given family in a project.

    Args:
        project: project ID or project number of the Cloud project you want to get image from.
        family: name of the image family you want to get image from.

    Returns:
        An Image object.
    """
    image_client = compute_v1.ImagesClient()
    # List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
    newest_image = image_client.get_from_family(project=project, family=family)
    return newest_image


def disk_from_image(
    disk_type: str,
    disk_size_gb: int,
    boot: bool,
    source_image: str,
    auto_delete: bool = True,
) -> compute_v1.AttachedDisk:
    """
    Create an AttachedDisk object to be used in VM instance creation. Uses an image 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_image: source image to use when creating this disk. You must have read access to this disk. This can be one
            of the publicly available images or an image from one of your projects.
            This value uses the following format: "projects/{project_name}/global/images/{image_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 image.
    """
    boot_disk = compute_v1.AttachedDisk()
    initialize_params = compute_v1.AttachedDiskInitializeParams()
    initialize_params.source_image = source_image
    initialize_params.disk_size_gb = disk_size_gb
    initialize_params.disk_type = disk_type
    boot_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.
    boot_disk.auto_delete = auto_delete
    boot_disk.boot = boot
    return boot_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_windows_instance(
    project_id: str,
    zone: str,
    instance_name: str,
    machine_type: str,
    source_image_family: str = "windows-2022",
    network_link: str = "global/networks/default",
    subnetwork_link: str | None = None,
) -> compute_v1.Instance:
    """
    Creates a new Windows Server instance that has only an internal IP address.

    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.
        machine_type: machine type you want to create in following format:
            "zones/{zone}/machineTypes/{type_name}". For example:
            "zones/europe-west3-c/machineTypes/f1-micro"
            You can find the list of available machine types using:
            https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/list
        source_image_family: name of the public image family for Windows Server or SQL Server images.
            https://cloud.google.com/compute/docs/images#os-compute-support
        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}"

    Returns:
        Instance object.
    """
    if subnetwork_link is None:
        subnetwork_link = f"regions/{zone}/subnetworks/default"

    base_image = get_image_from_family(
        project="windows-cloud", family=source_image_family
    )
    disk_type = f"zones/{zone}/diskTypes/pd-standard"
    disks = [disk_from_image(disk_type, 100, True, base_image.self_link, True)]

    # You must verify or configure routes and firewall rules in your VPC network
    # to allow access to kms.windows.googlecloud.com.
    # More information about access to kms.windows.googlecloud.com: https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server

    # Additionally, you must enable Private Google Access for subnets in your VPC network
    # that contain Windows instances with only internal IP addresses.
    # More information about Private Google Access: https://cloud.google.com/vpc/docs/configure-private-google-access#enabling

    instance = create_instance(
        project_id,
        zone,
        instance_name,
        disks,
        machine_type=machine_type,
        network_link=network_link,
        subnetwork_link=subnetwork_link,
        external_access=True,  # Set this to False to disable external IP for your instance
    )
    return instance

REST

Pour créer une instance avec l'API, incluez la propriété initializeParams dans votre demande de création d'instance et spécifiez une image Windows. Par exemple, le corps de votre requête pourrait ressembler à ceci :

instance = {
  "name": "[INSTANCE_NAME]",
  "machineType": "zones/[ZONE]/machineTypes/[MACHINE_TYPE]",
  "disks": [{
      "boot": "true",
      "type": "PERSISTENT",
      "initializeParams": {
         "diskName": "[DISK_NAME]",
         "sourceImage": "https://www.googleapis.com/compute/v1/projects/windows-cloud/global/images/family/[IMAGE_FAMILY]",
         "diskSizeGb": "[BOOT_DISK_SIZE]",
         "diskType": "[BOOT_DISK_TYPE]",
       }
    }],
  "networkInterfaces": [{
    "accessConfigs": [{
      "type": "ONE_TO_ONE_NAT",
      "name": "External NAT"
     }],
    "network": "global/networks/default"
  }],
  "serviceAccounts": [{
       "email": DEFAULT_SERVICE_EMAIL,
       "scopes": DEFAULT_SCOPES
  }]
}

où :

  • [INSTANCE_NAME] est le nom de la nouvelle instance.
  • [IMAGE_FAMILY] est l'une des familles d'images publiques pour les images Windows Server ou SQL Server.
  • [ZONE] est la zone associée à cette instance.
  • [MACHINE_TYPE] est l'un des types de machines disponibles.
  • [BOOT_DISK_SIZE] est la taille du disque de démarrage en Go. Les disques persistants plus volumineux présentent un débit plus élevé.
  • [BOOT_DISK_TYPE] est le type du disque de démarrage pour votre instance. Par exemple, pd-ssd.

Si vous avez choisi une image compatible avec les VM protégées, vous pouvez éventuellement modifier les paramètres de la VM protégée de l'instance en renseignant les éléments suivants dans le corps de la requête booléenne :

  • enableSecureBoot : active ou désactive le démarrage sécurisé. Le démarrage sécurisé permet de protéger vos instances de VM contre les logiciels malveillants et les rootkits opérant au niveau des secteurs de démarrage et du noyau. Pour plus d'informations, consultez la section Démarrage sécurisé.
  • enableVtpm : active ou désactive le module vTPM (Virtual Trusted Platform Module). Le module vTPM active le démarrage mesuré, ce qui permet de valider l'intégrité du préamorçage et du démarrage de la VM. Pour plus d'informations, consultez la section Module vTPM (Virtual Trusted Platform Module).

  • enableIntegrityMonitoring : active ou désactive la surveillance de l'intégrité. Cette fonctionnalité vous permet de surveiller et de valider l'intégrité pendant le démarrage de l'environnement d'exécution de vos instances de VM protégées au moyen de rapports Cloud Monitoring. Pour plus d'informations, consultez la section Surveillance de l'intégrité.

Pour plus d'informations sur la création d'une instance, consultez la documentation de instances.insert().

Une fois que vous avez créé l'instance Windows ou SQL Server, définissez son mot de passe initial afin de pouvoir vous y connecter via RDP.

En outre, vous pouvez associer la VM à un domaine Microsoft AD géré lors de la création ou après la création de la VM. Pour en savoir plus, consultez la section Associer automatiquement une VM Windows à un domaine.

Créer une instance Windows Server utilisant une adresse IP interne pour l'activation

Pour créer une instance Windows Server qui ne dispose que d'une adresse IP interne, vous devez préalablement vérifier ou configurer des routes et des règles de pare-feu dans votre réseau VPC afin d'autoriser l'accès à kms.windows.googlecloud.com. En outre, vous devez activer l'accès privé à Google pour les sous-réseaux de votre réseau VPC qui contiennent des instances Windows ne disposant que d'une adresse IP interne.

gcloud

Lorsque vous créez une instance en utilisant gcloud CLI, vous pouvez utiliser l'option --no-address pour vous assurer qu'aucune adresse IP externe ne lui est attribuée :

gcloud compute instances create [INSTANCE_NAME] --network [NETWORK_NAME] \
 --subnet [SUBNET_NAME] \
 --no-address \
 --zone [ZONE] \
 --image-project windows-cloud \
 --image-family [IMAGE_FAMILY] \
 --machine-type [MACHINE_TYPE] \
 --boot-disk-size [BOOT_DISK_SIZE] \
 --boot-disk-type [BOOT_DISK_TYPE]

Remplacez les espaces réservés suivants par des valeurs valides :

  • [INSTANCE_NAME] est le nom de la nouvelle instance.
  • [SUBNET_NAME] est le nom du sous-réseau du réseau VPC qui sera utilisé par l'instance. Le sous-réseau doit être situé dans la même région que la zone choisie pour l'instance.
  • [IMAGE_FAMILY] est l'une des familles d'images publiques pour les images Windows Server.
  • [MACHINE_TYPE] est l'un des types de machines disponibles.
  • [BOOT_DISK_SIZE] est la taille du disque de démarrage en Go. Les disques persistants plus volumineux présentent un débit plus élevé.
  • [BOOT_DISK_TYPE] est le type du disque de démarrage pour votre instance. Exemple : pd-ssd.

Go

import (
	"context"
	"fmt"
	"io"

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

// createWndowsServerInstanceInternalIP creates a new Windows Server instance
// that has only an internal IP address.
func createWndowsServerInstanceInternalIP(
	w io.Writer,
	projectID, zone, instanceName, machineType, sourceImageFamily, networkLink, subnetworkLink string,
) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// machineType := "n1-standard-1"
	// sourceImageFamily := "windows-2022"
	// networkLink := "global/networks/default"
	// subnetworkLink := "regions/europe-central2/subnetworks/default"

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

	disk := &computepb.AttachedDisk{
		// Describe the size and source image of the boot disk to attach to the instance.
		InitializeParams: &computepb.AttachedDiskInitializeParams{
			DiskSizeGb: proto.Int64(64),
			SourceImage: proto.String(
				fmt.Sprintf(
					"projects/windows-cloud/global/images/family/%s",
					sourceImageFamily,
				),
			),
		},
		AutoDelete: proto.Bool(true),
		Boot:       proto.Bool(true),
	}

	network := &computepb.NetworkInterface{
		// You must verify or configure routes and firewall rules in your VPC network
		// to allow access to kms.windows.googlecloud.com.
		// More information about access to kms.windows.googlecloud.com:
		// https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server

		// Additionally, you must enable Private Google Access for subnets in your VPC network
		// that contain Windows instances with only internal IP addresses.
		// More information about Private Google Access:
		// https://cloud.google.com/vpc/docs/configure-private-google-access#enabling
		Name:       proto.String(networkLink),
		Subnetwork: proto.String(subnetworkLink),
	}

	inst := &computepb.Instance{
		Name: proto.String(instanceName),
		Disks: []*computepb.AttachedDisk{
			disk,
		},
		MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/%s", zone, machineType)),
		NetworkInterfaces: []*computepb.NetworkInterface{
			network,
		},
		// If you chose an image that supports Shielded VM,
		// you can optionally change the instance's Shielded VM settings.
		// ShieldedInstanceConfig: &computepb.ShieldedInstanceConfig{
		// 	EnableSecureBoot: proto.Bool(true),
		// 	EnableVtpm: proto.Bool(true),
		// 	EnableIntegrityMonitoring: proto.Bool(true),
		// },
	}

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

	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


import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
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.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateWindowsServerInstanceInternalIp {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // projectId - ID or number of the project you want to use.
    String projectId = "your-google-cloud-project-id";

    // zone - Name of the zone you want to use, for example: us-west3-b
    String zone = "europe-central2-b";

    // instanceName - Name of the new machine.
    String instanceName = "instance-name";

    // networkLink - 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.
    String networkLink = "global/networks/default";

    // subnetworkLink - Name of the subnetwork you want the new instance to use.
    //  *   This value uses the following format:
    //  *   "regions/{region}/subnetworks/{subnetwork_name}"
    String subnetworkLink = "regions/europe-central2/subnetworks/default";

    createWindowsServerInstanceInternalIp(projectId, zone, instanceName, networkLink,
        subnetworkLink);
  }

  // Creates a new Windows Server instance that has only an internal IP address.
  public static void createWindowsServerInstanceInternalIp(String projectId, String zone,
      String instanceName, String networkLink, String subnetworkLink)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    // machineType - Machine type you want to create in following format:
    //  *    "zones/{zone}/machineTypes/{type_name}". For example:
    //  *    "zones/europe-west3-c/machineTypes/f1-micro"
    //  *    You can find the list of available machine types using:
    //  *    https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/list
    String machineType = "n1-standard-1";
    // sourceImageFamily - Name of the public image family for Windows Server or SQL Server images.
    //  *    https://cloud.google.com/compute/docs/images#os-compute-support
    String sourceImageFamily = "windows-2022";

    // Instantiates a client.
    try (InstancesClient instancesClient = InstancesClient.create()) {

      AttachedDisk attachedDisk = AttachedDisk.newBuilder()
          // Describe the size and source image of the boot disk to attach to the instance.
          .setInitializeParams(AttachedDiskInitializeParams.newBuilder()
              .setDiskSizeGb(64)
              .setSourceImage(
                  String.format("projects/windows-cloud/global/images/family/%s",
                      sourceImageFamily))
              .build())
          .setAutoDelete(true)
          .setBoot(true)
          .setType(AttachedDisk.Type.PERSISTENT.toString())
          .build();

      Instance instance = Instance.newBuilder()
          .setName(instanceName)
          .setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType))
          .addDisks(attachedDisk)
          .addNetworkInterfaces(NetworkInterface.newBuilder()
              // You must verify or configure routes and firewall rules in your VPC network
              // to allow access to kms.windows.googlecloud.com.
              // More information about access to kms.windows.googlecloud.com: https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server

              // Additionally, you must enable Private Google Access for subnets in your VPC network
              // that contain Windows instances with only internal IP addresses.
              // More information about Private Google Access: https://cloud.google.com/vpc/docs/configure-private-google-access#enabling
              .setName(networkLink)
              .setSubnetwork(subnetworkLink)
              .build())
          // If you chose an image that supports Shielded VM, you can optionally change the
          // instance's Shielded VM settings.
          // .setShieldedInstanceConfig(ShieldedInstanceConfig.newBuilder()
          //    .setEnableSecureBoot(true)
          //    .setEnableVtpm(true)
          //    .setEnableIntegrityMonitoring(true)
          //    .build())
          .build();

      InsertInstanceRequest request = InsertInstanceRequest.newBuilder()
          .setProject(projectId)
          .setZone(zone)
          .setInstanceResource(instance)
          .build();

      // Wait for the operation to complete.
      Operation operation = instancesClient.insertAsync(request).get(5, TimeUnit.MINUTES);

      if (operation.hasError()) {
        System.out.printf("Error in creating instance %s", operation.getError());
        return;
      }

      System.out.printf("Instance created %s", instanceName);
    }
  }
}

Node.js

/**
 * 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 machineType = 'n1-standard-1';
// const sourceImageFamily = 'windows-2022';
// const networkLink = 'global/networks/default';
// const subnetworkLink = 'regions/europe-central2/subnetworks/default';

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

async function createWindowsServerInstanceInternalIP() {
  const instancesClient = new compute.InstancesClient();

  const [response] = await instancesClient.insert({
    instanceResource: {
      name: instanceName,
      disks: [
        {
          // Describe the size and source image of the boot disk to attach to the instance.
          initializeParams: {
            diskSizeGb: '64',
            sourceImage: `projects/windows-cloud/global/images/family/${sourceImageFamily}/`,
          },
          autoDelete: true,
          boot: true,
          type: 'PERSISTENT',
        },
      ],
      machineType: `zones/${zone}/machineTypes/${machineType}`,
      networkInterfaces: [
        {
          // You must verify or configure routes and firewall rules in your VPC network
          // to allow access to kms.windows.googlecloud.com.
          // More information about access to kms.windows.googlecloud.com: https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server

          // Additionally, you must enable Private Google Access for subnets in your VPC network
          // that contain Windows instances with only internal IP addresses.
          // More information about Private Google Access: https://cloud.google.com/vpc/docs/configure-private-google-access#enabling
          name: networkLink,
          subnetwork: subnetworkLink,
        },
      ],
      // If you chose an image that supports Shielded VM, you can optionally change the instance's Shielded VM settings.
      // "shieldedInstanceConfig": {
      //   "enableSecureBoot": true,
      //   "enableVtpm": true,
      //   "enableIntegrityMonitoring": true
      // },
    },
    project: projectId,
    zone,
  });
  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.');
}

createWindowsServerInstanceInternalIP();

Python

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_image_from_family(project: str, family: str) -> compute_v1.Image:
    """
    Retrieve the newest image that is part of a given family in a project.

    Args:
        project: project ID or project number of the Cloud project you want to get image from.
        family: name of the image family you want to get image from.

    Returns:
        An Image object.
    """
    image_client = compute_v1.ImagesClient()
    # List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details
    newest_image = image_client.get_from_family(project=project, family=family)
    return newest_image


def disk_from_image(
    disk_type: str,
    disk_size_gb: int,
    boot: bool,
    source_image: str,
    auto_delete: bool = True,
) -> compute_v1.AttachedDisk:
    """
    Create an AttachedDisk object to be used in VM instance creation. Uses an image 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_image: source image to use when creating this disk. You must have read access to this disk. This can be one
            of the publicly available images or an image from one of your projects.
            This value uses the following format: "projects/{project_name}/global/images/{image_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 image.
    """
    boot_disk = compute_v1.AttachedDisk()
    initialize_params = compute_v1.AttachedDiskInitializeParams()
    initialize_params.source_image = source_image
    initialize_params.disk_size_gb = disk_size_gb
    initialize_params.disk_type = disk_type
    boot_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.
    boot_disk.auto_delete = auto_delete
    boot_disk.boot = boot
    return boot_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_windows_instance(
    project_id: str,
    zone: str,
    instance_name: str,
    machine_type: str,
    source_image_family: str = "windows-2022",
    network_link: str = "global/networks/default",
    subnetwork_link: str | None = None,
) -> compute_v1.Instance:
    """
    Creates a new Windows Server instance that has only an internal IP address.

    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.
        machine_type: machine type you want to create in following format:
            "zones/{zone}/machineTypes/{type_name}". For example:
            "zones/europe-west3-c/machineTypes/f1-micro"
            You can find the list of available machine types using:
            https://cloud.google.com/sdk/gcloud/reference/compute/machine-types/list
        source_image_family: name of the public image family for Windows Server or SQL Server images.
            https://cloud.google.com/compute/docs/images#os-compute-support
        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}"

    Returns:
        Instance object.
    """
    if subnetwork_link is None:
        subnetwork_link = f"regions/{zone}/subnetworks/default"

    base_image = get_image_from_family(
        project="windows-cloud", family=source_image_family
    )
    disk_type = f"zones/{zone}/diskTypes/pd-standard"
    disks = [disk_from_image(disk_type, 100, True, base_image.self_link, True)]

    # You must verify or configure routes and firewall rules in your VPC network
    # to allow access to kms.windows.googlecloud.com.
    # More information about access to kms.windows.googlecloud.com: https://cloud.google.com/compute/docs/instances/windows/creating-managing-windows-instances#kms-server

    # Additionally, you must enable Private Google Access for subnets in your VPC network
    # that contain Windows instances with only internal IP addresses.
    # More information about Private Google Access: https://cloud.google.com/vpc/docs/configure-private-google-access#enabling

    instance = create_instance(
        project_id,
        zone,
        instance_name,
        disks,
        machine_type=machine_type,
        network_link=network_link,
        subnetwork_link=subnetwork_link,
        external_access=True,  # Set this to False to disable external IP for your instance
    )
    return instance

Comme cette instance n'a pas d'adresse IP externe, vous ne pouvez pas vous y connecter directement via Internet. Vous pouvez vous connecter à l'instance depuis un autre réseau connecté à votre réseau VPC à l'aide de Cloud Interconnect ou de Cloud VPN. Vous pouvez également vous connecter dans un premier temps à une instance bastion via RDP, puis à l'instance qui ne dispose que d'une adresse IP interne.

En outre, vous pouvez associer la VM à un domaine Microsoft AD géré lors de la création ou après la création de la VM. Pour en savoir plus, consultez la section Associer automatiquement une VM Windows à un domaine.

Configurer l'accès à kms.windows.googlecloud.com

Pour permettre l'activation et le renouvellement des licences Windows, votre réseau VPC doit répondre aux exigences suivantes en matière de routage et de règles de pare-feu.

Exigences de routage

Vos instances Windows doivent pouvoir atteindre kms.windows.googlecloud.com (35.190.247.13) via un routage ayant comme saut suivant la passerelle Internet par défaut. Vous ne pouvez pas activer des instances Windows à l'aide d'une passerelle NAT ou Cloud NAT basée sur une instance, car kms.windows.googlecloud.com rejette les demandes d'activation provenant d'adresses IP non reconnues comme étant des instances Compute Engine.

Vous pouvez utiliser la route par défaut de votre réseau VPC pour acheminer directement le trafic vers kms.windows.googlecloud.com. Si vous supprimez cette route ou si vous envisagez de le faire ultérieurement, vous devez créer une route statique personnalisée dont la destination correspond à l'adresse 35.190.247.13, et dont le saut suivant est défini sur la passerelle internet par défaut :

gcloud compute routes create [ROUTE_NAME] \
    --destination-range=35.190.247.13/32 \
    --network=[NETWORK] \
    --next-hop-gateway=default-internet-gateway

Remplacez [ROUTE_NAME] par le nom que vous souhaitez donner à cette route et [NETWORK] par le nom de votre réseau VPC.

Soit la route par défaut, soit la route statique personnalisée tel que décrit ci-dessus, peuvent permettre aux instances avec des adresses IP externes de communiquer avec kms.windows.googlecloud.com. Si certaines instances Windows ne possèdent pas d'adresse IP externe ou utilisent Cloud NAT, vous devez également activer l'accès privé à Google. Cela permet aux instances ne disposant que d'une adresse IP interne d'envoyer du trafic à l'adresse IP associée à kms.windows.googlecloud.com (35.190.247.13).

Exigences relatives aux règles de pare-feu

La règle de pare-feu implicite d'autorisation du trafic sortant permet aux instances d'effectuer des requêtes sortantes et de recevoir les réponses renvoyées. Vos instances Windows peuvent donc communiquer avec kms.windows.googlecloud.com, sous réserve que vous n'ayez pas créé une règle de pare-feu personnalisée interdisant le trafic sortant.

Si vous souhaitez créer des règles de pare-feu personnalisées, nous vous conseillons fortement de créer une règle d'autorisation du trafic sortant de priorité élevée autorisant explicitement la communication avec l'adresse 35.190.247.13. Cela vous permet d'éviter de bloquer accidentellement les activations de Windows lorsque vous modifiez des règles de pare-feu.

Les exemples gcloud suivants créent la règle de sortie autorisée recommandée avec la priorité la plus élevée :

gcloud compute firewall-rules create [RULE_NAME] \
    --direction=EGRESS \
    --network=[NETWORK] \
    --action=ALLOW \
    --rules=tcp:1688 \
    --destination-ranges=35.190.247.13/32 \
    --priority=0

Remplacez [RULE_NAME] par le nom que vous souhaitez donner à cette règle de pare-feu et [NETWORK] par le nom de votre réseau VPC.

Vérifier qu'une instance a démarré correctement

Les instances Windows nécessitent un temps de démarrage plus long en raison du processus sysprep. Il est possible que la console Google Cloud indique que l'instance est en cours d'exécution alors que le processus sysprep n'est pas encore terminé. Pour vérifier si l'instance a bien démarré et qu'elle est prête à être utilisée, vérifiez la sortie du port série avec la commande suivante :

gcloud compute instances get-serial-port-output [INSTANCE_NAME]

[INSTANCE_NAME] correspond au nom de l'instance à vérifier.

...[snip]...
Running schtasks with arguments /run /tn GCEStartup
-->  SUCCESS: Attempted to run the scheduled task "GCEStartup".
-------------------------------------------------------------
Instance setup finished. [INSTANCE_NAME] is ready to use.
-------------------------------------------------------------

Activer et désactiver les fonctionnalités d'instance Windows

Si vous possédez des instances Windows avec une version d'image v20170509 ou ultérieure, ou une version de l'agent 4.1.0 ou ultérieure, vous pouvez définir la configuration de l'instance dans un fichier de configuration, ou dans des métadonnées personnalisées de l'instance ou du projet. Le fichier de configuration est au format INI et se trouve à l'emplacement suivant :

C:\Program Files\Google\Compute Engine\instance_configs.cfg

Le système ignore les paramètres de configuration en appliquant l'ordre de priorité suivant, qui part de la priorité la plus élevée pour aller à la priorité la plus basse :

  1. Paramètres de configuration définis dans le fichier de configuration
  2. Paramètres de configuration définis dans les métadonnées personnalisées au niveau de l'instance
  3. Paramètres de configuration définis dans les métadonnées personnalisées au niveau du projet

Par exemple, si vous pouvez activer la fonctionnalité accountManager dans un fichier de configuration, votre instance ignore les paramètres de l'instance que vous définissez dans les métadonnées personnalisées pour désactiver cette fonctionnalité.

L'un des avantages de la définition de ces paramètres dans le fichier de configuration est qu'ils persistent lorsque vous créez une image personnalisée pour une instance Windows Server. Les métadonnées personnalisées au niveau de l'instance ne persistent pas au-delà de la durée de vie de l'instance.

Vous pouvez désactiver différentes fonctionnalités d'instance Windows à l'aide des exemples suivants.

Désactiver le gestionnaire de comptes

La désactivation du gestionnaire de comptes désactive également la réinitialisation des mots de passe à l'aide de Google Cloud CLI ou de la console Google Cloud :

  • Fichier de configuration :

    [accountManager]
    disable=true
    
  • Dans les métadonnées personnalisées, définissez disable-account-manager sur true.

Désactiver le gestionnaire d'adresses

  • Entrée du fichier de configuration :

    [addressManager]
    disable=true
    
  • Dans les métadonnées personnalisées, définissez disable-address-manager sur true.

Clustering de basculement Windows Server

Activer l'agent de clustering de basculement Windows Server :

  • Entrée du fichier de configuration :

    [wsfc]
    enable=true
    
  • Dans les métadonnées personnalisées, définissez enable-wsfc sur true.

Utiliser plusieurs équilibreurs de charge internes

Indiquez l'adresse IP de l'instance d'équilibrage de charge interne pour le clustering de basculement. Il s'agit d'une configuration avancée ; il n'est pas nécessaire de la définir pour un cluster de basculement dédié.

Normalement, une instance d'équilibrage de charge interne est utilisée pour diriger le trafic réseau vers une instance de VM à la fois. Si vous ajoutez une deuxième instance d'équilibrage de charge interne qui utilise les instances de VM en clustering de basculement dans le cadre d'un backend de site Web avec équilibrage de charge, vous disposez de deux adresses IP d'équilibrage de charge interne. Si le clustering de basculement utilise l'adresse IP 10.0.0.10 et que l'équilibreur de charge du site Web utilise 10.0.0.11, vous devez spécifier l'adresse IP de l'équilibreur de charge que vous utilisez pour le clustering de basculement. Cela clarifiera l'adresse utilisée pour le cluster.

  • Entrée du fichier de configuration :

    [wsfc]
    addresses=10.0.0.10
    
  • Dans les métadonnées personnalisées, définissez wsfc-addrs sur 10.0.0.10.

Modifier le port de l'agent de clustering

Définissez le port de l'agent de clustering de basculement. Le port par défaut est 59998. Vous ne devez spécifier un port que si vous souhaitez utiliser un port différent :

  • Entrée du fichier de configuration :

    [wsfc]
    port=12345
    
  • Dans les métadonnées personnalisées, définissez wsfc-agent-port sur le numéro de port.

Notes sur la version de l'image

Les anciennes images n'utilisent pas de fichier de configuration et ne comportent qu'un sous-ensemble de fonctionnalités. Les versions d'image entre la version v20160112 et la version v20170509 ou la version de l'agent Windows entre 3.2.1.0 et 4.0.0 nécessitent l'utilisation des valeurs de métadonnées personnalisées suivantes :

  • Définissez disable-account-manager sur true dans les métadonnées de l'instance pour désactiver le gestionnaire de comptes.
  • Définissez disable-address-manager sur true dans les métadonnées de l'instance pour désactiver le gestionnaire d'adresses.

Étapes suivantes