Prenota un indirizzo IP esterno statico

Puoi prenotare indirizzi IP esterni statici. Puoi anche elencare e rilasciare dagli indirizzi IP esterni statici prenotati. Per assegnare un IP esterno statico a un'istanza di una macchina virtuale (VM), consulta Configurare indirizzi IP esterni statici.

Gli indirizzi IP esterni possono essere statici o temporanei. Se una VM richiede un indirizzo IP esterno fisso che non cambia, può ottenere un indirizzo IP esterno statico. Puoi prenotare un nuovo IP esterno o promuovere indirizzi IP esterni temporanei esistenti.

Se hai bisogno di un indirizzo IP interno statico, vedi Prenotare un indirizzo IP interno statico .

Prima di iniziare

  • Ulteriori informazioni sugli indirizzi IP.
  • Scopri di più su quote e limiti per gli indirizzi IP esterni statici.
  • Scopri di più sui prezzi degli indirizzi IP esterni.
  • Se non l'hai già fatto, configura l'autenticazione. L'autenticazione è la procedura mediante la quale la tua identità sia verificato per l'accesso ai servizi e alle API Google Cloud. Per eseguire il codice o campioni da un ambiente di sviluppo locale, puoi autenticarti 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

    Installa Google Cloud CLI, quindi initialize eseguendo questo comando:

    gcloud init

    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 Configurare l'autenticazione per un ambiente di sviluppo locale nella documentazione sull'autenticazione di Google Cloud.

    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 prenotare e gestire gli indirizzi IP statici, chiedi all'amministratore di concederti Ruolo IAM Amministratore rete Compute (roles/compute.networkAdmin) per il progetto. Per saperne di più sulla concessione dei ruoli, consulta Gestire l'accesso.

Questo ruolo predefinito contiene le autorizzazioni necessarie per prenotare e gestire gli indirizzi IP statici. Per vedere le autorizzazioni esatte obbligatorie, espandi la sezione Autorizzazioni obbligatorie:

Autorizzazioni obbligatorie

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

  • compute.addresses.create sull'indirizzo IP
  • compute.addresses.createInternal sull'indirizzo IP
  • compute.networks.list sulla rete
  • compute.subnetworks.use sulla subnet
  • compute.subnetworks.list sulla subnet

Potresti anche riuscire a ottenere queste autorizzazioni con ruoli personalizzati e altri ruoli predefiniti.

Informazioni sugli indirizzi IP esterni statici

Un indirizzo IP esterno statico è l'indirizzo IP riservato per la risorsa finché non decidi di rilasciarlo. Se hai un indirizzo IP che ai quali i tuoi clienti o utenti fanno affidamento per accedere al tuo servizio, puoi prenotare in modo che solo la tua risorsa possa utilizzarlo. Puoi anche promuovere un indirizzo IP esterno temporaneo a un indirizzo IP esterno statico.

Per ulteriori informazioni, vedi Indirizzi IP.

La seguente tabella elenca gli indirizzi IP esterni statici supportati in Google Cloud.

Tipo di indirizzo IP Risorsa Intervallo IP Origine Associato a
Indirizzi IPv4 esterni a livello di regione VM e bilanciatori del carico a livello di regione /32 Pool di indirizzi IP esterni di Google Progetto
Indirizzi IPv6 esterni a livello di regione VM e bilanciatori del carico a livello di regione supportati /96 Intervallo di indirizzi IPv6 esterni della subnet Subnet
Indirizzi IPv4 esterni globali Bilanciatori del carico globali /32 Pool di indirizzi IP esterni di Google Progetto
Indirizzi IPv6 esterni globali Bilanciatori del carico globali /64 Pool di indirizzi IP esterni di Google Progetto

Per un elenco di bilanciatori del carico regionali e globali, consulta Riepilogo dei tipi di bilanciatore del carico.

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.

Prenota un nuovo indirizzo IP esterno statico

Dopo aver prenotato l'indirizzo, assegnalo a una nuova VM durante la sua creazione o su una VM esistente.

