使用路徑

本頁面說明如何建立及管理 Google Cloud虛擬私有雲 (VPC) 網路的路徑。本頁面假設您熟悉不同類型的 Google Cloud 路徑及路徑中所述的各類路徑特性。

每個新網路都具有兩類由系統產生的路徑:可以移除或替換的預設路徑,以及新網路中各個子網路專屬的子網路路徑。除非您刪除對應的子網路,否則無法移除子網路路徑。

除了系統產生的路徑之外,您也可以建立其他的自訂靜態路徑

列出虛擬私有雲網路的路徑

您可以使用 Google Cloud CLI 或 API 列出及查看下列類型路徑的詳細資料:

gcloud CLI 指令和 API 方法都不會顯示下列類型的路徑:

如要查看完整路徑,請使用 Google Cloud 控制台。如要列出及說明策略路由,請參閱「使用策略路由」。

主控台

  1. 前往 Google Cloud 控制台的「Routes」(路徑) 頁面。

    前往「Routes」(路徑)

  2. 在「有效路徑」分頁中,執行下列操作:

    • 選擇虛擬私有雲網路。
    • 選擇區域。
  3. 點按「查看」。

  4. 您可以依路徑類型、目的地 IP 範圍和下一個躍點類型等屬性進行篩選。

  5. 選用:按一下「顯示受抑制的路徑」切換鈕,即可查看受抑制的路徑。如要查看路線遭到停用的原因,請將滑鼠游標移至「狀態」欄中的圖示。

gcloud

如要列出及查看子網路路徑靜態路徑的詳細資料,請使用 gcloud compute routes 指令。這些指令不會顯示其他類型的路線。如要查看所有路徑,請使用 Google Cloud 控制台。

如要列出路徑,請按照下列步驟操作:

gcloud compute routes list \
    --filter="network=NETWORK_NAME" \
    --project=PROJECT_ID

如要取得路線詳細資料,請按照下列步驟操作:

gcloud compute routes describe ROUTE_NAME \
    --format="flattened()" \
    --project=PROJECT_ID

更改下列內容:

  • NETWORK_NAME:虛擬私有雲網路的名稱
  • PROJECT_ID:含有虛擬私有雲網路的專案 ID
  • ROUTE_NAME:路徑名稱

API

如要列出及查看子網路路徑靜態路徑的詳細資料,請使用 routes.listroutes.get 方法。這些方法不會顯示其他類型的路線。如要查看所有路徑,請使用 Google Cloud 控制台。

如要列出路徑,請按照下列步驟操作:

GET https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/routes?filter=network="NETWORK_URL

如要取得路線詳細資料,請按照下列步驟操作:

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

更改下列內容:

  • PROJECT_ID:含有虛擬私有雲網路的專案 ID
  • NETWORK_URL:虛擬私有雲網路的網址
  • ROUTE_NAME:路徑名稱

列出 VM 網路介面的適用路徑

您可以使用 Google Cloud 控制台查看 VM 網路介面的適用路徑。這項查看作業會縮小可用於輸出流量的路徑清單範圍。

如要查看 VM 特定網路介面的適用路徑,請按照下列步驟操作。

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往 VM 執行個體

  2. 在清單中找出 VM 執行個體,在資料列結尾的「更多動作」選單中,選取「查看網路詳細資料」

  3. 如果執行個體擁有多個網路介面,請在「Network interface details」(網路介面詳細資料) 區段中,選取要查看的網路介面。

  4. 在「防火牆和路徑詳細資料」部分,按一下「路徑」分頁標籤,即可查看套用至網路介面的所有路徑,這些路徑將依照路徑名稱排序。

新增及移除靜態路徑

您可以新增或移除虛擬私有雲網路的本機靜態路徑和依據政策的路徑。本節說明如何新增及刪除本機靜態路由。如要進一步瞭解如何新增及移除策略路徑,請參閱「使用策略路徑」。

