预留静态外部 IP 地址

您可以预留静态外部 IP 地址。您还可以列出和释放预留的静态外部 IP 地址。如需为虚拟机实例分配静态外部 IP 地址,请参阅配置静态外部 IP 地址

外部 IP 地址可以是静态地址或临时地址。如果虚拟机需要固定不变的外部 IP 地址,您可以获取静态外部 IP 地址。您可以预留新的外部 IP 地址,也可以提升现有的临时外部 IP 地址。

如果您需要使用静态内部 IP 地址,请改为参阅预留静态内部 IP 地址

准备工作

  • 了解 IP 地址
  • 了解静态外部 IP 地址的配额和限制
  • 了解外部 IP 地址价格
  • 如果您尚未设置身份验证,请进行设置。 身份验证是通过其进行身份验证以访问 Google Cloud 服务和 API 的过程。如需从本地开发环境运行代码或示例,您可以按如下方式进行身份验证。

    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

    Install the Google Cloud CLI, then initialize it by running the following command:

    gcloud init

    Terraform

    如需在本地开发环境中使用本页面上的 Terraform 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

    如需了解详情,请参阅 Google Cloud 身份验证文档中的 为本地开发环境设置 ADC

    REST

    如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的凭据。

      Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init

    如需了解详情,请参阅 Google Cloud 身份验证文档中的使用 REST 时进行身份验证

所需的角色

如需获得预留和管理静态 IP 地址所需的权限,请让您的管理员为您授予项目的 Compute Network Admin (roles/compute.networkAdmin) IAM 角色。如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

此预定义角色可提供预留和管理静态 IP 地址所需的权限。如需查看所需的确切权限,请展开所需权限部分:

所需权限

预留和管理静态 IP 地址需要以下权限:

  • 针对该 IP 地址的 compute.addresses.create 权限
  • 针对该 IP 地址的 compute.addresses.createInternal 权限
  • 针对网络的 compute.networks.list 权限
  • 针对子网的 compute.subnetworks.use 权限
  • 针对子网的 compute.subnetworks.list 权限

您也可以使用自定义角色或其他预定义角色来获取这些权限。

静态外部 IP 地址简介

静态外部 IP 地址是为您的资源预留直到您决定将其释放的 IP 地址。如果您有一个客户或用户要用来访问服务的 IP 地址,您可以预留该 IP 地址,以仅供您的资源使用。您也可以将临时外部 IP 地址升级为静态外部 IP 地址。

如需了解详情,请参阅 IP 地址

下表列出了 Google Cloud 支持的静态外部 IP 地址。

IP 地址类型 资源 IP 范围 来源 关联对象:
区域级外部 IPv4 地址 虚拟机和区域级负载均衡器 /32 Google 的外部 IP 地址池 项目
区域级外部 IPv6 地址 虚拟机和支持的区域级负载均衡器 /96 子网的外部 IPv6 地址范围 子网
全球外部 IPv4 地址 全球负载均衡器 /32 Google 的外部 IP 地址池 项目
全球外部 IPv6 地址 全球负载均衡器 /64 Google 的外部 IP 地址池 项目

如需查看区域级和全球负载均衡器列表,请参阅负载均衡器类型摘要

限制

  • 一次只能有一个资源使用某个静态外部 IP 地址。

  • IP 地址分配给资源后,无法分辨该 IP 地址是静态地址还是临时地址。您可以将 IP 地址与为相关项目预留的静态外部 IP 地址列表进行比较。如需查看项目可用的静态外部 IP 地址列表,请使用 gcloud compute addresses list 子命令

  • 每个虚拟机都可以有多个网络接口,并且每个接口可以分配有以下 IP 地址:

    • 内部 IPv4 地址(必需)
    • 外部 IPv4 地址
    • /96 IPv6 地址范围,可以是内部或外部,但不能同时是两者
  • 您无法更改静态 IP 地址的名称。

  • 分配的外部 IP 地址与虚拟机位于同一物理主机上,并且与虚拟机位于同一区域,可用于包括路由、延迟时间和定价在内的所有用途。无论互联网地理位置查找信息如何,情况都是如此。