Console

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

    Vai a indirizzi IP

  2. Fai clic su Prenota indirizzo IP statico esterno.
  3. Nel campo Nome, inserisci il nome di un indirizzo IP.
  4. Specifica se il livello di servizio di rete è Premium o Standard. La prenotazione di indirizzi statici IPv6 è supportata solo nel livello Premium.
  5. Specifica se si tratta di un indirizzo IPv4 o IPv6.
  6. Specifica se questo indirizzo IP è A livello di regione o Globale.
    • Se prenoti un indirizzo IP statico per un bilanciatore del carico globale, scegli Globale e fai clic su Prenota.
    • Se prenoti un indirizzo IP statico per una VM o un regionale, scegli A livello di regione, quindi seleziona regione in cui creare l'indirizzo.
  7. Se prenoti un indirizzo IPv6 esterno a livello di regione, scegli anche le seguenti:

    • Rete: la rete VPC
    • Subnet: la subnet da cui assegnare la rete statica a livello di regione Indirizzo IPv6
    • Tipo di endpoint: scegli Istanza VM o Bilanciatore del carico di rete
  8. (Facoltativo) Se prenoti l'indirizzo IP esterno statico per una VM, Nell'elenco Collegato a, seleziona una VM di collegare l'indirizzo IP.

  9. Fai clic su Prenota per prenotare l'indirizzo IP.

gcloud

Per prenotare un indirizzo IP esterno statico, utilizza il metodo Comando gcloud compute addresses create.

Segui le istruzioni riportate di seguito per prenotare un indirizzo IPv4 o IPv6 esterno statico:

Indirizzo IP globale

Per prenotare un indirizzo IP globale:
  gcloud compute addresses create ADDRESS_NAME \
      --global \
      --ip-version [IPV4 | IPV6]
  
.
.

Indirizzo IPv4 esterno regionale

Per prenotare un indirizzo IPv4 esterno a livello di regione:
   gcloud compute addresses create ADDRESS_NAME \
       --region=REGION
   
.
.

Indirizzo IPv6 esterno a livello di regione

Per prenotare un indirizzo IPv6 esterno a livello di regione:
   gcloud compute addresses create ADDRESS_NAME \
       --region=REGION \
       --subnet=SUBNET_NAME \
       --ip-version=IPV6 \
       --endpoint-type=[VM | NETLB]
   
.

Sostituisci quanto segue:

  • ADDRESS_NAME: il nome che vuoi associare a questo indirizzo.
  • REGION: per gli indirizzi IP esterni a livello di regione, specifica la regione in cui vuoi prenotare questo indirizzo. Questa regione deve trovarsi nella stessa regione della risorsa a cui vuoi collegare Indirizzo IP.
  • SUBNET_NAME: per gli indirizzi IPv6 esterni a livello di regione, specifica la subnet da cui assegnare l'indirizzo IPv6 regionale statico. La La subnet deve avere un intervallo di indirizzi IPv6 esterno assegnato.
  • [IPV4 | IPV6]: per gli indirizzi IP globali, e specificare la versione IP, IPv4 o IPv6. Per esterni a livello di regione Per gli indirizzi IPv6, specifica IPv6. Un intervallo IPv6 /96 viene assegnato dalla subnet specificata.
  • VM | NETLB: per gli indirizzi IPv6 esterni a livello di regione, specificare il tipo di endpoint; che si tratti di una VM o di un bilanciatore del carico di rete.

Per visualizzare il risultato, utilizza il Comando gcloud compute addresses describe:

gcloud compute addresses describe ADDRESS_NAME

Terraform

Puoi utilizzare lo google_compute_address risorsa per creare un indirizzo IP esterno a livello di regione.

resource "google_compute_address" "default" {
  name   = "my-test-static-ip-address"
  region = "us-central1"
}

L'esempio seguente mostra come utilizzare il parametro google_compute_global_address risorsa per creare un indirizzo IPv6 esterno globale:

resource "google_compute_global_address" "default" {
  project      = var.project_id # Replace this with your service project ID in quotes
  name         = "ipv6-address"
  address_type = "EXTERNAL"
  ip_version   = "IPV6"
}

