Configura indirizzi IP esterni statici

Puoi assegnare indirizzi IP esterni statici alla tua macchina virtuale (VM) di Compute Engine. Puoi anche cambiare, elencare e rilasciare indirizzi IP statici per il tuo delle VM in esecuzione. Per prenotare un indirizzo IP esterno statico, consulta Riserva un indirizzo IP esterno statico.

Gli indirizzi IP esterni possono essere statici o temporanei. Se una VM richiede un indirizzo IP esterno fisso che non cambia, esegui la seguenti:

  1. Ottieni un indirizzo IP esterno statico. Puoi prenotare un nuovo IP esterno o promuovere indirizzi IP esterni temporanei esistenti.
  2. Assegna l'indirizzo IP prenotato a una VM esistente o assegnalo durante la creazione una nuova VM.

Se hai bisogno di un indirizzo IP statico sulla piattaforma Compute Engine interna rete, vedi Prenota un indirizzo IP interno statico.

Prima di iniziare

  • Ulteriori informazioni sugli indirizzi IP.
  • Informazioni quote e limiti per gli indirizzi IP esterni statici.
  • Informazioni prezzi degli indirizzi IP esterni.
  • Se non l'hai già fatto, configura l'autenticazione. Autenticazione è Il processo di verifica dell'identità per l'accesso ai servizi e alle API di Google Cloud. Per eseguire codice o esempi da un ambiente di sviluppo locale, puoi eseguire l'autenticazione Compute Engine come segue.

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

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

      gcloud init
    2. Set a default region and zone.
    3. Terraform

      Per utilizzare gli esempi di Terraform in questa pagina in un ambiente dell'ambiente di sviluppo, installare e inizializzare 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, vedi Set up authentication for a local development environment.

      REST

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

        Installa Google Cloud CLI, quindi initialize eseguendo questo comando:

        gcloud init

      Per ulteriori informazioni, vedi Esegui l'autenticazione per l'utilizzo di REST nella documentazione sull'autenticazione di Google Cloud.

Ruoli obbligatori

Per ottenere le autorizzazioni necessarie per configurare e gestire gli indirizzi IP statici, chiedi all'amministratore di concederti i seguenti ruoli IAM sul tuo progetto:

Per saperne di più sulla concessione dei ruoli, consulta Gestire l'accesso.

Questi ruoli predefiniti le autorizzazioni necessarie per configurare e gestire gli indirizzi IP statici. Per vedere le autorizzazioni esatte obbligatorie, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

Per configurare e gestire gli indirizzi IP statici sono necessarie le seguenti autorizzazioni:

  • compute.instances.update sull'istanza VM
  • compute.instances.updateNetworkInterface sull'istanza VM
  • compute.instances.addAccessConfig sull'istanza VM
  • compute.instances.deleteAccessConfig sull'istanza VM
  • compute.networks.list sulla rete
  • compute.subnetworks.use sulla subnet
  • compute.subnetworks.list sulla subnet
  • Per creare le VM:
    • compute.instances.create nel progetto
    • Per utilizzare un'immagine personalizzata per creare la VM: compute.images.useReadOnly sull'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 nel modello di istanza
    • Per assegnare una rete legacy alla VM,: compute.networks.use nel progetto
    • Per specificare un indirizzo IP statico per la VM: compute.addresses.use nel progetto
    • Per assegnare un indirizzo IP esterno alla VM quando utilizzi una rete legacy: compute.networks.useExternalIp nel progetto
    • Per specificare una subnet per la VM: compute.subnetworks.use nel progetto o nella subnet scelta
    • Per assegnare un indirizzo IP esterno alla VM quando utilizzi una rete VPC,: compute.subnetworks.useExternalIp nel progetto o nella subnet scelta
    • Per impostare i metadati dell'istanza VM per la VM: compute.instances.setMetadata nel 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 che la VM deve utilizzare: compute.instances.setServiceAccount sulla VM
    • Per creare un nuovo disco per la VM: compute.disks.create nel 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 riuscire a ottenere queste autorizzazioni con ruoli personalizzati e altri ruoli predefiniti.

Limitazioni

  • Solo una risorsa alla volta può usare un indirizzo IP esterno statico.

  • Non è possibile verificare se un indirizzo IP è statico o temporaneo dopo è stato assegnato a una risorsa. Puoi confrontare l'indirizzo IP con l'elenco di indirizzi IP esterni statici riservati al progetto. Utilizza la Sottocomando gcloud compute addresses list per visualizzare un elenco di indirizzi IP esterni statici disponibili progetto.

  • Ogni VM può avere più interfacce di rete, e a ciascuna interfaccia possono essere assegnati i seguenti indirizzi IP:

    • Un indirizzo IPv4 interno (obbligatorio)
    • Un indirizzo IPv4 esterno
    • Un intervallo di indirizzi IPv6 /96, interno o esterno, ma non entrambi
  • Non puoi modificare il nome di un indirizzo IP statico.

  • Gli indirizzi IP esterni assegnati esistono nello stesso host fisico della VM ed esistono nella stessa regione della VM per tutti gli scopi, inclusi per routing, latenza e prezzi. Ciò vale indipendentemente geolocalizzazione su internet informazioni.

Nota:le interfacce di rete possono ricevere traffico da più regole di forwarding, che potrebbero gestire altri indirizzi IP esterni. Qualsiasi di indirizzi IP esterni può fare riferimento a un'interfaccia di rete tramite regole di forwarding, ma a ciascuna interfaccia di rete può essere assegnato un solo un indirizzo IPv4 esterno e un intervallo di indirizzi IPv6 /96 esterno.

Per ulteriori informazioni sul bilanciamento del carico e sulle regole di forwarding, consulta il bilanciamento del carico documentazione.

Visualizza gli indirizzi IP esterni statici disponibili

Per elencare gli indirizzi IP esterni statici che hai prenotato per il tuo seguire questi passaggi.

Console

  1. Nella console Google Cloud, vai alla pagina Indirizzi IP.

    Vai a indirizzi IP

  2. Fai clic su Indirizzi IP esterni.

gcloud

Usa il comando gcloud compute addresses list:

  • Per elencare tutti gli indirizzi IP, utilizza il seguente comando:

    gcloud compute addresses list
  • Per elencare tutti gli indirizzi IP globali, utilizza il seguente comando:

    gcloud compute addresses list --global
  • Per elencare tutti gli indirizzi IP a livello di regione in una determinata regione, utilizza quanto segue :

    gcloud compute addresses list \
        --regions=REGION
    

    Sostituisci REGION con la regione che vuoi per elencare gli indirizzi. Puoi elencare gli indirizzi di più regioni in base a specificando nomi delle regioni separati da virgole:

    gcloud compute addresses list \
        --regions=REGION1,REGION2,..REGION_n_
    

API

  • Per elencare gli indirizzi IPv4 o IPv6 a livello di regione, chiama il metodo Metodo addresses.list:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/addresses
    

    Sostituisci quanto segue:

    • PROJECT_ID: l'ID progetto per questa richiesta
    • REGION: il nome della regione per questo richiesta
  • Per elencare tutti gli indirizzi in tutte le regioni, chiama il Metodo addresses.aggregatedList:

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/aggregated/addresses
    
  • Per elencare gli indirizzi IPv4 o IPv6 globali, chiama il metodo Metodo globalAddresses.list:

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

    Sostituisci quanto segue:

    PROJECT_ID: l'ID progetto per questa richiesta

