Crea un'istanza VM con un nome host personalizzato

Quando crei un'istanza di una macchina virtuale (VM), Google Cloud crea un nome DNS interno a partire dal nome della VM. A meno che non specifichi un nome host personalizzato, Google Cloud utilizza il nome DNS interno creato automaticamente come nome host che fornisce alla VM.

Puoi creare una VM con un nome host personalizzato specificando un nome DNS completo. I nomi host personalizzati sono utili per mantenere convenzioni o supportare i requisiti per le applicazioni che si aspettano un determinato nome host.

Anche quando specifichi un nome host personalizzato, Google Cloud crea il nome DNS interno di Compute Engine. Puoi connetterti alla VM utilizzando questo record DNS interno creato automaticamente. Il record DNS interno si risolve nel nome DNS interno e non nel nome host personalizzato. Con i nomi host personalizzati, devi comunque creare un record DNS corrispondente nella zona appropriata, ad esempio utilizzando Cloud DNS.

Prima di iniziare

  • Se non l'hai ancora fatto, configura l'autenticazione. L'autenticazione è il processo mediante il quale viene verificata l'identità per l'accesso ai servizi e alle API Google Cloud. Per eseguire codice o esempi da un ambiente di sviluppo locale, puoi autenticarti in Compute Engine nel seguente modo.

    Seleziona la scheda relativa a come prevedi di utilizzare gli esempi in questa pagina:

    Console

    Quando utilizzi la console Google Cloud per accedere ai servizi e alle API di Google Cloud, non devi configurare l'autenticazione.

    gcloud

    1. Installa Google Cloud CLI, quindi initialize eseguendo questo comando:

      gcloud init
    2. Imposta una regione e una zona predefinite.

    Terraform

    Per utilizzare gli esempi Terraform in questa pagina da un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura Credenziali predefinite dell'applicazione con le tue credenziali utente.

    1. Installa Google Cloud CLI.
    2. Per initialize gcloud CLI, esegui questo comando:

      gcloud init
    3. Crea credenziali di autenticazione locali per il tuo Account Google:

      gcloud auth application-default login

    Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

    Go

    Per utilizzare gli esempi Go in questa pagina da un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura Credenziali predefinite dell'applicazione con le tue credenziali utente.

    1. Installa Google Cloud CLI.
    2. Per initialize gcloud CLI, esegui questo comando:

      gcloud init
    3. Crea credenziali di autenticazione locali per il tuo Account Google:

      gcloud auth application-default login

    Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

    Java

    Per utilizzare gli esempi Java in questa pagina da un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura Credenziali predefinite dell'applicazione con le tue credenziali utente.

    1. Installa Google Cloud CLI.
    2. Per initialize gcloud CLI, esegui questo comando:

      gcloud init
    3. Crea credenziali di autenticazione locali per il tuo Account Google:

      gcloud auth application-default login

    Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

    Node.js

    Per utilizzare gli esempi Node.js in questa pagina da un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura Credenziali predefinite dell'applicazione con le tue credenziali utente.

    1. Installa Google Cloud CLI.
    2. Per initialize gcloud CLI, esegui questo comando:

      gcloud init
    3. Crea credenziali di autenticazione locali per il tuo Account Google:

      gcloud auth application-default login

    Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

    Python

    Per utilizzare gli esempi Python in questa pagina da un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura Credenziali predefinite dell'applicazione con le tue credenziali utente.

    1. Installa Google Cloud CLI.
    2. Per initialize gcloud CLI, esegui questo comando:

      gcloud init
    3. Crea credenziali di autenticazione locali per il tuo Account Google:

      gcloud auth application-default login

    Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.

    REST

    Per utilizzare gli esempi di API REST in questa pagina in un ambiente di sviluppo locale, devi utilizzare le credenziali che fornisci a gcloud CLI.

      Installa Google Cloud CLI, quindi initialize eseguendo questo comando:

      gcloud init

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per creare una VM con un nome host personalizzato, chiedi all'amministratore di concederti il ruolo IAM Amministratore istanze Compute (v1) (roles/compute.instanceAdmin.v1) per il progetto. Per saperne di più sulla concessione dei ruoli, consulta Gestire l'accesso.

Questo ruolo predefinito contiene le autorizzazioni necessarie per creare una VM con un nome host personalizzato. Per visualizzare le autorizzazioni esatte necessarie, espandi la sezione Autorizzazioni richieste:

Autorizzazioni obbligatorie