新增或刪除子網路時,系統會自動新增或刪除子網路路徑。如要進一步瞭解如何新增及移除子網路,請參閱使用子網路

透過虛擬私有雲網路對等互連連線的虛擬私有雲網路中,所有路徑都必須在匯出這些路徑的虛擬私有雲網路中進行操作。詳情請參閱「路徑交換選項」。

新增靜態路徑前的注意事項

新增靜態路徑前,請先考量以下事項:

  • 請務必瞭解靜態路徑可使用的不同類型下一個躍點。如要瞭解不同類型的靜態路徑下一個躍點,包括支援 IPv6 目的地的躍點,請參閱「下一個躍點和功能」。
  • 除非使用混合式子網路,否則靜態路徑的目的地範圍不得與子網路或對等互連子網路路徑的目的地範圍相符,或是比該範圍更加具體明確。詳情請參閱「路徑總覽」中的與自訂靜態路徑的互動,以及「虛擬私有雲網路對等互連」說明文件中的子網路和靜態路徑互動
  • 使用自動模式 VPC 網路時如果要避免衝突,請勿建立目的地在 10.128.0.0/9 中的靜態路徑。詳情請參閱自動模式 IPv4 範圍
  • 自訂靜態路徑的目的地不能與任何內部的分配範圍重疊。
  • 在建立使用 VM 做為下一個躍點的自訂靜態路徑之前,請確保您已熟悉如何將執行個體做為下一個躍點。如果您選擇「下一個躍點執行個體」, Google Cloud 只會驗證在建立路徑時 VM 是否存在。
  • 如果您使用網路標記建立路徑,則只有具有該標記的 VM 會收到該路徑。不過,已加上標記的 VM 仍會接收所有沒有網路標記的路徑。

新增靜態路徑

為網路新增靜態路徑。如要進一步瞭解不同類型的靜態路徑下一個躍點,包括支援 IPv6 目的地的躍點,請參閱「下一個躍點和功能」。

主控台

  1. 前往 Google Cloud 控制台的「Routes」頁面。

    前往「Routes」(路徑)

  2. 按一下「路徑管理」分頁標籤。

  3. 按一下 [Create route] (建立路徑)

  4. 指定路徑的名稱和說明。

  5. 在「Network」(網路) 清單中,選取路徑的現有網路。

  6. 在「Route type」(路徑類型) 清單中,選取「Static route」(靜態路徑)

  7. 在「IP version」(IP 版本) 清單中,選取所需的 IP 版本:

    • 如要建立 IPv4 靜態路徑,請選取「IPv4」IPv4
    • 如要建立 IPv6 靜態路徑,請選取「IPv6」IPv6
  8. 指定目的地 IP 範圍。最廣的可能目的地為 IPv4 的 0.0.0.0/0 或 IPv6 的 ::/0

  9. 指定路徑的「priority」(優先等級)。 優先順序可設為 0 (最高優先順序) 至 65535 (最低優先順序)。

  10. 如要讓路徑僅適用於選取具有相符網路標記的執行個體,請在「Instance tags」(執行個體標記) 欄位中指定。保留空白欄位會使路徑適用於網路中的所有執行個體。

  11. 選取路徑的「下一個躍點」

    • 預設網際網路閘道:將封包傳送到網際網路,以及 Google API 和服務
    • 指定執行個體:將封包傳送到 VM 執行個體的網路介面。依名稱和區域指定 VM 執行個體。如果路由目的地是 IPv6 位址,VM 執行個體必須是雙重堆疊僅支援 IPv6 (搶先版)
    • 指定執行個體的 IP 位址:指定虛擬私有雲端網路中「現有執行個體」的 IP 位址。如要使用 IPv6 靜態路徑,執行個體必須是雙重堆疊。如要進一步瞭解有效的下一個躍點 IP 位址的重要限制,請參閱靜態路徑下一個躍點
    • 指定 VPN 通道使用靜態轉送,將封包傳送至現有的傳統版 VPN 通道。
    • 指定內部直通式網路負載平衡器的轉送規則:將封包傳遞至內部直通式網路負載平衡器,該負載平衡器由其內部轉送規則名稱和區域指定。轉送規則可以有 IPv4 或 IPv6 位址。您指定的轉送規則 IP 版本必須與您建立的靜態路徑 IP 版本相符。
  12. 點選「建立」