API

  • Per creare un indirizzo IPv4 a livello di regione, chiama il metodo Metodo addresses.insert:

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

    Il corpo della richiesta deve contenere quanto segue:

    {
      "name": "ADDRESS_NAME"
    }
    

    Sostituisci quanto segue:

    • PROJECT_ID: l'ID progetto per questa richiesta
    • REGION: il nome della regione per questo richiesta
    • ADDRESS_NAME: il nome che vuoi associa all'indirizzo
  • Per gli indirizzi IPv4 statici globali, chiama il metodo Metodo globalAddresses.insert:

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

    Il corpo della richiesta deve contenere quanto segue:

    {
      "name": "ADDRESS_NAME"
    }
    
  • Per gli indirizzi IPv6 statici globali, chiama il metodo Metodo globalAddresses.insert:

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

    Il corpo della richiesta deve contenere quanto segue:

    {
      "name": "ADDRESS_NAME",
      "ipVersion": "IPV6"
    }
    

    Per vedere il risultato, utilizza Metodo addresses.get.

  • Per gli indirizzi IPv6 statici a livello di regione, richiama il metodo Metodo addresses.insert:

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

    Il corpo della richiesta deve contenere quanto segue:

    {
      "name": "ADDRESS_NAME",
      "ipVersion": "IPV6",
      "ipv6EndpointType": "VM|LB",
      "networkTier": "PREMIUM",
      "subnetwork": "SUBNET"
    }
    

    Sostituisci SUBNET con la subnet per questo progetto.

    Per vedere il risultato, utilizza Metodo addresses.get.

Vai

import (
	"context"
	"fmt"
	"io"

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

// reserveNewRegionalExternal reserves a new regional external IP address in Google Cloud Platform.
func reserveNewRegionalExternal(w io.Writer, projectID, region, addressName string, isPremium bool) (*computepb.Address, error) {
	// projectID := "your_project_id"
	// region := "europe-central2"
	// addressName := "your_address_name"
	// isPremium := true
	ctx := context.Background()

	networkTier := computepb.AccessConfig_STANDARD.String()
	if isPremium {
		networkTier = computepb.AccessConfig_PREMIUM.String()
	}

	address := &computepb.Address{
		Name:        &addressName,
		NetworkTier: &networkTier,
	}

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

	req := &computepb.InsertAddressRequest{
		Project:         projectID,
		Region:          region,
		AddressResource: address,
	}

	op, err := client.Insert(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("unable to reserve regional address: %w", err)
	}

	err = op.Wait(ctx)
	if err != nil {
		return nil, fmt.Errorf("waiting for the regional address reservation operation to complete: %w", err)
	}

	addressResult, err := client.Get(ctx, &computepb.GetAddressRequest{
		Project: projectID,
		Region:  region,
		Address: addressName,
	})
	if err != nil {
		return nil, fmt.Errorf("unable to get reserved regional address: %w", err)
	}

	fmt.Fprintf(w, "Regional address %v reserved: %v", addressName, addressResult.GetAddress())

	return addressResult, err
}

// reserveNewGlobalExternal reserves a new global external IP address in Google Cloud Platform.
func reserveNewGlobalExternal(w io.Writer, projectID, addressName string, isV6 bool) (*computepb.Address, error) {
	// projectID := "your_project_id"
	// addressName := "your_address_name"
	// isV6 := false
	ctx := context.Background()
	ipVersion := computepb.Address_IPV4.String()
	if isV6 {
		ipVersion = computepb.Address_IPV6.String()
	}

	address := &computepb.Address{
		Name:      &addressName,
		IpVersion: &ipVersion,
	}

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

	req := &computepb.InsertGlobalAddressRequest{
		Project:         projectID,
		AddressResource: address,
	}

	op, err := client.Insert(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("unable to reserve global address: %w", err)
	}

	err = op.Wait(ctx)
	if err != nil {
		return nil, fmt.Errorf("waiting for the global address reservation operation to complete: %w", err)
	}

	addressResult, err := client.Get(ctx, &computepb.GetGlobalAddressRequest{
		Project: projectID,
		Address: addressName,
	})
	if err != nil {
		return nil, fmt.Errorf("unable to get reserved global address: %w", err)
	}

	fmt.Fprintf(w, "Global address %v reserved: %v", addressName, addressResult.GetAddress())

	return addressResult, nil
}

Java


import com.google.cloud.compute.v1.Address;
import com.google.cloud.compute.v1.Address.AddressType;
import com.google.cloud.compute.v1.Address.IpVersion;
import com.google.cloud.compute.v1.Address.NetworkTier;
import com.google.cloud.compute.v1.AddressesClient;
import com.google.cloud.compute.v1.GlobalAddressesClient;
import com.google.cloud.compute.v1.InsertAddressRequest;
import com.google.cloud.compute.v1.InsertGlobalAddressRequest;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ReserveNewExternalAddress {

  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";
    // Address name you want to use.
    String addressName = "your-address-name";
    // 'IPV4' or 'IPV6' depending on the IP version. IPV6 if True. Option only for global regions.
    boolean ipV6 = false;
    // 'STANDARD' or 'PREMIUM' network tier. Standard option available only in regional ip.
    boolean isPremium = false;
    // region (Optional[str]): The region to reserve the IP address in, if regional.
    // Must be None if global.
    String region = null;

    reserveNewExternalIpAddress(projectId, addressName, ipV6, isPremium, region);
  }

  // Reserves a new external IP address in the specified project and region.
  public static List<Address> reserveNewExternalIpAddress(String projectId, String addressName,
                                                          boolean ipV6, boolean isPremium,
                                                          String region)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {

    String ipVersion = ipV6 ? IpVersion.IPV6.name() : IpVersion.IPV4.name();
    String networkTier = !isPremium && region != null
            ? NetworkTier.STANDARD.name() : NetworkTier.PREMIUM.name();

    Address.Builder address = Address.newBuilder()
            .setName(addressName)
            .setAddressType(AddressType.EXTERNAL.name())
            .setNetworkTier(networkTier);

    // Use global client if no 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 (GlobalAddressesClient client = GlobalAddressesClient.create()) {
        address.setIpVersion(ipVersion);

        InsertGlobalAddressRequest addressRequest = InsertGlobalAddressRequest.newBuilder()
                .setProject(projectId)
                .setRequestId(UUID.randomUUID().toString())
                .setAddressResource(address.build())
                .build();

        client.insertCallable().futureCall(addressRequest).get(30, TimeUnit.SECONDS);

        return Lists.newArrayList(client.list(projectId).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 (AddressesClient client = AddressesClient.create()) {
        address.setRegion(region);

        InsertAddressRequest addressRequest = InsertAddressRequest.newBuilder()
                .setProject(projectId)
                .setRequestId(UUID.randomUUID().toString())
                .setAddressResource(address.build())
                .setRegion(region)
                .build();

        client.insertCallable().futureCall(addressRequest).get(30, TimeUnit.SECONDS);

        return Lists.newArrayList(client.list(projectId, region).iterateAll());
      }
    }
  }
}