注意:网络接口可以接收来自多个转发规则的流量,这些转发规则可能适用于其他外部 IP 地址。任意数量的外部 IP 地址都可以通过这些转发规则来引用某个网络接口,但每个网络接口只能分配有一个外部 IPv4 地址范围和一个外部 /96 IPv6 地址范围。

如需详细了解负载均衡和转发规则,请参阅负载均衡文档。

保留新的静态外部 IP 地址

预留该地址后,请在创建新虚拟机时将其分配给新虚拟机,或将其分配给现有虚拟机

控制台

  1. 在 Google Cloud 控制台中,进入 IP 地址页面。

    转到“IP 地址”

  2. 点击预留外部静态 IP 地址
  3. 名称字段中,输入 IP 地址名称。
  4. 指定网络服务层级是高级还是标准。 只有优质层级支持 IPv6 静态地址预留。
  5. 指定此 IP 地址是 IPv4 地址还是 IPv6 地址。
  6. 指定此 IP 地址是区域还是全球
    • 如果您要为全球负载均衡器预留静态 IP 地址,请选择全球,然后点击预留
    • 如果您要为虚拟机或区域级负载均衡器预留静态 IP 地址,请选择区域级,然后选择要在其中创建该地址的区域。
  7. 如果您要预留区域级外部 IPv6 地址,则还要选择以下各项:

    • 网络:VPC 网络
    • 子网:要从中分配静态区域级 IPv6 地址的子网
    • 端点类型:选择虚拟机实例网络负载均衡器
  8. 可选:如果您要为虚拟机预留静态外部 IP 地址,请在附加目标列表中,选择要将该 IP 地址附加到的虚拟机。

  9. 点击预留以预留该 IP 地址。

gcloud

如需预留静态外部 IP 地址,请使用 gcloud compute addresses create 命令

请按照以下说明预留静态外部 IPv4 或 IPv6 地址:

全球 IP 地址

如需预留全球 IP 地址,请运行以下命令:
  gcloud compute addresses create ADDRESS_NAME \
      --global \
      --ip-version [IPV4 | IPV6]
  

区域外部 IPv4 地址

如需预留区域级外部 IPv4 地址,请运行以下命令:
   gcloud compute addresses create ADDRESS_NAME \
       --region=REGION
   

区域级外部 IPv6 地址

如需预留区域级外部 IPv6 地址,请运行以下命令:
   gcloud compute addresses create ADDRESS_NAME \
       --region=REGION \
       --subnet=SUBNET_NAME \
       --ip-version=IPV6 \
       --endpoint-type=[VM | NETLB]
   

替换以下内容:

  • ADDRESS_NAME:您要与此地址关联的名称。
  • REGION:对于区域级外部 IP 地址,请指定您要在其中预留此地址的区域。此区域应为您要将 IP 地址附加到的资源所在的区域。
  • SUBNET_NAME:对于区域级外部 IPv6 地址,请指定要从中分配静态区域级 IPv6 地址的子网。该子网必须具有分配的外部 IPv6 地址范围
  • [IPV4 | IPV6]:对于全球 IP 地址,请指定 IP 版本(IPv4 或 IPv6)。对于区域级外部 IPv6 地址,请指定 IPv6。系统会从指定的子网分配 /96 IPv6 范围。
  • VM | NETLB:对于区域级外部 IPv6 地址,请指定端点类型;无论是虚拟机还是网络负载均衡器。

如需查看结果,请使用 gcloud compute addresses describe 命令

gcloud compute addresses describe ADDRESS_NAME

Terraform

您可以使用 google_compute_address 资源创建区域级外部 IP 地址。

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