gcloud

使用下列 gcloud CLI 指令建立新的自訂靜態路徑:

gcloud compute routes create ROUTE_NAME \
    --network=NETWORK \
    --destination-range=DESTINATION_RANGE \
    --priority=PRIORITY \
    NEXT_HOP_SPECIFICATION

更改下列內容:

  • ROUTE_NAME:路徑名稱
  • NETWORK:包含路徑的 VPC 網路名稱
  • DESTINATION_RANGE:此路徑適用的目的地 IPv4 或 IPv6 位址。最廣的可能目的地為 IPv4 的 0.0.0.0/0 或 IPv6 的 ::/0
  • PRIORITY:路徑優先順序,範圍從 0 (最高優先順序) 到 65535 (最低優先順序)
  • NEXT_HOP_SPECIFICATION:靜態路徑的下一個躍點。使用下列其中一個參數或參數組合:

    • --next-hop-gateway=default-internet-gateway:將封包傳送至網際網路,以及 Google API 和服務。
    • --next-hop-instance=INSTANCE_NAME--next-hop-instance-zone=ZONE:將封包傳送至現有 VM 執行個體的網路介面。依名稱和區域指定 VM 執行個體。如果路徑目的地是 IPv6 位址,VM 執行個體必須是雙重堆疊僅支援 IPv6 (搶先版)
    • --next-hop-address=ADDRESS:指定虛擬私有雲網路中「現有執行個體」的 IP 位址。如果是 IPv6 靜態路徑,執行個體必須是雙重堆疊。如要瞭解有效的下一個躍點 IP 位址的重要限制,請參閱「下一個躍點和功能」。
    • --next-hop-vpn-tunnel=VPN_TUNNEL_NAME--next-hop-vpn-tunnel-region=REGION:使用靜態轉送將封包傳送至現有的傳統版 VPN 通道。
    • --next-hop-ilb=FORWARDING_RULE--next-hop-ilb-region=REGION:將封包傳送至內部直通式網路負載平衡器。依據名稱 (或 IPv4 或 IPv6 位址) 和區域指定轉送規則。您指定的轉送規則 IP 版本必須與您建立的靜態路徑 IP 版本相符。如要進一步瞭解如何設定內部直通式網路負載平衡器的靜態路徑,請參閱「建立靜態路徑」。

    如要使自訂靜態路徑僅適用於按照網路標記選取 VM,請新增 --tags 標記並指定一或多個網路標記。如要進一步瞭解網路標記與自訂靜態路徑的協同合作方式,請參閱「路徑總覽」中的適用路徑。您可以在任何自訂靜態路徑中使用標記。

如要進一步瞭解 gcloud CLI 語法,請參閱 SDK 說明文件

API

建立新的自訂靜態路徑。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/routes
{
  "name": "ROUTE_NAME",
  "network": "NETWORK_NAME",
  "destRange": "DESTINATION_RANGE",
  "priority": PRIORITY,
  "NEXT_HOP_SPECIFICATION"
}