Python

from typing import 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 reserve_new_external_ip_address(
    project_id: str,
    address_name: str,
    is_v6: bool = False,
    is_premium: bool = False,
    region: Optional[str] = None,
):
    """
    Reserves a new external IP address in the specified project and region.

    Args:
    project_id (str): Your Google Cloud project ID.
    address_name (str): The name for the new IP address.
    is_v6 (bool): 'IPV4' or 'IPV6' depending on the IP version. IPV6 if True.
    is_premium (bool): 'STANDARD' or 'PREMIUM' network tier. Standard option available only in regional ip.
    region (Optional[str]): The region to reserve the IP address in, if regional. Must be None if global.

    Returns:
    None
    """

    ip_version = "IPV6" if is_v6 else "IPV4"
    network_tier = "STANDARD" if not is_premium and region else "PREMIUM"

    address = Address(
        name=address_name,
        address_type="EXTERNAL",
        network_tier=network_tier,
    )
    if not region:  # global IP address
        client = GlobalAddressesClient()
        address.ip_version = ip_version
        operation = client.insert(project=project_id, address_resource=address)
    else:  # regional IP address
        address.region = region
        client = AddressesClient()
        operation = client.insert(
            project=project_id, region=region, address_resource=address
        )

    operation.result()

    print(f"External IP address '{address_name}' reserved successfully.")

Promuovi un indirizzo IP esterno temporaneo

Se la tua VM ha indirizzo IP esterno temporaneo e assegnare in modo permanente l'indirizzo IP al progetto, da un indirizzo IP esterno temporaneo a un indirizzo IP esterno statico. Promozione di un un indirizzo IP esterno temporaneo da prenotare non fa sì che Google Cloud di pacchetti inviati alla VM. Sono inclusi i pacchetti inviati alla VM direttamente o tramite un bilanciatore del carico.