Vai

import (
	"context"
	"fmt"
	"io"

	compute "cloud.google.com/go/compute/apiv1"
	"google.golang.org/api/iterator"

	"cloud.google.com/go/compute/apiv1/computepb"
)

// listRegionalExternal retrieves list external IP addresses in Google Cloud Platform region.
func listRegionalExternal(w io.Writer, projectID, region string) ([]*computepb.Address, error) {
	// projectID := "your_project_id"
	// region := "europe-west3"

	ctx := context.Background()
	// Create the service client.
	addressesClient, err := compute.NewAddressesRESTClient(ctx)
	if err != nil {
		return nil, err
	}
	defer addressesClient.Close()

	// Build the request.
	req := &computepb.ListAddressesRequest{
		Project: projectID,
		Region:  region,
	}

	// List the addresses.
	it := addressesClient.List(ctx, req)

	// Iterate over the results.
	var addresses []*computepb.Address
	for {
		address, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, err
		}
		addresses = append(addresses, address)
	}

	// Print the addresses.
	fmt.Fprint(w, "Fetched addresses: \n")
	for _, address := range addresses {
		fmt.Fprintf(w, "%s\n", *address.Name)
	}

	return addresses, nil
}

// listGlobalExternal retrieves list external global IP addresses in Google Cloud Platform.
func listGlobalExternal(w io.Writer, projectID string) ([]*computepb.Address, error) {
	// projectID := "your_project_id"

	ctx := context.Background()
	// Create the service client.
	addressesClient, err := compute.NewGlobalAddressesRESTClient(ctx)
	if err != nil {
		return nil, err
	}
	defer addressesClient.Close()

	// Build the request.
	req := &computepb.ListGlobalAddressesRequest{
		Project: projectID,
	}

	// List the addresses.
	it := addressesClient.List(ctx, req)

	// Iterate over the results.
	var addresses []*computepb.Address
	for {
		address, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, err
		}
		addresses = append(addresses, address)
	}

	// Print the addresses.
	fmt.Fprint(w, "Fetched addresses: \n")
	for _, address := range addresses {
		fmt.Fprintf(w, "%s\n", *address.Name)
	}

	return addresses, nil
}

Java


import com.google.cloud.compute.v1.Address;
import com.google.cloud.compute.v1.AddressesClient;
import com.google.cloud.compute.v1.GlobalAddressesClient;
import com.google.cloud.compute.v1.ListAddressesRequest;
import com.google.cloud.compute.v1.ListGlobalAddressesRequest;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class ListStaticExternalIp {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Region where the VM and IP is located.
    String region = "your-region-id";

    listStaticExternalIp(projectId, region);
  }

  // Lists all static external IP addresses, either regional or global.
  public static List<Address> listStaticExternalIp(String projectId, String region)
          throws IOException {
    // Use regional client if a region is specified
    if (region != null) {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (AddressesClient client = AddressesClient.create()) {
        ListAddressesRequest request = ListAddressesRequest.newBuilder()
                .setProject(projectId)
                .setRegion(region)
                .build();

        return Lists.newArrayList(client.list(request).iterateAll());
      }
    } else {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      try (GlobalAddressesClient client = GlobalAddressesClient.create()) {
        ListGlobalAddressesRequest request = ListGlobalAddressesRequest.newBuilder()
                .setProject(projectId)
                .build();

        return Lists.newArrayList(client.list(request).iterateAll());
      }
    }
  }
}

Python

from typing import List, Optional

from google.cloud.compute_v1.services.addresses.client import AddressesClient
from google.cloud.compute_v1.services.global_addresses import GlobalAddressesClient
from google.cloud.compute_v1.types import Address


def list_static_ip_addresses(
    project_id: str, region: Optional[str] = None
) -> List[Address]:
    """
    Lists all static external IP addresses, either regional or global.

    Args:
    project_id (str): project ID.
    region (Optional[str]): The region of the IP addresses if regional. None if global.

    Returns:
    List[Address]: A list of Address objects containing details about the requested IPs.
    """
    if region:
        # Use regional client if a region is specified
        client = AddressesClient()
        addresses_iterator = client.list(project=project_id, region=region)
    else:
        # Use global client if no region is specified
        client = GlobalAddressesClient()
        addresses_iterator = client.list(project=project_id)

    return list(addresses_iterator)  # Convert the iterator to a list to return

Configura indirizzi IP esterni statici

Le seguenti sezioni descrivono come configurare indirizzi IP esterni statici per le tue VM.

Crea una VM che utilizza un indirizzo IP esterno statico

Dopo aver prenotato un indirizzo IP esterno statico, puoi assegnarlo a una VM.

Console

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

    Vai a Crea un'istanza

  2. Specifica i dettagli della VM.

  3. Espandi la sezione Opzioni avanzate.

  4. Espandi la sezione Networking.

  5. Nella sezione Interfacce di rete, espandi una rete a riga di comando per modificarlo.

  6. Per assegnare un indirizzo IPv4:

    1. Seleziona una rete.
    2. Seleziona l'indirizzo IP dall'elenco Indirizzo IPv4 esterno.
  7. Per assegnare un indirizzo IPv6:

    1. Seleziona una rete che contiene una subnet IPv6.
    2. Seleziona una subnet a doppio stack dall'elenco Subnet.
    3. Per Tipo di stack IP, seleziona IPv4 e IPv6 (stack doppio).
    4. Seleziona l'indirizzo IPv6 esterno appena prenotato dal Elenco indirizzi IPv6 esterni. In alternativa, seleziona CREA INDIRIZZO IP e prenota un nuovo indirizzo IPv6 esterno statico.
    5. In Network Service Tier (Livello di servizio di rete), seleziona Premium.
  8. Per completare la modifica dell'interfaccia di rete predefinita, fai clic su Fine.

  9. Continua con il processo di creazione della VM.

gcloud

Puoi creare una VM e assegnare un indirizzo IP esterno a livello di regione statico che hai già prenotato.

  • Per assegnare un indirizzo IPv4 esterno statico, segui questi passaggi:

    gcloud compute instances create VM_NAME --address=IP_ADDRESS
    

    Sostituisci quanto segue:

    • VM_NAME: il nome della VM.
    • IP_ADDRESS: l'indirizzo IP da assegnare al VM. Usa l'indirizzo IP esterno statico riservato non il nome dell'indirizzo.
  • Per assegnare un indirizzo IPv6 esterno statico, segui questi passaggi:

    gcloud compute instances create VM_NAME \
        --subnet=SUBNET \
        --stack-type=IPV4_IPV6 \
        --external-ipv6-address=IPV6_ADDRESS \
        --external-ipv6-prefix-length=96 \
        --ipv6-network-tier=PREMIUM \
        --zone=ZONE
    

Terraform

Puoi utilizzare la risorsa google_compute_instance per assegnare un indirizzo IP esterno.

resource "google_compute_instance" "default" {
  name         = "dns-proxy-nfs"
  machine_type = "n1-standard-1"
  zone         = "us-central1-a"

  boot_disk {
    initialize_params {
      image = "ubuntu-1404-trusty-v20160627"
    }
  }

  network_interface {
    network = "default"
    access_config {
      nat_ip = google_compute_address.default.address
    }
  }
}

REST

Per assegnare un indirizzo IPv4 esterno statico a una nuova VM:

Nella tua richiesta di crea una nuova VM, indicare esplicitamente networkInterfaces[].accessConfigs[].natIP e l'indirizzo IPv4 esterno che vuoi utilizzare. Ad esempio:

{
  "name": "VM_NAME",
  "machineType": "zones/ZONE/machineTypes/MACHINE_TYPE",
  "networkInterfaces": [{
    "accessConfigs": [{
      "type": "ONE_TO_ONE_NAT",
      "name": "External NAT",
      "natIP": "IPV4_ADDRESS"
     }],
    "network": "global/networks/default"
  }],
  "disks": [{
      "autoDelete": "true",
      "boot": "true",
      "type": "PERSISTENT",
      "initializeParams": {
          "sourceImage": "SOURCE_IMAGE"
      }
}]
}

Per assegnare un indirizzo IPv6 esterno statico a una nuova VM:

Nella tua richiesta di crea una nuova VM, indicare esplicitamente networkInterfaces[].ipv6AccessConfigs[].externalIpv6 e l'indirizzo IPv6 esterno che vuoi utilizzare. Ad esempio:

{
  "name": "VM_NAME",
  "machineType": "zones/ZONE/machineTypes/MACHINE_TYPE",
  "networkInterfaces": [{
          "accessConfigs": [{
              "name": "external-nat",
              "type": "ONE_TO_ONE_NAT"
          }],
          "ipv6AccessConfigs": [{
        "externalIpv6": "IOV6_ADDRESS",
        "externalIpv6PrefixLength": 96,
        "name": "external-ipv6-access-config",
        "networkTier": "PREMIUM",
        "type": "DIRECT_IPV6"
          }],
      "stackType": "IPV4_IPV6",
      "subnetwork":"SUBNETWORK
  }],
  "disks": [{
    "autoDelete": "true",
    "boot": "true",
    "mode": "READ_WRITE",
    "type": "PERSISTENT",
    "initializeParams": {
        "sourceImage": "SOURCE_IMAGE"
    },
  }],
 }

Vai


// assignStaticExternalToNewVM creates a new VM instance and assigns a static external IP address to it.
// NOTE: ip address is expected to exist and be located in the same region as new VM
func assignStaticExternalToNewVM(w io.Writer, projectID, zone, instanceName, ipAddress string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// ipAddress := 301.222.11.123

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

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

	// List of public operating system (OS) images: https://cloud.google.com/compute/docs/images/os-details.
	newestDebianReq := &computepb.GetFromFamilyImageRequest{
		Project: "debian-cloud",
		Family:  "debian-12",
	}
	newestDebian, err := imagesClient.GetFromFamily(ctx, newestDebianReq)
	if err != nil {
		return fmt.Errorf("unable to get image from family: %w", err)
	}

	req := &computepb.InsertInstanceRequest{
		Project: projectID,
		Zone:    zone,
		InstanceResource: &computepb.Instance{
			Name: proto.String(instanceName),
			Disks: []*computepb.AttachedDisk{
				{
					InitializeParams: &computepb.AttachedDiskInitializeParams{
						DiskSizeGb:  proto.Int64(10),
						SourceImage: newestDebian.SelfLink,
						DiskType:    proto.String(fmt.Sprintf("zones/%s/diskTypes/pd-standard", zone)),
					},
					AutoDelete: proto.Bool(true),
					Boot:       proto.Bool(true),
					Type:       proto.String(computepb.AttachedDisk_PERSISTENT.String()),
				},
			},
			MachineType: proto.String(fmt.Sprintf("zones/%s/machineTypes/n1-standard-1", zone)),
			NetworkInterfaces: []*computepb.NetworkInterface{
				{
					AccessConfigs: []*computepb.AccessConfig{
						{
							Type:        proto.String(computepb.AccessConfig_ONE_TO_ONE_NAT.String()),
							Name:        proto.String("External NAT"),
							NetworkTier: proto.String(computepb.AccessConfig_PREMIUM.String()),
							NatIP:       proto.String(ipAddress),
						},
					},
				},
			},
		},
	}

	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, "Static address %s assigned to new VM", ipAddress)

	return nil
}

Java