更改下列內容:

  • PROJECT_ID:建立路徑的專案 ID
  • ROUTE_NAME:路徑名稱
  • NETWORK:包含路徑的 VPC 網路名稱。
  • DESTINATION_RANGE:此路徑適用的目的地 IPv4 或 IPv6 位址範圍。最廣的可能目的地為 IPv4 的 0.0.0.0/0 或 IPv6 的 ::/0
  • PRIORITY:路徑優先順序,範圍從 0 (最高優先順序) 到 65535 (最低優先順序)
  • NEXT_HOP_SPECIFICATION:靜態路徑的下一個躍點。使用下列其中一個參數或參數組合:
    • nextHopGateway: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/gateways/default-internet-gateway: 將封包傳送至網際網路,以及 Google API 和服務
    • nextHopInstance: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances/INSTANCE_NAME: 將封包傳送至 VM 執行個體的網路介面。依名稱和區域指定 VM 執行個體。如果路由目的地是 IPv6 位址,VM 執行個體必須是雙重堆疊僅支援 IPv6 (搶先版)
    • nextHopIp: ADDRESS:指定虛擬私有雲網路中「現有執行個體」的 IP 位址。如要使用 IPv6 靜態路徑,執行個體必須是雙重堆疊。如要進一步瞭解有效的下一個躍點 IP 位址的重要限制,請參閱「下一個躍點和功能」一文。
    • nextHopVpnTunnel: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/vpnTunnels/VPN_TUNNEL_NAME: 使用靜態轉送,將封包傳送至現有的傳統版 VPN 通道。
    • nextHopIlb: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/forwardingRules/FORWARDING_RULE: 將封包傳送至內部直通式網路負載平衡器。 依據名稱 (或 IPv4 或 IPv6 位址) 和區域指定轉送規則。您指定的轉送規則 IP 版本必須與您建立的靜態路徑 IP 版本相符。

如要使自訂靜態路徑僅適用於按照網路標記選取 VM,請新增 tags 欄位並指定一或多個網路標記。如要進一步瞭解網路標記與自訂靜態路徑的協同合作方式,請參閱「路徑總覽」中的適用路徑。您可以在任何自訂靜態路徑中使用標記。

詳情請參閱 routes.insert 方法。

Terraform

您可以使用 Terraform 模組建立靜態路徑。

這個靜態路徑會建立通往網際網路的預設路徑。

module "google_compute_route" {
  source       = "terraform-google-modules/network/google//modules/routes"
  version      = "~> 10.0"
  project_id   = var.project_id # Replace this with your project ID in quotes
  network_name = "default"

  routes = [
    {
      name              = "egress-internet"
      description       = "route through IGW to access internet"
      destination_range = "0.0.0.0/0"
      tags              = "egress-inet"
      next_hop_internet = "true"
    }
  ]
}

如要瞭解如何套用或移除 Terraform 設定,請參閱「基本 Terraform 指令」。

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

// createRoute creates a route with given name inside given project.
func createRoute(w io.Writer, projectID, name string) error {
	// projectID := "your_project_id"
	// name := "testname"

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

	route := &computepb.Route{
		Name:           proto.String(name),
		Network:        proto.String("global/networks/default"),
		DestRange:      proto.String("0.0.0.0/0"),
		NextHopGateway: proto.String("global/gateways/default-internet-gateway"),
	}

	req := &computepb.InsertRouteRequest{
		Project:       projectID,
		RouteResource: route,
	}
	op, err := client.Insert(ctx, req)

	if err != nil {
		return fmt.Errorf("unable to insert a route: %w", err)
	}

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

	fmt.Fprintf(w, "Route created\n")

	return nil
}

Java


import com.google.cloud.compute.v1.InsertRouteRequest;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.Route;
import com.google.cloud.compute.v1.RoutesClient;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateRoute {

  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 Cloud project you want to use.
    String projectId = "your-project-id";
    // Route name you want to use.
    String routeName = "your-route-name";
    createRoute(projectId, routeName);
  }

  // Create route for a project.
  public static Operation.Status createRoute(String projectId, String routeName)
          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 (RoutesClient routesClient = RoutesClient.create()) {
      String nextHopGateway =
              String.format("projects/%s/global/gateways/default-internet-gateway", projectId);

      Route route = Route.newBuilder()
              .setName(routeName)
              .setDestRange("10.0.0.0/16")
              .setNetwork("global/networks/default")
              .setNextHopGateway(nextHopGateway)
              .build();

      InsertRouteRequest request = InsertRouteRequest.newBuilder()
              .setProject(projectId)
              .setRequestId(UUID.randomUUID().toString())
              .setRouteResource(route)
              .build();

      return routesClient.insertCallable().futureCall(request)
              .get(30, TimeUnit.SECONDS).getStatus();
    }
  }
}