Console

  1. Vai alla pagina Indirizzi IP.

    Vai a indirizzi IP

  2. Fai clic su Indirizzi IP esterni.
  3. (Facoltativo) Nel campo Filtro, cerca l'indirizzo IP temporaneo che vuoi promuovere.
  4. Nel menu Altre azioni () dell'indirizzo IP che vuoi promuovere, seleziona Promuovi a indirizzo IP statico.
  5. Inserisci un nome per il nuovo indirizzo IP statico e fai clic su Prenota.

gcloud

Usa le seguenti istruzioni per promuovere un IPv4 o IPv6 esterno statico indirizzo:

  • a promuovere un indirizzo IPv4 esterno temporaneo a un indirizzo IPv4 esterno statico , fornire l'indirizzo IP esterno temporaneo utilizzando Flag --addresses con Comando compute addresses create. Utilizza il flag region per promuovere un indirizzo IP temporaneo a livello di regione oppure il flag global per promuovere un indirizzo IP globale temporaneo.

    gcloud compute addresses create ADDRESS_NAME --addresses=IP_ADDRESS \
        [--region=REGION | --global]
    

    Sostituisci quanto segue:

    • ADDRESS_NAME: il nome che vuoi associare a questo indirizzo.
    • IP_ADDRESS: l'indirizzo IP che vuoi da promuovere.
    • REGION: la regione dell'IP a livello di regione a cui appartiene l'indirizzo email.

    • a promuovere un indirizzo IPv6 esterno temporaneo a livello di regione a un indirizzo indirizzo IPv6 esterno regionale, fornisci l'IP esterno temporaneo di destinazione utilizzando il flag --addresses con Comando compute addresses create.

    gcloud compute addresses create ADDRESS_NAME \
        --region=REGION \
        --addresses=IPV6_ADDRESS \
        --prefix-length=96
    

    Sostituisci quanto segue:

    • ADDRESS_NAME: un nome per l'indirizzo IP risorsa.
    • REGION: la regione dell'indirizzo IPv6 risorsa.
    • IPV6_ADDRESS: l'indirizzo IPv6 che stai promozione.

API

Per promuovere un indirizzo IP a livello di regione temporaneo, chiama il metodo Metodo addresses.insert:

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

Per promuovere un indirizzo IP globale temporaneo, effettua una richiesta POST all'indirizzo seguente URI:

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

Specifica i valori per i campi obbligatori del corpo della richiesta:

  • Per gli indirizzi IPv4, il corpo della richiesta deve contenere quanto segue campi:

    {
      "name": "ADDRESS_NAME",
      "address": "IPV4_ADDRESS"
      "addressType": "EXTERNAL"
    }
    
  • Per gli indirizzi IPv6, il corpo della richiesta deve contenere quanto segue campi:

    {
      "name": "ADDRESS_NAME",
      "address": "IPV6_ADDRESS"
      "prefixLength": 96
      "addressType": "EXTERNAL"
    }
    

    Sostituisci quanto segue:

    • ADDRESS_NAME: il nome che vuoi associa a questo indirizzo
    • IPV4_ADDRESS|IPV6_ADDRESS: il protocollo IPv4 o IPv6 l'indirizzo che vuoi promuovere
    • REGION: la regione in cui l'IPv4 o IPv6 indirizzo appartiene a
    • PROJECT_ID: l'ID progetto per questa richiesta

Vai

import (
	"context"
	"fmt"
	"io"

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

// promoteEphemeralAddress promotes an ephemeral IP address to a reserved static external IP address.
func promoteEphemeralAddress(w io.Writer, projectID, region, ephemeralIP, addressName string) error {
	// projectID := "your_project_id"
	// region := "europe-central2"
	// ephemeral_ip := "214.123.100.121"
	ctx := context.Background()

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

	addressResource := &computepb.Address{
		Name:        proto.String(addressName),
		AddressType: proto.String("EXTERNAL"),
		Address:     proto.String(ephemeralIP),
	}

	req := &computepb.InsertAddressRequest{
		Project:         projectID,
		Region:          region,
		AddressResource: addressResource,
	}

	op, err := client.Insert(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to insert address promoted: %v", err)
	}

	// Wait for the operation to complete
	err = op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("failed to complete promotion operation: %v", err)
	}

	fmt.Fprintf(w, "Ephemeral IP %s address promoted successfully", ephemeralIP)
	return nil
}