Per creare una VM con un nome host personalizzato sono necessarie le seguenti autorizzazioni:

  • compute.instances.create sul progetto
  • Per utilizzare un'immagine personalizzata per creare la VM: compute.images.useReadOnly nell'immagine
  • Per utilizzare uno snapshot per creare la VM: compute.snapshots.useReadOnly nello snapshot
  • Per utilizzare un modello di istanza per creare la VM: compute.instanceTemplates.useReadOnly sul modello di istanza
  • Per assegnare una rete legacy alla VM: compute.networks.use sul progetto
  • Per specificare un indirizzo IP statico per la VM: compute.addresses.use sul progetto
  • Per assegnare un indirizzo IP esterno alla VM quando utilizzi una rete legacy: compute.networks.useExternalIp sul progetto
  • Per specificare una subnet per la tua VM: compute.subnetworks.use sul progetto o nella subnet scelta
  • Per assegnare un indirizzo IP esterno alla VM quando utilizzi una rete VPC: compute.subnetworks.useExternalIp sul progetto o nella subnet scelta
  • Per impostare i metadati dell'istanza VM per la VM: compute.instances.setMetadata sul progetto
  • Per impostare i tag per la VM: compute.instances.setTags sulla VM
  • Per impostare le etichette per la VM: compute.instances.setLabels sulla VM
  • Per impostare un account di servizio per la VM da utilizzare: compute.instances.setServiceAccount sulla VM
  • Per creare un nuovo disco per la VM: compute.disks.create sul progetto
  • Per collegare un disco esistente in modalità di sola lettura o lettura/scrittura: compute.disks.use sul disco
  • Per collegare un disco esistente in modalità di sola lettura: compute.disks.useReadOnly sul disco

Potresti anche essere in grado di ottenere queste autorizzazioni con i ruoli personalizzati o altri ruoli predefiniti.

Limitazioni

  • Devi configurare manualmente il record DNS per il tuo nome host personalizzato. I nomi host personalizzati non vengono risolti dai record creati automaticamente forniti dal DNS interno di Compute Engine. Puoi utilizzare uno qualsiasi dei seguenti per ospitare il record DNS per il nome host personalizzato:

  • Non puoi modificare un nome host personalizzato dopo aver creato la VM.

Sistemi operativi supportati

I nomi host personalizzati vengono impostati nell'ambiente guest utilizzando gli hook di uscita dhclient su Linux. I sistemi operativi Linux che non supportano gli hook di uscita dhclient o non utilizzano dhclient potrebbero non avere il nome host corretto.

Per l'elenco completo delle versioni del sistema operativo che supportano i nomi host personalizzati, consulta la sezione relativa al supporto dell'ambiente ospite in Dettagli del sistema operativo.

Convenzione di denominazione

I nomi host personalizzati devono essere conformi ai requisiti RFC 1035 per i nomi host validi. Per soddisfare questi requisiti, i nomi host personalizzati devono soddisfare le seguenti specifiche di formato:

  • Il nome host contiene almeno due etichette descritte come segue:
    • Ogni etichetta contiene espressioni regolari che includono solo questi caratteri: [a-z]([-a-z0-9]*[a-z0-9])?.
    • Le etichette sono concatenate con un punto.
    • Ogni etichetta ha una lunghezza compresa tra 1 e 63 caratteri.
  • Il nome host non deve superare i 253 caratteri.

Non valido: contiene una singola etichetta

my-host1234

Valido: contiene tre etichette concatenate da punti

my-host1234.example.com

Crea una VM con un nome host personalizzato

Console

  1. Nella console Google Cloud, vai alla pagina Crea un'istanza.

    Vai a Crea un'istanza

  2. Specifica un nome per la VM. Per ulteriori informazioni, consulta la convenzione di denominazione delle risorse.

  3. Espandi la sezione Opzioni avanzate, quindi segui questi passaggi:

    1. Espandi la sezione Networking.
    2. Nel campo Hostname (Nome host), specifica il nome host personalizzato.
  4. Se necessario, apporta ulteriori personalizzazioni della VM.

  5. Per creare e avviare la VM, fai clic su Crea.

Passaggio successivo: configura i tuoi record DNS. Per ulteriori informazioni, consulta Gestione dei record.

gcloud

Utilizzando Google Cloud CLI, segui le istruzioni per creare un'istanza da un'immagine o da un snapshot, aggiungi il flag --hostname e utilizza il comando gcloud compute instances create come segue:

gcloud compute instances create VM_NAME \
    --hostname=HOST_NAME

Sostituisci quanto segue:

  • VM_NAME: il nome della VM
  • HOST_NAME: il nome host del dominio completo che vuoi assegnare

Ad esempio, per creare una VM myinstance con il nome host personalizzato test.example.com, esegui questo comando:

gcloud compute instances create myinstance \
    --hostname=test.example.com

Passaggio successivo: configura i tuoi record DNS. Per ulteriori informazioni, consulta Gestione dei record.

Terraform

Puoi utilizzare una risorsa Terraform per creare un'istanza con un nome host personalizzato utilizzando l'argomento hostname.


resource "google_compute_instance" "custom_hostname_instance" {
  name         = "custom-hostname-instance-name"
  machine_type = "f1-micro"
  zone         = "us-central1-c"

  # Set a custom hostname below
  hostname = "hashicorptest.com"

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
    }
  }
  network_interface {
    # A default network is created for all GCP projects
    network = "default"
    access_config {
    }
  }
}
Per generare il codice Terraform, puoi utilizzare il componente Codice equivalente nella console Google Cloud.
  1. Nella console Google Cloud, vai alla pagina Istanze VM.

    Vai a Istanze VM

  2. Fai clic su Crea istanza.
  3. Specifica i parametri desiderati.
  4. Nella parte superiore o inferiore della pagina, fai clic su Codice equivalente e poi sulla scheda Terraform per visualizzare il codice Terraform.

Passaggio successivo: configura i tuoi record DNS. Per ulteriori informazioni, consulta Gestione dei record.

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

// createInstanceWithCustomHostname creates an instance with custom hostname.
func createInstanceWithCustomHostname(w io.Writer, projectID, zone, instanceName, hostname, machineType, sourceImage, networkName string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// hostname := "host.example.com" // Custom hostnames must conform to RFC 1035 requirements for valid hostnames.
	// machineType := "n1-standard-1"
	// sourceImage := "projects/debian-cloud/global/images/family/debian-10"
	// networkName := "global/networks/default"

	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),
			// Custom hostnames are not resolved by the automatically created records
			// provided by Compute Engine internal DNS.
			// You must manually configure the DNS record for your custom hostname.
			Hostname: proto.String(hostname),
			Disks: []*computepb.AttachedDisk{
				{
					// Describe the size and source image of the boot disk to attach to the instance.
					InitializeParams: &computepb.AttachedDiskInitializeParams{
						DiskSizeGb:  proto.Int64(10),
						SourceImage: proto.String(sourceImage),
					},
					AutoDelete: proto.Bool(true),
					Boot:       proto.Bool(true),
					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
				},
			},
			MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/%s", zone, machineType)),
			NetworkInterfaces: []*computepb.NetworkInterface{
				{
					// Use the network interface provided in the networkName argument.
					Name: proto.String(networkName),
				},
			},
		},
	}

	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 CreateInstanceWithCustomHostname {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // hostName: Custom hostname of the new VM instance.
    // *    Custom hostnames must conform to RFC 1035 requirements for valid hostnames.
    String project = "your-project-id";
    String zone = "zone-name"; // eg: "us-central1-a"
    String instanceName = "instance-name";
    String hostName = "host.example.com";
    createInstanceWithCustomHostname(project, zone, instanceName, hostName);
  }

  // Creates an instance with custom hostname.
  public static void createInstanceWithCustomHostname(String projectId, String zone,
      String instanceName, String hostName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    //  machineType - Machine type for the VM instance specified in the 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 by using this gcloud command:
    //  *    $ gcloud compute machine-types list
    //  sourceImage - Path of the disk image you want to use for your boot
    //  *    disk. This image can be one of the public images
    //  *    eg: "projects/...
    //  *    or a private image you have access to.
    //  *    You can check the list of available public images using:
    //  *    $ gcloud compute images list
    //  networkName - Name of the network you want the new instance to use.
    //  *    For example: global/networks/default - if you want to use the default network.
    String machineType = "n1-standard-1";
    String sourceImage = String.format("projects/%s/global/images/family/%s", "debian-cloud",
        "debian-11");
    String networkName = "global/networks/default";

    try (InstancesClient instancesClient = InstancesClient.create()) {
      System.out.printf("Creating the %s instance in %s with hostname %s...", instanceName, zone,
          hostName);

      AttachedDisk disk =
          AttachedDisk.newBuilder()
              .setBoot(true)
              .setAutoDelete(true)
              .setType(AttachedDisk.Type.PERSISTENT.toString())
              .setInitializeParams(
                  // Describe the size and source image of the boot disk to attach to the instance.
                  AttachedDiskInitializeParams.newBuilder()
                      .setSourceImage(sourceImage)
                      .setDiskSizeGb(10).build())
              .build();

      // Use the network interface provided in the networkName argument.
      NetworkInterface networkInterface = NetworkInterface.newBuilder()
          .setName(networkName)
          .build();

      Instance instanceResource = Instance.newBuilder()
          // Custom hostnames are not resolved by the automatically created records
          // provided by Compute Engine internal DNS.
          // You must manually configure the DNS record for your custom hostname.
          .setName(instanceName)
          .setHostname(hostName)
          .addDisks(disk)
          .setMachineType(String.format("zones/%s/machineTypes/%s", zone, machineType))
          .addNetworkInterfaces(networkInterface).build();

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

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

      if (response.hasError()) {
        System.out.printf("Instance creation failed for instance: %s ; Response: %s ! ! ",
            instanceName, response);
        return;
      }
      System.out.printf("Instance created : %s", instanceName);
      System.out.printf("Operation Status for instance %s is %s: ", instanceName,
          response.getStatus());
    }

  }

}

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 hostname = 'host.example.com'
// const machineType = 'n1-standard-1';
// const sourceImage = 'projects/debian-cloud/global/images/family/debian-10';
// const networkName = 'global/networks/default';

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