Python

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def create_route(
    project_id: str,
    network: str,
    route_name: str,
    destination_range: str,
    *,
    next_hop_gateway: str | None = None,
    next_hop_ip: str | None = None,
    next_hop_instance: str | None = None,
    next_hop_vpn_tunnel: str | None = None,
    next_hop_ilb: str | None = None,
) -> compute_v1.Route:
    """
    Create a new route in selected network by providing a destination and next hop name.

    Note: The set of {next_hop_gateway, next_hop_ip, next_hop_instance, next_hop_vpn_tunnel,
        next_hop_ilb} is exclusive, you and only specify one of those parameters.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        network: name of the network the route will be created in. Available name formats:
            * https://www.googleapis.com/compute/v1/projects/{project_id}/global/networks/{network}
            * projects/{project_id}/global/networks/{network}
            * global/networks/{network}
        route_name: name of the new route.
        destination_range: range of destination IPs this route should be applied to. E.g. 10.0.0.0/16.
        next_hop_gateway: name of the gateway the traffic should be directed to.
        next_hop_ip: IP address the traffic should be directed to.
        next_hop_instance: name of the instance the traffic should be directed to. Name format:
            "projects/{project}/zones/{zone}/instances/{instance_name}"
        next_hop_vpn_tunnel: name of the VPN tunnel the traffic should be directed to. Name format:
            "projects/{project}/regions/{region}/vpnTunnels/{vpn_tunnel_name}"
        next_hop_ilb: name of a forwarding rule of the Internal Load Balancer the traffic
            should be directed to. Name format:
            "projects/{project}/regions/{region}/forwardingRules/{forwarding_rule_region}"

    Returns:
        A new compute_v1.Route object.
    """
    excl_args = {
        next_hop_instance,
        next_hop_ilb,
        next_hop_vpn_tunnel,
        next_hop_gateway,
        next_hop_ip,
    }
    args_set = sum(1 if arg is not None else 0 for arg in excl_args)

    if args_set != 1:
        raise RuntimeError("You must specify exactly one next_hop_* parameter.")

    route = compute_v1.Route()
    route.name = route_name
    route.network = network
    route.dest_range = destination_range

    if next_hop_gateway:
        route.next_hop_gateway = next_hop_gateway
    elif next_hop_ip:
        route.next_hop_ip = next_hop_ip
    elif next_hop_instance:
        route.next_hop_instance = next_hop_instance
    elif next_hop_vpn_tunnel:
        route.next_hop_vpn_tunnel = next_hop_vpn_tunnel
    elif next_hop_ilb:
        route.next_hop_ilb = next_hop_ilb

    route_client = compute_v1.RoutesClient()
    operation = route_client.insert(project=project_id, route_resource=route)

    wait_for_extended_operation(operation, "route creation")

    return route_client.get(project=project_id, route=route_name)

新增 IPv4 預設路徑

系統會為每個虛擬私有雲網路自動設定 IPv4 預設靜態路徑 (0.0.0.0/0),並將 next-hop-gateway 設為 default-internet-gateway。如有需要,請按照下列步驟重新建立這條路線。

主控台

  1. 前往 Google Cloud 控制台的「Routes」(路徑) 頁面。

    前往「Routes」(路徑)

  2. 按一下「路徑管理」分頁標籤。

  3. 按一下 [Create route] (建立路徑)

  4. 指定路徑的名稱和說明。

  5. 選取路徑的現有網路。

  6. 在「Destination IP range」(目的地 IP 範圍) 中輸入 0.0.0.0/0

  7. 指定路徑的優先順序。優先順序可設為 0 (最高優先順序) 至 65535 (最低優先順序)。

  8. 在「下一個躍點」中,選取「預設網際網路閘道」

  9. 點選「建立」