Java


import com.google.cloud.compute.v1.Address;
import com.google.cloud.compute.v1.Address.AddressType;
import com.google.cloud.compute.v1.AddressesClient;
import com.google.cloud.compute.v1.InsertAddressRequest;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class PromoteEphemeralIp {

  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";
    // Ephemeral IP address to promote.
    String ephemeralIp = "your-ephemeralIp";
    // Name of the address to assign.
    String addressName = "your-addressName";

    promoteEphemeralIp(projectId, region, ephemeralIp, addressName);
  }

  // Promote ephemeral IP found on the instance to a static IP.
  public static List<Address> promoteEphemeralIp(String projectId, String region,
                                                 String ephemeralIp, String addressName)
          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 (AddressesClient client = AddressesClient.create()) {
      Address addressResource = Address.newBuilder()
              .setName(addressName)
              .setRegion(region)
              .setAddressType(AddressType.EXTERNAL.name())
              .setAddress(ephemeralIp)
              .build();

      InsertAddressRequest addressRequest = InsertAddressRequest.newBuilder()
              .setRegion(region)
              .setProject(projectId)
              .setAddressResource(addressResource)
              .setRequestId(UUID.randomUUID().toString())
              .build();

      client.insertCallable().futureCall(addressRequest).get(30, TimeUnit.SECONDS);

      return Lists.newArrayList(client.list(projectId, region).iterateAll());
    }
  }
}

Python

import uuid

from google.cloud.compute_v1 import AddressesClient
from google.cloud.compute_v1.types import Address


def promote_ephemeral_ip(project_id: str, ephemeral_ip: str, region: str):
    """
    Promote ephemeral IP found on the instance to a static IP.

    Args:
        project_id (str): Project ID.
        ephemeral_ip (str): Ephemeral IP address to promote.
        region (str): Region where the VM and IP is located.
    """
    addresses_client = AddressesClient()

    # Create a new static IP address using existing ephemeral IP
    address_resource = Address(
        name=f"ip-reserved-{uuid.uuid4()}",  # new name for promoted IP address
        region=region,
        address_type="EXTERNAL",
        address=ephemeral_ip,
    )
    operation = addresses_client.insert(
        project=project_id, region=region, address_resource=address_resource
    )
    operation.result()

    print(f"Ephemeral IP {ephemeral_ip} has been promoted to a static IP.")

L'indirizzo IP esterno rimane collegato alla VM anche dopo a un indirizzo IP esterno statico. Se devi assegnare un indirizzo IP esterno statico appena promosso a un'altra risorsa, annullare l'assegnazione dell'indirizzo IP esterno statico alla VM esistente.

Elenca indirizzi IP esterni statici

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

Descrivere un indirizzo IP esterno statico

Per ottenere informazioni su un indirizzo IP esterno statico, segui questi passaggi.

Console

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

    Vai a indirizzi IP

  2. Fai clic su Indirizzi IP esterni.

  3. Fai clic sull'indirizzo IP su cui vuoi visualizzare ulteriori informazioni.

gcloud

Usa il comando gcloud compute addresses describe. Sostituisci ADDRESS_NAME con il nome di l'indirizzo IP esterno che vuoi descrivere.

  • Per un indirizzo IPv4 o IPv6 globale, utilizza il seguente comando:

    gcloud compute addresses describe ADDRESS_NAME --global
  • Per un indirizzo IPv4 o IPv6 a livello di regione, utilizza il comando seguente:

    gcloud compute addresses describe ADDRESS_NAME --region=REGION

API

  • Per descrivere un indirizzo IPv4 o IPv6 a livello di regione, chiama il metodo Metodo addresses.get:

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

    Sostituisci quanto segue:

    • PROJECT_ID: l'ID progetto per la richiesta
    • REGION: il nome della regione per la richiesta
    • ADDRESS_NAME: il nome dell'indirizzo IP
  • Per descrivere un indirizzo IPv4 o IPv6 globale, chiama il metodo Metodo globalAddresses.get:

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

    Sostituisci quanto segue:

    • PROJECT_ID: l'ID progetto per la richiesta
    • ADDRESS_NAME: il nome dell'indirizzo IP

Vai