以下示例展示了如何使用 google_compute_global_address 资源创建全球外部 IPv6 地址:

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

  • 如需创建区域 IPv4 地址,请调用区域 addresses.insert 方法

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

    请求正文应包含以下内容:

    {
      "name": "ADDRESS_NAME"
    }
    

    请替换以下内容:

    • PROJECT_ID:此请求的项目 ID
    • REGION:此请求的区域名称。
    • ADDRESS_NAME:您要与此地址关联的名称
  • 对于全球静态 IPv4 地址,请调用 globalAddresses.insert 方法

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

    请求正文应包含以下内容:

    {
      "name": "ADDRESS_NAME"
    }
    
  • 对于全球静态 IPv6 地址,请调用 globalAddresses.insert 方法

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

    请求正文应包含以下内容:

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

    如需查看结果,请使用 addresses.get 方法

  • 对于区域级静态 IPv6 地址,请调用 addresses.insert 方法

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

    请求正文应包含以下内容:

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

    SUBNET 替换为此项目的子网。

    如需查看结果,请使用 addresses.get 方法

Go

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

升级临时外部 IP 地址

如果实例具有临时外部 IP 地址,并且您要将该 IP 地址永久分配给项目,请将该临时外部 IP 地址提升为静态外部 IP 地址。将临时外部 IP 地址升级为预留的外部 IP 地址不会导致 Google Cloud 丢弃发送到实例的数据包。这包括直接发送或通过负载均衡器发送到实例的数据包。

控制台

  1. 转到 IP 地址页面。

    转到“IP 地址”

  2. 点击外部 IP 地址
  3. 可选:在过滤条件字段中,搜索要提升的临时 IP 地址。
  4. 在要提升的 IP 地址的更多操作菜单 () 中,选择提升为静态 IP 地址
  5. 输入新静态 IP 地址的名称,然后点击预留

gcloud

请按照以下说明提升静态外部 IPv4 或 IPv6 地址:

  • 如需将临时外部 IPv4 地址提升为静态外部 IPv4 地址,请通过将 --addresses 标志与 compute addresses create 命令结合使用来提供临时外部 IP 地址。 可以使用 region 标志升级临时区域 IP 地址,或者可以使用 global 标志升级临时全球 IP 地址。

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

    替换以下内容:

    • ADDRESS_NAME:您要与此地址关联的名称。
    • IP_ADDRESS:您要提升的 IP 地址。
    • REGION 是区域级 IP 地址所属的区域。
  • 如需将临时区域级外部 IPv6 地址提升为静态区域级外部 IPv6 地址,请通过将 --addresses 标志与 gcloud compute addresses create 命令结合使用来提供临时外部 IP 地址。

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

    替换以下内容:

    • ADDRESS_NAME:IP 地址资源的名称
    • REGION:IPv6 地址资源的区域
    • IPV6_ADDRESS:您要升级的 IPv6 地址。

API

如需升级临时地区 IP 地址,请调用 addresses.insert 方法

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

如需升级临时全球 IP 地址,请向以下 URI 发出 POST 请求:

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

为请求正文的必填字段指定值:

  • 对于 IPv4 地址,请求正文应包含以下字段:

    {
      "name": "ADDRESS_NAME",
      "address": "IPV4_ADDRESS"
      "addressType": "EXTERNAL"
    }
    
  • 对于 IPv6 地址,请求正文应包含以下字段:

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

    替换以下内容:

    • ADDRESS_NAME:您要与此地址关联的名称
    • IPV4_ADDRESS|IPV6_ADDRESS:您要提升的 IPv4 或 IPv6 地址
    • REGION:IPv4 或 IPv6 地址所属的区域
    • PROJECT_ID:此请求的项目 ID

Go