gcloud

重新建立網路的 IPv4 預設路徑。

gcloud compute routes create ROUTE_NAME \
    --destination-range=0.0.0.0/0 \
    --network=NETWORK \
    --next-hop-gateway=default-internet-gateway

更改下列內容:

  • ROUTE_NAME:路徑名稱
  • NETWORK:包含路徑的 VPC 網路名稱

API

重新建立網路的 IPv4 預設路徑。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/routes
{
  "destRange": "0.0.0.0/0",
  "name": "ROUTE_NAME",
  "network": "NETWORK_NAME",
  "nextHopGateway": "projects/PROJECT_ID/global/gateways/default-internet-gateway"
}

更改下列內容:

  • PROJECT_ID:建立路徑的專案 ID
  • ROUTE_NAME:路徑名稱
  • NETWORK_NAME:包含路徑的 VPC 網路名稱

新增 IPv6 預設路徑

建立子網路時,如果將 IPv6 存取類型設為外部,系統會自動為虛擬私有雲網路設定 IPv6 預設靜態路徑 (::/0),並將 next-hop-gateway 設為 default-internet-gateway。您可以刪除路徑,封鎖從 VM 傳輸至網際網路的所有 IPv6 流量。你也可以視需要重新建立路線。

主控台

  1. 前往 Google Cloud 控制台的「Routes」(路徑) 頁面。

    前往「Routes」(路徑)

  2. 按一下「路徑管理」分頁標籤。

  3. 按一下 [Create route] (建立路徑)

  4. 指定路徑的名稱和說明。

  5. 選取路徑的現有網路。

  6. 在「Destination IP range」(目的地 IP 範圍) 中輸入 ::/0

  7. 指定路徑的「priority」(優先等級)。 優先順序可設為 0 (最高優先順序) 至 65535 (最低優先順序)。

  8. 在「下一個躍點」中,選取「預設網際網路閘道」

  9. 點選「建立」

gcloud

為網路重新建立 IPv6 預設路徑。

gcloud compute routes create ROUTE_NAME \
    --destination-range=::/0 \
    --network=NETWORK \
    --next-hop-gateway=default-internet-gateway

更改下列內容:

  • ROUTE_NAME:路徑的名稱。
  • NETWORK:包含路徑的 VPC 網路名稱。

API

為網路重新建立 IPv6 預設路徑。

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/routes
{
  "destRange": "::/0",
  "name": "ROUTE_NAME",
  "network": "NETWORK_NAME",
  "nextHopGateway": "projects/PROJECT_ID/global/gateways/default-internet-gateway"
}

更改下列內容:

  • PROJECT_ID:建立路徑的專案 ID
  • ROUTE_NAME:路徑名稱
  • NETWORK_NAME:包含路徑的 VPC 網路名稱

修改靜態路徑

靜態路徑建立後就無法編輯或更新。如要修改靜態路徑,必須先將其刪除並建立取代的路徑。

刪除靜態路徑

如要刪除路線,請按照下列步驟操作。

主控台

  1. 前往 Google Cloud 控制台的「Routes」(路徑) 頁面。

    前往「Routes」(路徑)

  2. 按一下「路徑管理」分頁標籤。

  3. 在要刪除的規則旁,選取核取方塊。

  4. 按一下 「Delete」(刪除)

  5. 再按一下 [刪除] 加以確認。

gcloud

使用下列 gcloud CLI 指令刪除自訂靜態路徑:

gcloud compute routes delete ROUTE_NAME

ROUTE_NAME 替換為要刪除的路徑名稱。

API

使用 routes.delete 方法刪除自訂靜態路徑,從虛擬私有雲網路中移除該路徑:

DELETE https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/global/routes/ROUTE_NAME