import (
	"context"
	"fmt"
	"io"

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

// getExternalAddress retrieves the external IP address of the given address.
func getRegionalExternal(w io.Writer, projectID, region, addressName string) (*computepb.Address, error) {
	// projectID := "your_project_id"
	// region := "europe-west3"
	// addressName := "your_address_name"

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

	req := &computepb.GetAddressRequest{
		Project: projectID,
		Region:  region,
		Address: addressName,
	}

	address, err := addressesClient.Get(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("unable to get address: %w", err)
	}

	fmt.Fprintf(w, "Regional address %s has external IP address: %s\n", addressName, address.GetAddress())

	return address, nil
}

func getGlobalExternal(w io.Writer, projectID, addressName string) (*computepb.Address, error) {

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

	req := &computepb.GetGlobalAddressRequest{
		Project: projectID,
		Address: addressName,
	}

	address, err := globalAddressesClient.Get(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("unable to get address: %w", err)
	}

	fmt.Fprintf(w, "Global address %s has external IP address: %s\n", addressName, address.GetAddress())

	return address, nil
}

Java


import com.google.cloud.compute.v1.Address;
import com.google.cloud.compute.v1.AddressesClient;
import com.google.cloud.compute.v1.GetAddressRequest;
import com.google.cloud.compute.v1.GetGlobalAddressRequest;
import com.google.cloud.compute.v1.GlobalAddressesClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class GetStaticIpAddress {

  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";
    // Name of the address to assign.
    String addressName = "your-addressName";

    getStaticIpAddress(projectId, region, addressName);
  }

  // Retrieves a static external IP address, either regional or global.
  public static Address getStaticIpAddress(String projectId, String region, String addressName)
          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()) {
        GetAddressRequest request = GetAddressRequest.newBuilder()
                .setProject(projectId)
                .setRegion(region)
                .setAddress(addressName)
                .build();

        return client.get(request);
      }
    } 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()) {
        GetGlobalAddressRequest request = GetGlobalAddressRequest.newBuilder()
                .setProject(projectId)
                .setAddress(addressName)
                .build();

        return client.get(request);
      }
    }
  }
}

Python

from typing import 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 get_static_ip_address(
    project_id: str, address_name: str, region: Optional[str] = None
) -> Address:
    """
    Retrieves a static external IP address, either regional or global.

    Args:
    project_id (str): project ID.
    address_name (str): The name of the IP address.
    region (Optional[str]): The region of the IP address if it's regional. None if it's global.

    Raises: google.api_core.exceptions.NotFound: in case of address not found

    Returns:
    Address: The Address object containing details about the requested IP.
    """
    if region:
        # Use regional client if a region is specified
        client = AddressesClient()
        address = client.get(project=project_id, region=region, address=address_name)
    else:
        # Use global client if no region is specified
        client = GlobalAddressesClient()
        address = client.get(project=project_id, address=address_name)

    return address

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.

Se utilizzi la console Google Cloud, puoi rilasciare un indirizzo IP statico solo se non è usato da un'altra risorsa.

Se utilizzi gcloud CLI o l'API, puoi rilasciare un indirizzo IP, indipendentemente dal fatto che sia utilizzato o meno da un'altra risorsa.

  • Se l'indirizzo IP non è utilizzato da una risorsa, viene al pool di indirizzi IP esterni disponibili,

  • Se l'indirizzo IP è utilizzato da una risorsa, rimane collegato alla fino a quando non viene eliminata.

Console

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

    Vai a indirizzi IP

  2. Fai clic su Indirizzi IP esterni.

  3. (Facoltativo) Nel campo Filtro, inserisci static e seleziona Statico : tipo dall'elenco a discesa.

  4. Seleziona l'indirizzo IP esterno statico che vuoi rilasciare.

  5. Fai clic su Rilascia indirizzo statico.

    Se non vedi questa opzione, fai clic sul menu Altre azioni. () nella barra dei menu in alto, quindi seleziona Rilascia l'indirizzo statico dall'elenco.

gcloud

Utilizza la Comando compute addresses delete:

gcloud compute addresses delete ADDRESS_NAME

Sostituisci ADDRESS_NAME con il nome del protocollo IPv4 o Indirizzo IPv6 da rilasciare.