import com.google.cloud.compute.v1.AccessConfig;
import com.google.cloud.compute.v1.AccessConfig.Type;
import com.google.cloud.compute.v1.Address.NetworkTier;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.GetInstanceRequest;
import com.google.cloud.compute.v1.ImagesClient;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class AssignStaticExternalNewVmAddress {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Instance ID of the Google Cloud project you want to use.
    String instanceId = "your-instance-id";
    // Name of the zone to create the instance in. For example: "us-west3-b"
    String zone = "your-zone-id";
    // 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"
    String machineType = String.format("zones/%s/machineTypes/{your-machineType-id}", zone);
    // boolean flag indicating if the instance should have an external IPv4 address assigned.
    boolean externalAccess = true;
    // 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.
    String externalIpv4 = "your-externalIpv4-id";

    assignStaticExternalNewVmAddress(projectId, instanceId, zone,
            externalAccess, machineType, externalIpv4);
  }

  // Create a new VM instance with assigned static external IP address.
  public static Instance assignStaticExternalNewVmAddress(String projectId, String instanceName,
                                                          String zone, boolean externalAccess,
                                                          String machineType, String externalIpv4)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    String sourceImage;
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (ImagesClient imagesClient = ImagesClient.create()) {
      sourceImage = imagesClient.getFromFamily("debian-cloud", "debian-11").getSelfLink();
    }
    AttachedDisk attachedDisk = buildAttachedDisk(sourceImage, zone);

    return createInstance(projectId, instanceName, zone,
            attachedDisk, machineType, externalAccess, externalIpv4);
  }

  private static AttachedDisk buildAttachedDisk(String sourceImage, String zone) {
    AttachedDiskInitializeParams initializeParams = AttachedDiskInitializeParams.newBuilder()
            .setSourceImage(sourceImage)
            .setDiskSizeGb(10)
            .setDiskType(String.format("zones/%s/diskTypes/pd-standard", zone))
            .build();

    return AttachedDisk.newBuilder()
            .setInitializeParams(initializeParams)
            // Remember to set auto_delete to True if you want the disk to be deleted
            // when you delete your VM instance.
            .setAutoDelete(true)
            .setBoot(true)
            .build();
  }

  // Send an instance creation request to the Compute Engine API and wait for it to complete.
  private static Instance createInstance(String projectId, String instanceName,
                                         String zone, AttachedDisk disks,
                                         String machineType, boolean externalAccess,
                                         String externalIpv4)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (InstancesClient client = InstancesClient.create()) {
      Instance instanceResource =
              buildInstanceResource(instanceName, disks, machineType, externalAccess, externalIpv4);

      InsertInstanceRequest build = InsertInstanceRequest.newBuilder()
              .setProject(projectId)
              .setRequestId(UUID.randomUUID().toString())
              .setZone(zone)
              .setInstanceResource(instanceResource)
              .build();
      client.insertCallable().futureCall(build).get(60, TimeUnit.SECONDS);

      GetInstanceRequest getInstanceRequest = GetInstanceRequest.newBuilder()
              .setInstance(instanceName)
              .setProject(projectId)
              .setZone(zone)
              .build();

      return client.get(getInstanceRequest);
    }
  }

  private static Instance buildInstanceResource(String instanceName, AttachedDisk disk,
                                                String machineType, boolean externalAccess,
                                                String externalIpv4) {
    NetworkInterface networkInterface =
            networkInterface(externalAccess, externalIpv4);

    return Instance.newBuilder()
            .setName(instanceName)
            .addDisks(disk)
            .setMachineType(machineType)
            .addNetworkInterfaces(networkInterface)
            .build();
  }

  private static NetworkInterface networkInterface(boolean externalAccess, String externalIpv4) {
    NetworkInterface.Builder build = NetworkInterface.newBuilder()
            .setNetwork("global/networks/default");
    if (externalAccess) {
      AccessConfig.Builder accessConfig = AccessConfig.newBuilder()
              .setType(Type.ONE_TO_ONE_NAT.name())
              .setName("External NAT")
              .setNetworkTier(NetworkTier.PREMIUM.name());
      if (externalIpv4 != null) {
        accessConfig.setNatIP(externalIpv4);
      }
      build.addAccessConfigs(accessConfig.build());
    }

    return build.build();
  }
}

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 assign_static_external_ip_to_new_vm(
    project_id: str, zone: str, instance_name: str, ip_address: str
) -> compute_v1.Instance:
    """
    Create a new VM instance with assigned static external IP address.

    Args:
        project_id (str): project ID or project number of the Cloud project you want to use.
        zone (str): name of the zone to create the instance in. For example: "us-west3-b"
        instance_name (str): name of the new virtual machine (VM) instance.
        ip_address(str): external address to be assigned to this instance. It must live in the same
        region as the zone of the instance and be precreated before function called.

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

Modificare o assegnare un indirizzo IP esterno a una VM esistente

Puoi modificare o assegnare un indirizzo IP esterno, temporaneo o statico, per una VM esistente.

Una VM può avere più interfacce, ognuna delle quali può avere un'interfaccia Indirizzo IP. Se la VM ha già un indirizzo IP esterno, devi rimuovi l'indirizzo. Successivamente, puoi assegnare un nuovo l'indirizzo IP della VM esistente.

Console

  1. Nella console Google Cloud, vai alla pagina Istanze VM.

    Vai a Istanze VM

  2. Fai clic sul nome della VM a cui vuoi assegnare un IP esterno a. Viene visualizzata la pagina Dettagli istanza.
  3. Nella pagina Dettagli istanza, completa i seguenti passaggi:

    1. Fai clic su Modifica.
    2. Espandi Interfacce di rete.
    3. Seleziona l'indirizzo IP esterno richiesto da assegnare alla VM:
      1. Per Indirizzo IPv4 esterno, seleziona Indirizzo IPv4 esterno statico o temporaneo.
      2. Per Indirizzo IPv6 esterno, seleziona Indirizzo IPv6 esterno statico o temporaneo.
    4. Fai clic su Fine.
  4. Fai clic su Salva.

gcloud

  1. (Facoltativo) Prenota un indirizzo IP esterno statico.

    Se vuoi assegnare un indirizzo IP esterno statico, devi prenotare un e assicurarsi che non sia utilizzato un'altra risorsa. Se necessario, segui le istruzioni per riservare un nuovo indirizzo IP esterno statico o annullare l'assegnazione di un indirizzo IP esterno statico.

    Se intendi utilizzare un indirizzo IP esterno temporaneo, puoi saltare questo passaggio e Compute Engine assegna in modo casuale all'indirizzo IP esterno.

  2. Rimuovi le assegnazioni di indirizzi IP esistenti, come descritto in Annulla l'assegnazione di un indirizzo IP esterno statico.

  3. Assegna il nuovo indirizzo IP esterno.

    • Per assegnare un indirizzo IPv4, utilizza il metodo Sottocomando instances add-access-config:

      Nota: non sostituire IP_ADDRESS con il nome dell'IP statico . Devi utilizzare l'indirizzo IP effettivo.
      gcloud compute instances add-access-config VM_NAME \
        --access-config-name="ACCESS_CONFIG_NAME" --address=IP_ADDRESS
      

      Sostituisci quanto segue:

      • VM_NAME: il nome della VM.
      • ACCESS_CONFIG_NAME: il nome con cui chiamare configurazione dell'accesso. Assicurati di inserire il nome completo tra virgolette.
      • IP_ADDRESS: l'indirizzo IP da aggiungere.

      Se vuoi che Compute Engine assegni una risorsa esterna temporanea per l'indirizzo IP anziché utilizzare un indirizzo IP esterno statico, ometti il --address IP_ADDRESS proprietà:

      gcloud compute instances add-access-config VM_NAME \
        --access-config-name="ACCESS_CONFIG_NAME"
      
    • Per assegnare un intervallo di indirizzi IPv6, utilizza il metodo Sottocomando instance network-interfaces update:

      gcloud compute instances network-interfaces update VM_NAME \
        --network-interface==NIC \
        --ipv6-network-tier=PREMIUM \
        --stack-type=IPV4_IPV6 \
        --external-ipv6-address=IPV6_ADDRESS \
        --external-ipv6-prefix-length=96 \
        --zone=ZONE
      

      Sostituisci quanto segue:

      • VM_NAME: il nome della VM.
      • NIC: il nome dell'interfaccia di rete.
      • IPV6_ADDRESS: l'indirizzo IPv6 da assegnare alla VM. Specifica il primo indirizzo IPv6 nella Intervallo di /96.
      • ZONE: la zona della VM.

REST

Puoi modificare l'indirizzo IPv4 o IPv6 esterno di una VM aggiungendo un nuovo la configurazione dell'accesso per quella VM.

  1. Rimuovi le assegnazioni di indirizzi IP esistenti, come descritto in Annulla l'assegnazione di un indirizzo IP esterno statico.

  2. Elimina la configurazione di accesso esistente inviando una richiesta POST a Metodo instances.deleteAccessConfig.

    POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/deleteAccessConfig
    
  3. Aggiungi una nuova configurazione di accesso all'interfaccia di rete della VM inviando una richiesta POST al Metodo instances.addAccessConfig.

Vai

import (
	"context"
	"fmt"
	"io"

	"google.golang.org/protobuf/proto"

	compute "cloud.google.com/go/compute/apiv1"
	"cloud.google.com/go/compute/apiv1/computepb"
)

// assignStaticAddressToExistingVM assigns a static external IP address to an existing VM instance.
// Note: VM and assigned IP must be in the same region.
func assignStaticAddressToExistingVM(w io.Writer, projectID, zone, instanceName, IPAddress, networkInterfaceName string) error {
	// projectID := "your_project_id"
	// zone := "europe-central2-b"
	// instanceName := "your_instance_name"
	// IPAddress := "34.111.222.333"
	// networkInterfaceName := "nic0"

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

	reqGet := &computepb.GetInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
	}

	instance, err := instancesClient.Get(ctx, reqGet)
	if err != nil {
		return fmt.Errorf("could not get instance: %w", err)
	}

	var networkInterface *computepb.NetworkInterface
	for _, ni := range instance.NetworkInterfaces {
		if *ni.Name == networkInterfaceName {
			networkInterface = ni
			break
		}
	}

	if networkInterface == nil {
		return fmt.Errorf("No network interface named '%s' found on instance %s", networkInterfaceName, instanceName)
	}

	var accessConfig *computepb.AccessConfig
	for _, ac := range networkInterface.AccessConfigs {
		if *ac.Type == computepb.AccessConfig_ONE_TO_ONE_NAT.String() {
			accessConfig = ac
			break
		}
	}

	if accessConfig != nil {
		// network interface is immutable - deletion stage is required in case of any assigned ip (static or ephemeral).
		reqDelete := &computepb.DeleteAccessConfigInstanceRequest{
			Project:          projectID,
			Zone:             zone,
			Instance:         instanceName,
			AccessConfig:     *accessConfig.Name,
			NetworkInterface: networkInterfaceName,
		}

		opDelete, err := instancesClient.DeleteAccessConfig(ctx, reqDelete)
		if err != nil {
			return fmt.Errorf("unable to delete access config: %w", err)
		}

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

	reqAdd := &computepb.AddAccessConfigInstanceRequest{
		Project:  projectID,
		Zone:     zone,
		Instance: instanceName,
		AccessConfigResource: &computepb.AccessConfig{
			NatIP: &IPAddress,
			Type:  proto.String(computepb.AccessConfig_ONE_TO_ONE_NAT.String()),
		},
		NetworkInterface: networkInterfaceName,
	}

	opAdd, err := instancesClient.AddAccessConfig(ctx, reqAdd)
	if err != nil {
		return fmt.Errorf("unable to add access config: %w", err)
	}

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

	fmt.Fprintf(w, "Static address %s assigned to the instance %s\n", IPAddress, instanceName)

	return nil
}

Java


import com.google.cloud.compute.v1.AccessConfig;
import com.google.cloud.compute.v1.AccessConfig.Type;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class AssignStaticExistingVm {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Instance ID of the Google Cloud project you want to use.
    String instanceId = "your-instance-id";
    // Name of the zone to create the instance in. For example: "us-west3-b"
    String zone = "your-zone-id";
    // Name of the network interface to assign.
    String netInterfaceName = "your-netInterfaceName-id";

    assignStaticExistingVmAddress(projectId, instanceId, zone, netInterfaceName);
  }

  // Updates or creates an access configuration for a VM instance to assign a static external IP.
  // As network interface is immutable - deletion stage is required
  // in case of any assigned ip (static or ephemeral).
  // VM and ip address must be created before calling this function.
  // IMPORTANT: VM and assigned IP must be in the same region.
  public static Instance assignStaticExistingVmAddress(String projectId, String instanceId,
                                                       String zone, String netInterfaceName)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (InstancesClient client = InstancesClient.create()) {
      Instance instance = client.get(projectId, zone, instanceId);

      NetworkInterface networkInterface = null;
      for (NetworkInterface netInterface : instance.getNetworkInterfacesList()) {
        if (netInterface.getName().equals(netInterfaceName)) {
          networkInterface = netInterface;
          break;
        }
      }

      if (networkInterface == null) {
        throw new IllegalArgumentException(
                String.format(
                        "No '{network_interface_name}' variable found on instance %s.",
                        instanceId)
        );
      }
      AccessConfig accessConfig = null;
      for (AccessConfig config : networkInterface.getAccessConfigsList()) {
        if (config.getType().equals(Type.ONE_TO_ONE_NAT.name())) {
          accessConfig = config;
          break;
        }
      }

      if (accessConfig != null) {
        // Delete the existing access configuration first
        client.deleteAccessConfigAsync(projectId, zone, instanceId,
                        accessConfig.getName(), netInterfaceName)
                .get(30, TimeUnit.SECONDS);
      }

      // Add a new access configuration with the new IP
      AccessConfig newAccessConfig = AccessConfig.newBuilder()
              // Leave this field undefined to use an IP from a shared ephemeral IP address pool
              // .setNatIP(ipAddress)
              .setType(Type.ONE_TO_ONE_NAT.name())
              .setName("external-nat")
              .build();

      client.addAccessConfigAsync(projectId, zone, instanceId, netInterfaceName, newAccessConfig)
              .get(30, TimeUnit.SECONDS);

      // return updated instance
      return client.get(projectId, zone, instanceId);
    }
  }
}

Python

import uuid

from google.cloud.compute_v1 import InstancesClient
from google.cloud.compute_v1.types import AccessConfig
from google.cloud.compute_v1.types import AddAccessConfigInstanceRequest
from google.cloud.compute_v1.types import DeleteAccessConfigInstanceRequest


def assign_static_ip_to_existing_vm(
    project_id: str,
    zone: str,
    instance_name: str,
    ip_address: str,
    network_interface_name: str = "nic0",
):
    """
    Updates or creates an access configuration for a VM instance to assign a static external IP.
    As network interface is immutable - deletion stage is required in case of any assigned ip (static or ephemeral).
    VM and ip address must be created before calling this function.
    IMPORTANT: VM and assigned IP must be in the same region.

    Args:
        project_id (str): Project ID.
        zone (str): Zone where the VM is located.
        instance_name (str): Name of the VM instance.
        ip_address (str): New static external IP address to assign to the VM.
        network_interface_name (str): Name of the network interface to assign.

    Returns:
        google.cloud.compute_v1.types.Instance: Updated instance object.
    """
    client = InstancesClient()
    instance = client.get(project=project_id, zone=zone, instance=instance_name)
    network_interface = next(
        (ni for ni in instance.network_interfaces if ni.name == network_interface_name),
        None,
    )

    if network_interface is None:
        raise ValueError(
            f"No network interface named '{network_interface_name}' found on instance {instance_name}."
        )

    access_config = next(
        (ac for ac in network_interface.access_configs if ac.type_ == "ONE_TO_ONE_NAT"),
        None,
    )

    if access_config:
        # Delete the existing access configuration first
        delete_request = DeleteAccessConfigInstanceRequest(
            project=project_id,
            zone=zone,
            instance=instance_name,
            access_config=access_config.name,
            network_interface=network_interface_name,
            request_id=str(uuid.uuid4()),
        )
        delete_operation = client.delete_access_config(delete_request)
        delete_operation.result()

    # Add a new access configuration with the new IP
    add_request = AddAccessConfigInstanceRequest(
        project=project_id,
        zone=zone,
        instance=instance_name,
        network_interface="nic0",
        access_config_resource=AccessConfig(
            nat_i_p=ip_address, type_="ONE_TO_ONE_NAT", name="external-nat"
        ),
        request_id=str(uuid.uuid4()),
    )
    add_operation = client.add_access_config(add_request)
    add_operation.result()

    updated_instance = client.get(project=project_id, zone=zone, instance=instance_name)
    return updated_instance

Limita gli indirizzi IP esterni a VM specifiche

Per alcuni carichi di lavoro, potresti avere requisiti essenziali che includono restrizioni relative a sicurezza e rete. Ad esempio, potresti voler limitare indirizzi IP esterni, in modo che possano essere usate solo da VM specifiche. Questo può aiutare a impedire l'esfiltrazione di dati e mantenere l'isolamento della rete. L'utilizzo di un Criterio dell'organizzazione, puoi limitare gli indirizzi IP esterni a VM specifiche per controllare l'uso degli indirizzi IP esterni per le VM all'interno di un un'organizzazione o un progetto.

Il vincolo per controllare l'indirizzo IP esterno sulle VM è:

constraints/compute.vmExternalIpAccess

Per utilizzare il vincolo, devi specificare un criterio con un allowedList di VM possono avere indirizzi IP esterni. Se non specifichi un criterio, tutti gli indirizzi IP esterni sono consentiti per tutte le VM. Quando il criterio è attivo, solo le VM elencate nell'elenco allowedValues può essere assegnato un IP esterno statico o temporaneo e altre VM di Compute Engine l'organizzazione o il progetto che non sono esplicitamente definiti nel criterio gli utenti non potranno utilizzare indirizzi IP esterni.

Le VM vengono identificate nelle liste consentite e bloccate utilizzando l'URI della VM:

projects/PROJECT_ID/zones/ZONE/instances/VM_NAME

Specifiche per la limitazione degli indirizzi IP esterni

  • Puoi applicare questa vincolo di elenco solo alle VM.
  • Non puoi applicare il vincolo in modo retroattivo. Tutte le VM con gli indirizzi IP esterni, prima di abilitare il criterio, conservano il proprio IP esterno indirizzi IP esterni.
  • Questo vincolo accetta allowedList o deniedList, ma non entrambi nello stesso criterio.
  • Spetta a te o a un amministratore con le autorizzazioni necessarie gestire e mantenere l'integrità e il ciclo di vita delle VM. Solo il vincolo verifica l'URI della VM e non impedisce alle VM nella lista consentita di alterati, eliminati o ricreati.

Autorizzazioni necessarie per limitare gli indirizzi IP esterni

Per impostare un vincolo a livello di progetto o organizzazione, devi è stato concesso il ruolo orgpolicy.policyAdmin nell'organizzazione.

Imposta il vincolo del criterio a livello di organizzazione

Console

  1. Vai alla pagina Criteri dell'organizzazione.

    Vai a Criteri dell'organizzazione

  2. Se necessario, seleziona l'organizzazione richiesta dal progetto menu a discesa.
  3. Fai clic su Definisci gli IP esterni consentiti per le istanze VM.
  4. Fai clic su Modifica per modificare il criterio IP esterno. Se non riesci ad accedere Modifica, non è lo strumento corretto autorizzazioni.
  5. Seleziona Personalizza per impostare il criterio dell'organizzazione per VM specifiche.

    Opzione di personalizzazione nella pagina Modifica criterio dell&#39;organizzazione.

  6. Seleziona l'Applicazione delle norme e il Tipo di criterio richiesti.

  7. In Valori criterio, seleziona Personalizzato.

  8. Inserisci un URI per una VM e premi Invio. L'URI deve essere nel formato seguente formato:

    projects/PROJECT_ID/zones/ZONE/instances/VM_NAME
    
  9. Fai clic su Nuovo valore del criterio e inserisci gli URI per le VM in base alle esigenze.

  10. Fai clic su Salva per applicare il vincolo.

gcloud

Per impostare un vincolo per l'accesso IP esterno, devi prima che la tua organizzazione ID. Puoi trovare l'ID organizzazione eseguendo il Comando organizations list e cercando l'ID numerico nella risposta:

gcloud organizations list

gcloud CLI restituisce un elenco di organizzazioni nel seguente formato:

DISPLAY_NAME               ID
example-organization1      29252605212
example-organization2      1234567890

Utilizza la Comando gcloud resource-manager org-policies set-policy per impostare il criterio. Devi fornire il criterio come file JSON. Crea un file JSON nel seguente formato:

{
"constraint": "constraints/compute.vmExternalIpAccess",
"listPolicy": {
  "allowedValues": [
     "projects/PROJECT_ID/zones/ZONE/instances/VM_NAME",
     "projects/PROJECT_ID/zones/ZONE/instances/VM_NAME",
     "projects/PROJECT_ID/zones/ZONE/instances/VM_NAME"
  ]
 }
}

Sostituisci quanto segue:

  • PROJECT_ID: l'ID progetto per questa richiesta, ad esempio example-project. Tieni presente che questa procedura è diversa dalla configurazione ai criteri dell'organizzazione, che richiedono l'ID numerico dell'organizzazione.
  • ZONE: la zona della VM
  • VM_NAME: il nome della VM

In alternativa, puoi specificare un elenco deniedValues per indicare le VM che vuoi impedire esplicitamente di avere un indirizzo IP esterno. Qualsiasi VM non in elenco sarebbe implicitamente autorizzata ad avere all'indirizzo IP esterno. Puoi specificare solo allowedValues o deniedValues, ma non entrambi.

Quindi, passa il file con la tua richiesta:

gcloud resource-manager org-policies set-policy MY_POLICY.JSON --organization=ORGANIZATION_ID

Sostituisci ORGANIZATION_ID con l'ID numerico del dell'organizzazione.

Se non vuoi che nessuna VM abbia accesso IP esterno, puoi impostare un criterio con allValues impostato su DENY:

{
  "constraint": "constraints/compute.vmExternalIpAccess",
  "listPolicy": {
    "allValues": "DENY"
  }
}

REST

Utilizza la API setOrgPolicy() per definire il vincolo. Le VM nell'elenco allowedValue specificare possono avere indirizzi IP esterni. In alternativa, puoi specifica un elenco deniedValues per indicare le VM che hai esplicitamente vuoi impedire di avere un indirizzo IP esterno. Qualsiasi VM che non si trovi sarebbero implicitamente autorizzati ad avere un indirizzo IP esterno. Puoi specificare solo allowedValues o deniedValues, ma non entrambi.

Ad esempio, quella che segue è una richiesta di applicazione Vincolo compute.vmExternalIpAccess a un'organizzazione in cui le VM da determinati progetti all'interno dell'organizzazione possono avere indirizzi IP esterni:

POST https://cloudresourcemanager.googleapis.com/v1/organizations/ORGANIZATION_ID:setOrgPolicy

dove ORGANIZATION_ID è l'ID numerico del dell'organizzazione.

Ora, nel corpo della richiesta, indica il criterio per questo vincolo:

{
  "policy": {
    "constraint": "constraints/compute.vmExternalIpAccess",
    "listPolicy": {
      "allowedValues": [
        "projects/PROJECT_ID/zones/ZONE/instances/VM_NAME",
        "projects/PROJECT_ID/zones/ZONE/instances/VM_NAME",
        "projects/PROJECT_ID/zones/ZONE/instances/VM_NAME"
        ]
      }
    }
 }

Se non vuoi che nessuna VM abbia accesso IP esterno, puoi impostare un criterio con allValues impostato su DENY:

{
  "policy": {
    "constraint": "constraints/compute.vmExternalIpAccess",
    "listPolicy": {
      "allValues": "DENY"
      }
    }
 }

Impostare il criterio a livello di progetto

L'impostazione di un criterio a livello di progetto sostituisce il criterio a livello di organizzazione livello. Ad esempio, se a livello di organizzazione è presente example-vm-1 nella Elenco allowedValues, ma il criterio a livello di progetto ha la stessa VM nell'elenco deniedValues, alla VM non sarebbe consentito avere all'indirizzo IP esterno.

Console

Segui la stessa procedura descritta in Imposta un vincolo di criterio a livello di organizzazione, ma scegli il tuo progetto dal selettore di progetti anziché dell'organizzazione.

Selettore progetti.

gcloud

Utilizza la Comando gcloud resource-manager org-policies set-policy per impostare il criterio. Devi fornire il criterio come file JSON. Crea un file JSON nel seguente formato:

{
 "constraint": "constraints/compute.vmExternalIpAccess",
 "listPolicy": {
  "allowedValues": [
   "projects/PROJECT_ID/zones/ZONE/instances/VM_NAME"
  ]
 }
}

Sostituisci quanto segue:

  • PROJECT_ID: l'ID progetto per questa richiesta, ad esempio example-project. Tieni presente che questa procedura è diversa dalla configurazione ai criteri dell'organizzazione, che richiedono l'ID numerico dell'organizzazione.
  • ZONE: la zona della VM.
  • VM_NAME: il nome della VM.

In alternativa, puoi specificare un elenco deniedValues di VM esplicitamente di avere un indirizzo IP esterno. Qualsiasi VM non presenti nell'elenco sarebbero implicitamente autorizzati ad avere un indirizzo IP esterno. Puoi specificare solo allowedValues o deniedValues, ma non entrambi.

Quindi, passa il file con la tua richiesta:

gcloud resource-manager org-policies set-policy MY_POLICY.JSON --project=example-project

REST

Utilizza la API setOrgPolicy per definire il vincolo. Le VM nell'elenco allowedValue specificato possono avere indirizzi IP esterni. In alternativa, puoi specificare Elenco deniedValues per indicare le VM da cui vuoi impedire esplicitamente di avere un indirizzo IP esterno. Qualsiasi VM non in elenco è implicitamente autorizzati ad avere un indirizzo IP esterno. Puoi specificare solo: allowedValues o deniedValues, ma non entrambi.

Ad esempio, questa è una richiesta di impostare il Vincolo di compute.vmExternalIpAccess su un progetto per consentire VM specifiche per avere indirizzi IP esterni:

POST https://cloudresourcemanager.googleapis.com/v1/projects/PROJECT_ID:setOrgPolicy

Sostituisci PROJECT_ID con l'ID progetto per questo richiesta.

Il corpo della richiesta contiene il criterio per questo vincolo:

{
  "policy": {
    "constraint": "constraints/compute.vmExternalIpAccess",
    "listPolicy": {
      "allowedValues": [
        "projects/PROJECT_ID/zones/ZONE/instances/VM_NAME"
      ]
    }
  }
}

Best practice per limitare gli indirizzi IP esterni

  • Evita di utilizzare l'elenco deniedValues con questo di blocco. Se definisci valori nell'elenco deniedValues, significa che solo le VM nell'elenco deniedValues non possono utilizzare e gli indirizzi IP esterni. Potrebbe trattarsi di un problema di sicurezza se vuoi controllare esattamente quali VM possono avere indirizzi IP esterni. Se vuoi rimuovere alcune VM dall'elenco allowedValues, aggiorna il criterio esistente per rimuovere le VM da allowedList anziché VM nell'elenco deniedValues con una gerarchia inferiore.

  • Se vuoi impostare un criterio su gran parte della gerarchia delle risorse, esenta determinati progetti, ripristina il criterio predefinito utilizzando il metodo setOrgPolicy specificando restoreDefault per consentire l'associazione di tutte le VM nei progetti a indirizzi IP esterni indirizzi IP esterni. I criteri attuali per i progetti non sono interessati per impostazione predefinita.

  • Usa il criterio dell'organizzazione insieme ai ruoli IAM per controllare meglio l'ambiente. Questo criterio si applica solo alle VM, ma se vuoi controllare e controllare meglio limitare gli indirizzi IP esterni sui dispositivi di rete, puoi concedere il ruolo compute.networkAdmin alle parti appropriate.

  • Tutti i servizi e i prodotti in esecuzione su Compute Engine all'interno dell'organizzazione o del progetto con il criterio abilitato sono soggetti a questa del criterio dell'organizzazione. Nello specifico, servizi come Google Kubernetes Engine, Dataflow, Dataproc e Cloud SQL sono interessati da questa . Se è un problema, Google consiglia di configurare altri servizi e prodotti in un a cui non è applicato il criterio dell'organizzazione e utilizza VPC condiviso, se necessario.

Gestisci indirizzi IP esterni statici

Le seguenti sezioni descrivono come gestire indirizzi IP esterni statici per le tue VM.

Determina se un indirizzo IP interno è temporaneo o statico

Gli indirizzi IP interni statici e temporanei si comportano e hanno lo stesso aspetto nella maggior parte i contesti. Tuttavia, con gli indirizzi IP interni statici puoi utilizzare per la stessa risorsa anche se la elimini e la crei nuovamente. In generale, se interrompi o elimini il comando, viene rilasciato risorsa.

Per determinare se un indirizzo è statico o temporaneo:

  1. Nella console Google Cloud, vai alla pagina Indirizzi IP.

    Vai a indirizzi IP

  2. Trova l'indirizzo nell'elenco e controlla nella colonna Tipo il tipo di Indirizzo IP.

Annulla l'assegnazione di un indirizzo IP esterno statico

L'annullamento dell'assegnazione di un indirizzo IP ne comporta la rimozione dalla risorsa, di mantenere riservato l'indirizzo IP. Dopo aver annullato l'assegnazione dell'indirizzo IP, puoi e riassegnare l'indirizzo IP a un'altra risorsa.

Puoi anche annullare l'assegnazione dell'indirizzo IPv4 o IPv6 l'eliminazione della VM.

Console

  1. Nella console Google Cloud, vai alla pagina Indirizzi IP.

    Vai a indirizzi IP

  2. Fai clic su Indirizzi IP esterni.

  3. Seleziona l'indirizzo IP statico di cui vuoi annullare l'assegnazione.

  4. Fai clic su Cambia per aprire la finestra di dialogo Collega indirizzo IP.

  5. Nell'elenco a discesa Allega a, seleziona Nessuno.

  6. Fai clic su OK.

gcloud

  1. Verifica se un indirizzo IP statico è in uso utilizzando il comando Comando gcloud compute addresses list:

    gcloud compute addresses list
    

    L'output è simile al seguente:

    NAME                      REGION    ADDRESS                  STATUS
    example-address-ipv4      REGION    198.51.100.1             RESERVED
    example-address-new-ipv4  REGION    203.0.113.1              IN_USE
    example-address-ipv6      REGION    2001:db8:1:1:1:1:1:1     RESERVED
    example-address-new-ipv6  REGION    2001:db8:4:4:4:4:4:4     IN_USE
    
    • Se l'indirizzo IP non è in uso, lo stato è RESERVED.
    • Se l'indirizzo IP è in uso, lo stato è IN_USE.
  2. Recupera il nome della VM che utilizza l'indirizzo IP:

    gcloud compute addresses describe ADDRESS_NAME \
      --region=REGION
    

    Sostituisci quanto segue:

    • ADDRESS_NAME: il nome dell'indirizzo IPv6 risorsa.
    • REGION: la regione dell'indirizzo IPv6 risorsa.

    L'output è simile al seguente:

    address: IP_ADDRESS
    addressType: EXTERNAL
    ...
    region: https://www.googleapis.com/compute/v1/projects/PROJECT/regions/REGION
    selfLink: https://www.googleapis.com/compute/v1/projects/PROJECT/regions/REGION/addresses/ADDRESS_NAME
    status: IN_USE
    subnetwork: https://www.googleapis.com/compute/v1/projects/PROJECT/regions/REGION/subnetworks/SUBNET
    users:
    - https://www.googleapis.com/compute/v1/projects/PROJECT/zones/ZONE/instances/VM_NAME
    

    Il campo users mostra il nome della VM che utilizza l'IP .

  3. Annulla l'assegnazione dell'indirizzo IP alla VM.

    • Per annullare l'assegnazione di un indirizzo IPv4, elimina il file di configurazione dell'accesso della VM:

      1. Ottieni il nome della configurazione di accesso da eliminare. Per avere il nome, utilizza la Comando gcloud compute instances describe. Sostituisci VM_NAME con il nome della VM.

        gcloud compute instances describe VM_NAME
        

        La configurazione dell'accesso viene visualizzata nel seguente formato:

        networkInterfaces:
          - accessConfigs:
            - kind: compute#accessConfig
              name: external-nat
              natIP: 203.0.113.1
              type: ONE_TO_ONE_NAT
        
      2. Elimina la configurazione dell'accesso utilizzando Comando gcloud compute instances delete-access-config:

        gcloud compute instances delete-access-config VM_NAME \
          --access-config-name="ACCESS_CONFIG_NAME"
        

        Sostituisci quanto segue:

        • VM_NAME: il nome della VM.
        • ACCESS_CONFIG_NAME: il nome del alla configurazione di accesso da eliminare. Assicurati di includere il nome completo tra virgolette.
    • Per annullare l'assegnazione di un intervallo di indirizzi IPv6, utilizza il metodo Comando instance network-interfaces update:

      gcloud compute instances network-interfaces update VM_NAME \
        --network-interface=nic0 \
        --stack-type=IPV4_ONLY \
        --zone=ZONE
      

      Sostituisci quanto segue:

      • VM_NAME: il nome della VM che utilizza l'indirizzo IP.
      • ZONE: la zona della VM.
  4. Verifica che l'indirizzo IP esterno statico sia ora disponibile e contrassegnato come RESERVED anziché IN_USE.

    gcloud compute addresses list \
      --filter="ADDRESS_NAME AND region=REGION"
    

    Sostituisci quanto segue:

    • ADDRESS_NAME: il nome dell'indirizzo IP risorsa.
    • REGION: la regione della risorsa dell'indirizzo IP.

Ora che il tuo indirizzo IP esterno statico è disponibile, puoi scegliere la assegnano a un'altra VM.

REST

Per annullare l'assegnazione di un indirizzo IPv4 o IPv6 esterno statico, segui questi passaggi passaggi:

  • Per gli indirizzi IPv4, elimina la configurazione dell'accesso collegata alla VM che utilizza l'indirizzo.

    1. Per verificare i dettagli di configurazione dell'accesso di una VM, crea una Richiesta di GET inviata a Metodo instances.get.

      GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME
      
    2. Elimina la configurazione di accesso esistente effettuando un Richiesta di POST inviata a Metodo instances.deleteAccessConfig.

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

      Sostituisci quanto segue:

      • PROJECT_ID: l'ID progetto per questo richiesta
      • ZONE: la zona in cui si trova la VM
      • VM_NAME: il nome della VM
  • Per gli indirizzi IPv6, aggiorna il tipo di stack della rete per la VM a cui è collegato l'indirizzo IPv6.

    1. Invia una richiesta PATCH a Metodo instances.updateNetworkInterface.

    2. Nel corpo della richiesta, aggiorna il valore del campo stackType in IPV4_ONLY.

      Ad esempio:

      PATCH https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/VM_NAME/updateNetworkInterface
      
      {
        "networkInterfaces": [{
          ...
          "stackType" : "IPV4_ONLY"
          ...
          }]
      }
      

Java


import com.google.cloud.compute.v1.AccessConfig;
import com.google.cloud.compute.v1.AccessConfig.Type;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.NetworkInterface;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class UnassignStaticIpAddress {

  public static void main(String[] args)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Google Cloud project you want to use.
    String projectId = "your-project-id";
    // Instance ID of the Google Cloud project you want to use.
    String instanceId = "your-instance-id";
    // Name of the zone to create the instance in. For example: "us-west3-b"
    String zone = "your-zone";
    // Name of the network interface to assign.
    String netInterfaceName = "your-netInterfaceName";

    unassignStaticIpAddress(projectId, instanceId, zone, netInterfaceName);
  }

  public static Instance unassignStaticIpAddress(String projectId, String instanceId,
                                                 String zone, String netInterfaceName)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (InstancesClient client = InstancesClient.create()) {
      Instance instance = client.get(projectId, zone, instanceId);
      NetworkInterface networkInterface = null;
      for (NetworkInterface netIterface : instance.getNetworkInterfacesList()) {
        if (netIterface.getName().equals(netInterfaceName)) {
          networkInterface = netIterface;
          break;
        }
      }

      if (networkInterface == null) {
        throw new IllegalArgumentException(
                String.format(
                        "No '{network_interface_name}' variable found on instance %s.",
                        instanceId)
        );
      }

      AccessConfig accessConfig = null;
      for (AccessConfig config : networkInterface.getAccessConfigsList()) {
        if (config.getType().equals(Type.ONE_TO_ONE_NAT.name())) {
          accessConfig = config;
          break;
        }
      }

      if (accessConfig != null) {
        // Delete the existing access configuration first
        client.deleteAccessConfigAsync(projectId, zone, instanceId,
                        accessConfig.getName(), netInterfaceName).get(30, TimeUnit.SECONDS);
      }

      // return updated instance
      return client.get(projectId, zone, instanceId);
    }
  }
}

Python

import uuid

from google.cloud.compute_v1 import InstancesClient
from google.cloud.compute_v1.types import DeleteAccessConfigInstanceRequest


def unassign_static_ip_from_existing_vm(
    project_id: str,
    zone: str,
    instance_name: str,
    network_interface_name: str = "nic0",
):
    """
    Updates access configuration for a VM instance to unassign a static external IP.
    VM (and IP address in case of static IP assigned) must be created before calling this function.

    Args:
        project_id (str): Project ID.
        zone (str): Zone where the VM is located.
        instance_name (str): Name of the VM instance.
        network_interface_name (str): Name of the network interface to unassign.
    """
    client = InstancesClient()
    instance = client.get(project=project_id, zone=zone, instance=instance_name)
    network_interface = next(
        (ni for ni in instance.network_interfaces if ni.name == network_interface_name),
        None,
    )

    if network_interface is None:
        raise ValueError(
            f"No network interface named '{network_interface_name}' found on instance {instance_name}."
        )

    access_config = next(
        (ac for ac in network_interface.access_configs if ac.type_ == "ONE_TO_ONE_NAT"),
        None,
    )

    if access_config:
        # Delete the existing access configuration
        delete_request = DeleteAccessConfigInstanceRequest(
            project=project_id,
            zone=zone,
            instance=instance_name,
            access_config=access_config.name,
            network_interface=network_interface_name,
            request_id=str(uuid.uuid4()),
        )
        delete_operation = client.delete_access_config(delete_request)
        delete_operation.result()

    updated_instance = client.get(project=project_id, zone=zone, instance=instance_name)
    return updated_instance

Rilascia un indirizzo IP esterno statico

Se non hai più bisogno di un indirizzo IPv4 o IPv6 esterno statico, puoi rilasciare l'indirizzo IP eliminando la risorsa dell'indirizzo IP. L'eliminazione di una VM rilascia automaticamente un indirizzo IP esterno statico. Devi rilasciare manualmente indirizzi IP esterni statici quando non sono più necessari.

Per rilasciare un indirizzo IP esterno statico, consulta Rilasciare un indirizzo IP esterno statico nella documentazione del VPC.

Passaggi successivi