更改下列內容:

  • PROJECT_ID:路線所在的專案 ID。
  • ROUTE_NAME:要刪除的路徑名稱。

Go

import (
	"context"
	"fmt"
	"io"

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

// deleteRoute deletes a route by name in given project.
func deleteRoute(w io.Writer, projectID, name string) error {
	// projectID := "your_project_id"
	// name := "testname"

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

	req := &computepb.DeleteRouteRequest{
		Project: projectID,
		Route:   name,
	}
	op, err := client.Delete(ctx, req)

	if err != nil {
		return fmt.Errorf("unable to delete a route: %w", err)
	}

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

	fmt.Fprintf(w, "Route deleted\n")

	return nil
}

Java


import com.google.cloud.compute.v1.DeleteRouteRequest;
import com.google.cloud.compute.v1.RoutesClient;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteRoute {

  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 Cloud project you want to use.
    String projectId = "your-project-id";
    // Route name you want to delete.
    String routeName = "your-route-name";

    deleteRoute(projectId, routeName);
  }

  // Deletes a route from a project.
  public static void deleteRoute(String projectId, String routeName)
          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 (RoutesClient routesClient = RoutesClient.create()) {
      DeleteRouteRequest request = DeleteRouteRequest.newBuilder()
              .setProject(projectId)
              .setRoute(routeName)
              .setRequestId(UUID.randomUUID().toString())
              .build();
      routesClient.deleteCallable().futureCall(request).get(30, TimeUnit.SECONDS);
    }
  }
}

Python

from __future__ import annotations

import sys
from typing import Any

from google.api_core.extended_operation import ExtendedOperation
from google.cloud import compute_v1


def wait_for_extended_operation(
    operation: ExtendedOperation, verbose_name: str = "operation", timeout: int = 300
) -> Any:
    """
    Waits for the extended (long-running) operation to complete.

    If the operation is successful, it will return its result.
    If the operation ends with an error, an exception will be raised.
    If there were any warnings during the execution of the operation
    they will be printed to sys.stderr.

    Args:
        operation: a long-running operation you want to wait on.
        verbose_name: (optional) a more verbose name of the operation,
            used only during error and warning reporting.
        timeout: how long (in seconds) to wait for operation to finish.
            If None, wait indefinitely.

    Returns:
        Whatever the operation.result() returns.

    Raises:
        This method will raise the exception received from `operation.exception()`
        or RuntimeError if there is no exception set, but there is an `error_code`
        set for the `operation`.

        In case of an operation taking longer than `timeout` seconds to complete,
        a `concurrent.futures.TimeoutError` will be raised.
    """
    result = operation.result(timeout=timeout)

    if operation.error_code:
        print(
            f"Error during {verbose_name}: [Code: {operation.error_code}]: {operation.error_message}",
            file=sys.stderr,
            flush=True,
        )
        print(f"Operation ID: {operation.name}", file=sys.stderr, flush=True)
        raise operation.exception() or RuntimeError(operation.error_message)

    if operation.warnings:
        print(f"Warnings during {verbose_name}:\n", file=sys.stderr, flush=True)
        for warning in operation.warnings:
            print(f" - {warning.code}: {warning.message}", file=sys.stderr, flush=True)

    return result


def delete_route(project_id: str, route_name: str) -> None:
    """
    Delete a route in project.

    Args:
        project_id: project ID or project number of the Cloud project you want to use.
        route_name: name of the route to delete.
    """

    route_client = compute_v1.RoutesClient()
    operation = route_client.delete(project=project_id, route=route_name)

    wait_for_extended_operation(operation, "route deletion")

路線變更的傳播

新增或刪除靜態路徑時,該路徑會傳播至 VPC 網路中的所有區域和 VM 執行個體。如果路線作業狀態為 PENDINGRUNNING,表示路線變更已加入佇列。

排入佇列後,路徑作業狀態會變更為 DONE。VPC 網路和 VPC 網路對等互連網路中的所有 VM 執行個體,可能需要額外 30 秒才會開始使用新路徑或停止使用舊路徑。