API

  • Per rilasciare un indirizzo IPv4 o IPv6 a livello di regione, chiama il metodo Metodo addresses.delete:

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

    Sostituisci quanto segue:

    • PROJECT_ID: l'ID progetto per questa richiesta
    • REGION: il nome della regione per questo richiesta
    • ADDRESS_NAME: il nome dell'indirizzo IP
  • Per rilasciare un indirizzo IPv4 o IPv6 globale, chiama il metodo Metodo globalAddresses.delete:

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

    Sostituisci quanto segue:

    • ADDRESS_NAME: il nome dell'indirizzo IP
    • PROJECT_ID: l'ID progetto per questa richiesta

Vai

import (
	"context"
	"fmt"
	"io"

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

// releaseRegionalStaticExternal releases a static regional external IP address.
func releaseRegionalStaticExternal(w io.Writer, projectID, region, addressName string) error {
	// projectID := "your_project_id"
	// region := "us-central1"
	// addressName := "your_address_name"

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

	req := &computepb.DeleteAddressRequest{
		Project: projectID,
		Region:  region,
		Address: addressName,
	}

	op, err := addressesClient.Delete(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to release static external IP address: %w", err)
	}

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

	fmt.Fprintf(w, "Static external IP address released\n")

	return nil
}

// releaseGlobalStaticExternal releases a static global external IP address.
func releaseGlobalStaticExternal(w io.Writer, projectID, addressName string) error {
	// projectID := "your_project_id"
	// addressName := "your_address_name"

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

	req := &computepb.DeleteGlobalAddressRequest{
		Project: projectID,
		Address: addressName,
	}

	op, err := addressesClient.Delete(ctx, req)
	if err != nil {
		return fmt.Errorf("unable to release static external IP address: %w", err)
	}

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

	fmt.Fprintf(w, "Static external IP address released\n")

	return nil
}

Java


import com.google.cloud.compute.v1.AddressesClient;
import com.google.cloud.compute.v1.DeleteAddressRequest;
import com.google.cloud.compute.v1.DeleteGlobalAddressRequest;
import com.google.cloud.compute.v1.GlobalAddressesClient;
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 ReleaseStaticAddress {

  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";
    // The region to reserve the IP address in, if regional. Must be None if global
    String region = "your-region =";
    // Name of the address to release.
    String addressName = "your-addressName";

    releaseStaticAddress(projectId, addressName, region);
  }

  // Releases a static external IP address that is currently reserved.
  // This action requires that the address is not being used by any forwarding rule.
  public static void releaseStaticAddress(String projectId, String addressName, String region)
          throws IOException, ExecutionException, InterruptedException, TimeoutException {
    Operation operation;
    // Use global client if no 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 (GlobalAddressesClient client = GlobalAddressesClient.create()) {
        DeleteGlobalAddressRequest request = DeleteGlobalAddressRequest.newBuilder()
                .setProject(projectId)
                .setAddress(addressName)
                .build();

        operation = client.deleteCallable().futureCall(request).get(30, TimeUnit.SECONDS);
      }
    } 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 (AddressesClient client = AddressesClient.create()) {
        DeleteAddressRequest request = DeleteAddressRequest.newBuilder()
                .setProject(projectId)
                .setRegion(region)
                .setAddress(addressName)
                .build();

        operation = client.deleteCallable().futureCall(request).get(30, TimeUnit.SECONDS);
      }
    }
    if (operation.hasError()) {
      System.out.printf("Can't release external IP address '%s'. Caused by : %s",
              addressName, operation.getError());
    }
    System.out.printf("External IP address '%s' released successfully.", addressName);
  }
}

Python

from typing import Optional

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


def release_external_ip_address(
    project_id: str,
    address_name: str,
    region: Optional[str] = None,
) -> None:
    """
    Releases a static external IP address that is currently reserved.
    This action requires that the address is not being used by any forwarding rule.

    Args:
        project_id (str): project ID.
        address_name (str): name of the address to release.
        region (Optional[str]): The region to reserve the IP address in, if regional. Must be None if global.


    """
    if not region:  # global IP address
        client = GlobalAddressesClient()
        operation = client.delete(project=project_id, address=address_name)
    else:  # regional IP address
        client = AddressesClient()
        operation = client.delete(
            project=project_id, region=region, address=address_name
        )

    operation.result()
    print(f"External IP address '{address_name}' released successfully.")

Passaggi successivi