import (
	"context"
	"fmt"
	"io"

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

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

在外部 IP 地址升级为静态外部 IP 地址后,该地址仍然会附加到该实例。如果您需要将这个新升级的静态外部 IP 地址分配给另一个资源,请为现有实例取消分配该静态外部 IP 地址

列出静态外部 IP 地址

如需列出您为项目预留的静态外部 IP 地址,请按照以下步骤操作。

控制台

  1. 在 Google Cloud 控制台中,进入 IP 地址页面。

    进入“IP 地址”

  2. 点击外部 IP 地址

gcloud

使用 gcloud compute addresses list 命令

  • 如需列出所有 IP 地址,请使用以下命令:

    gcloud compute addresses list
  • 如需列出所有全球 IP 地址,请使用以下命令:

    gcloud compute addresses list --global
  • 如需列出给定区域中的所有区域级 IP 地址,请使用以下命令:

    gcloud compute addresses list \
        --regions=REGION
    

    REGION 替换为要列出其地址的区域。您可以通过指定以英文逗号分隔的区域名称来列出多个区域的地址:

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

API

  • 如需列出区域级 IPv4 或 IPv6 地址,请调用 addresses.list 方法

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

    替换以下内容:

    • PROJECT_ID:此请求的项目 ID
    • REGION:此请求的地区名称
  • 如需列出所有区域中的所有地址,请调用 addresses.aggregatedList 方法

    GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/aggregated/addresses
    
  • 如需列出全球 IPv4 或 IPv6 地址,请调用 globalAddresses.list 方法

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

    请替换以下内容:

    PROJECT_ID:此请求的项目 ID

Go

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

描述静态外部 IP 地址

如需获取有关静态外部 IP 地址的信息,请按照以下步骤操作。

控制台

  1. 在 Google Cloud 控制台中,进入 IP 地址页面。

    进入“IP 地址”

  2. 点击外部 IP 地址

  3. 点击要获取其详细信息的 IP 地址。

gcloud

使用 gcloud compute addresses describe 命令并将 ADDRESS_NAME 替换为您要描述的外部 IP 地址的名称。

  • 对于全球 IPv4 或 IPv6 地址,请使用以下命令:

    gcloud compute addresses describe ADDRESS_NAME --global
  • 对于区域级 IPv4 或 IPv6 地址,请使用以下命令:

    gcloud compute addresses describe ADDRESS_NAME --region=REGION

API

  • 如需描述区域级 IPv4 或 IPv6 地址,请调用 addresses.get 方法

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

    替换以下内容:

    • PROJECT_ID:请求的项目 ID。
    • REGION:此请求的区域名称
    • ADDRESS_NAME:IP 地址的名称
  • 如需描述全球 IPv4 或 IPv6 地址,请调用 globalAddresses.get 方法

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

    替换以下内容:

    • PROJECT_ID:请求的项目 ID。
    • ADDRESS_NAME:IP 地址的名称

Go

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

释放静态外部 IP 地址

如果您不再需要某个静态外部 IPv4 或 IPv6 地址,可以通过删除 IP 地址资源来释放该 IP 地址。

如果您使用 Google Cloud 控制台,则只有在静态 IP 地址未被其他资源使用时,才能释放该地址。

如果您使用 gcloud CLI 或 API,则无论 IP 地址是否正被其他资源使用,都可以释放该 IP 地址。

  • 如果 IP 地址未被资源使用,则会返回到可用外部 IP 地址池中。

  • 如果 IP 地址正在被资源使用,则在资源被删除前,该 IP 地址会一直与该资源关联。

控制台

  1. 在 Google Cloud 控制台中,进入 IP 地址页面。

    进入“IP 地址”

  2. 点击外部 IP 地址

  3. 可选:在过滤条件字段中,输入 static,然后从下拉列表中选择静态:类型

  4. 选择要释放的静态外部 IP 地址。

  5. 点击释放静态地址

    如果您没有看到此选项,请点击顶部菜单栏中的更多操作菜单 (),然后从列表中选择释放静态地址

gcloud

使用 compute addresses delete 命令

gcloud compute addresses delete ADDRESS_NAME

ADDRESS_NAME 替换为要释放的 IPv4 或 IPv6 地址的名称。

API

  • 如需释放区域级 IPv4 或 IPv6 地址,请调用 addresses.delete 方法

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

    替换以下内容:

    • PROJECT_ID:此请求的项目 ID
    • REGION:此请求的地区名称
    • ADDRESS_NAME:IP 地址的名称
  • 如需释放全球 IPv4 或 IPv6 地址,请调用 globalAddresses.delete 方法

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

    请替换以下内容:

    • ADDRESS_NAME:IP 地址的名称
    • PROJECT_ID:此请求的项目 ID

Go

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

后续步骤