如果同時新增或移除多個靜態路徑,系統會以任意順序套用變更。我們無法保證您提交路線變更要求的順序就是這些要求的處理順序。不同的執行個體可能會在不同的時間察覺變更。

如要進行彼此相關的路線變更,您必須依序進行這些變更,也就是在前一項變更的狀態為 DONE 且經過額外 30 秒後,才能進行後續變更。

為執行個體啟用 IP 轉送功能

根據預設,IP 轉送功能會停用,並 Google Cloud 執行嚴格的來源位址檢查。視有效的輸出防火牆設定而定,VM 可以發出具有下列來源的封包:

  • 執行個體網路介面 (NIC) 的主要內部 IPv4 位址。
  • 執行個體 NIC 上設定的任何別名 IP 範圍。
  • 如果子網路上已設定 IPv6 位址範圍,且執行個體為雙重堆疊或僅支援 IPv6 (搶先版),則為指派給 NIC 的任何 IPv6 位址。
  • 與轉送規則相關聯的內部或外部 IP 位址 (適用於直通式負載平衡或通訊協定轉送),前提是執行個體是內部直通式網路負載平衡器、外部直通式網路負載平衡器的後端,或是目標執行個體參照的執行個體。

如要將 VM 做為路徑的下一個躍點來使用,VM 需要轉送來源與上述清單中 IP 位址或範圍不符的封包。如要轉送具有任意來源位址的封包,請啟用 IP 轉送:

  • 建立或更新 VM 時,請按照本節中的操作說明啟用 IP 轉送功能。啟用 IP 轉送功能後,會套用至 VM 上的所有 NIC。
  • 除了本節的步驟,您也必須在 VM 訪客作業系統中啟用 IP 轉送。如要在 Linux 上執行這項操作,請將下列一或兩個核心參數的值設為 1net.ipv4.ip_forward (適用於 IPv4) 或 net.ipv6.conf.all.forwarding (適用於 IPv6)。

如要在建立 VM 時啟用 IP 轉送功能,請完成下列步驟。

主控台

  1. 前往 Google Cloud 控制台的「VM instances」(VM 執行個體) 頁面

    前往 VM 執行個體

  2. 點選「建立執行個體」

  3. 在「進階選項」部分,展開「網路、磁碟、安全性、管理、單一租戶」

  4. 展開「Networking」(網路) 區段。

  5. 在「IP forwarding」(IP 轉送) 專區中,選取「Enable」(啟用) 核取方塊。

gcloud

建立執行個體時,請將 --can-ip-forward 標記新增至您的指令:

gcloud compute instances create ... --can-ip-forward

API

建立執行個體時,請使用 canIpForward 欄位啟用 IP 轉送:

POST https://compute.googleapis.com/compute/v1/projects/PROJECT_ID/zones/ZONE/instances
{
  "canIpForward": true,
  ...other fields
}

更改下列內容:

  • PROJECT_ID:包含執行個體的專案 ID
  • ZONE:包含執行個體的 Google Cloud 區域

詳情請參閱 instances.insert 方法

Terraform

您可以使用 Terraform 資源建立已啟用 IP 轉送的 VM 執行個體。

在本範例中,Terraform 引數已指派可變更的值。

resource "google_compute_instance" "default" {
  project      = var.project_id # Replace this with your project ID in quotes
  zone         = "southamerica-east1-b"
  name         = "instance-next-hop"
  machine_type = "e2-medium"
  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-9"
    }
  }
  network_interface {
    network = "default"
  }
  can_ip_forward = true
}

如要瞭解如何套用或移除 Terraform 設定,請參閱「基本 Terraform 指令」。

啟用 IP 轉送功能後,繼續執行 VM 建立程序

如要在現有 VM 上啟用 IP 轉送功能,請更新執行個體屬性canIpForward

後續步驟