// Create a new instance with the values provided above in the specified project and zone.
async function createInstanceWithCustomHostname() {
  const instancesClient = new compute.InstancesClient();

  console.log(
    `Creating the ${instanceName} instance in ${zone} with hostname ${hostname}...`
  );

  const [response] = await instancesClient.insert({
    instanceResource: {
      name: instanceName,
      // Custom hostnames are not resolved by the automatically created records
      // provided by Compute Engine internal DNS.
      // You must manually configure the DNS record for your custom hostname.
      hostname,
      disks: [
        {
          // Describe the size and source image of the boot disk to attach to the instance.
          initializeParams: {
            diskSizeGb: '10',
            sourceImage,
          },
          autoDelete: true,
          boot: true,
          type: 'PERSISTENT',
        },
      ],
      machineType: `zones/${zone}/machineTypes/${machineType}`,
      networkInterfaces: [
        {
          // Use the network interface provided in the networkName argument.
          name: networkName,
        },
      ],
    },
    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.');
}

createInstanceWithCustomHostname();

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_instance_custom_hostname(
    project_id: str, zone: str, instance_name: str, hostname: str
) -> compute_v1.Instance:
    """
    Create a new VM instance with Debian 10 operating system and a custom hostname.

    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.
        hostname: the hostname you want to use for the new instance.

    Returns:
        Instance object.
    """
    newest_debian = get_image_from_family(project="debian-cloud", family="debian-11")
    disk_type = f"zones/{zone}/diskTypes/pd-standard"
    disks = [disk_from_image(disk_type, 10, True, newest_debian.self_link)]
    instance = create_instance(
        project_id, zone, instance_name, disks, custom_hostname=hostname
    )
    return instance

REST

Segui le istruzioni dell'API per creare un'istanza da un'immagine o uno snapshot e specifica il campo hostname nel corpo della richiesta.

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances

{
 "name": "VM_NAME",
 "hostname": "HOST_NAME",
 ...
}

Sostituisci quanto segue:

  • PROJECT_ID: il tuo ID progetto
  • ZONE: la zona in cui vuoi creare la VM
  • VM_NAME: il nome della VM
  • HOST_NAME: il nome host del dominio completo che vuoi assegnare

Verifica il nome host personalizzato

Per le VM Linux, puoi verificare il nome host eseguendo il comando hostname -f sulla VM.

Puoi anche verificare il nome host personalizzato utilizzando la console Google Cloud o Google Cloud CLI.

Console

  1. Per visualizzare il nome host personalizzato per la tua VM, vai alla pagina Istanze VM.

    Vai a Istanze VM

  2. Fai clic sul nome dell'istanza per aprire la pagina Dettagli istanza VM.

  3. Esamina la sezione Nome host. Il campo Hostname (Nome host) è visibile solo se è stato impostato un nome host personalizzato.

    Pagina delle istanze VM che mostra il nome host.

gcloud

Per visualizzare il nome host personalizzato per la tua VM utilizzando gcloud compute, utilizza il sottocomando instances describe con un flag --format per filtrare l'output. Sostituisci VM_NAME con il nome della VM.

gcloud compute instances describe VM_NAME \
    --format='get(hostname)'

Ad esempio, per visualizzare il nome host personalizzato per una VM denominata myinstance, esegui questo comando.

gcloud compute instances describe myinstance \
    --format='get(hostname)'

L'output potrebbe essere simile al seguente:

test.example.com

Se non è impostato un nome host personalizzato, l'output per questo comando è vuoto.

Passaggi successivi