Hour 5: Hybrid connectivity: Cloud VPN, Interconnect and hub-and-spoke

HA VPN, Cloud Interconnect, Cloud Router and BGP, Network Connectivity Center, and the entry point for applications.
Hour 5HA VPNCloud RouterNetwork Connectivity Center

Hour 5: Hybrid connectivity

Almost every landing zone has to reach something that is not in Google Cloud: a data centre, a branch office, another cloud, or a partner. This hour covers the options for building that connection, how routes are exchanged, and how to make the connection resilient. It follows Hour 4, where you built the hub VPN network, Shared VPC and the IP plan. Here the hub gets its outside connections.

You start with the map of options (HA VPN, Dedicated Interconnect, Partner Interconnect and Cross-Cloud Interconnect) and a decision table. Then you learn Cloud Router and BGP, the control plane behind every connection. You build a redundant HA VPN, and you study Cloud Interconnect with its VLAN attachments and redundancy topologies. The second half of the hour moves from point-to-point links to a hub-and-spoke design with Network Connectivity Center, then to ingress: an external Application Load Balancer protected by Cloud Armor.

The hands-on part is small and safe. The Cloud Router lab (Module 7) uses free objects. The HA VPN build in Module 3 and the optional HA VPN in Module 7 create billable gateways and tunnels, and every lab ends with a cleanup that you must run.

Command output in the course uses illustrative IDs and addresses. Where a flag is not stable across SDK versions, the lesson says so and points to gcloud … --help.

What you will be able to do

  • Choose between HA VPN, Dedicated Interconnect, Partner Interconnect and Cross-Cloud Interconnect from bandwidth, latency, availability and cost needs.
  • Create a Cloud Router, explain ASNs, dynamic routing modes and custom route advertisement, and read BGP status.
  • Build and verify an HA VPN with two tunnels and BGP sessions, and clean it up in the right order.
  • Describe Interconnect VLAN attachments and the redundancy topologies for each availability target.
  • Design hub-and-spoke connectivity with Network Connectivity Center, and place a Cloud Armor policy in front of an external load balancer.
  • Troubleshoot tunnel, BGP, route, firewall and MTU problems in a fixed order.

Schedule (60 minutes)

#ModuleMinutes
1Connectivity options6
2Cloud Router and BGP7
3HA VPN8
4Cloud Interconnect7
5Network Connectivity Center8
6Ingress and Cloud Armor7
7Lab: Cloud Router and BGP configuration10
8Troubleshooting connectivity7
Total60

Which labs cost money

ModuleLab contentBillable resources
1Inventory and decision worksheetNone. Read-only commands.
2Lab VPC, subnet and Cloud RouterNone while no tunnels or VMs exist.
3HA VPN between two lab VPCsYes. Two HA VPN gateways and four tunnels, plus optional test VMs. Clean up in the same session.
4Interconnect inspection and planNone. Read-only commands; no circuit is ordered.
5 to 6Follow the lesson steps (see each lab tab)Check the cost line at the top of each lab. A load balancer and Cloud Armor policy are metered resources.
7Cloud Router and BGP configurationNone for the main lab. The optional HA VPN part is billable.
8Troubleshooting drillsNone; read-only checks.
Cost warning. HA VPN gateways and tunnels bill while they exist, even with no traffic. A forgotten lab keeps billing every day. Set a budget first, remember that budgets send alerts and do not cap spend, and run the cleanup commands at the end of every lab that creates a gateway or tunnel.

What you need

  • A sandbox Google Cloud project with billing linked and a budget alert (Hour 1).
  • The Compute Engine API enabled, and a role such as roles/compute.networkAdmin on the sandbox project.
  • The gcloud CLI (Cloud Shell is enough) and a terminal with openssl for the random lab secret.
  • A region you are allowed to use. An organization is helpful but not required for this hour. See Setup for the checks.

Hybrid connectivity products and limits change. Check the current documentation on the sources page before you quote an availability target or a bandwidth figure to a customer.

Setup

Hybrid connectivity: Cloud VPN, Interconnect and hub-and-spoke
Hour 5

Environment for Hour 5

This hour works in a single sandbox project. You create lab VPC networks, a Cloud Router, and (in two labs) HA VPN gateways and tunnels. Nothing here touches a production network. Do the checks below before Module 1, so that the labs do not stop on access, billing or API problems.

1. Access and tools

  • Project. A sandbox project that you may change. Do not use a project that already has production VPN or Interconnect objects.
  • Roles. roles/compute.networkAdmin on the sandbox project is enough for the networking labs. For Module 1 and Module 4, roles/compute.networkViewer is enough. API enablement needs roles/serviceusage.serviceUsageAdmin or equivalent.
  • Tools. The gcloud CLI (current release channel). Cloud Shell has it pre-installed, authenticated, and with openssl available. A local shell also works after gcloud init.
  • Organization. Not required. Without an organization, work at project level: every command in this hour uses --project. Features that need an organization (organization firewall policies, organization policy constraints) are explained in other hours, not required here.

2. Check commands

Run these in order. The expected output uses illustrative IDs.

gcloud --version
gcloud auth list
gcloud config set project PROJECT_ID
gcloud config get-value project
Google Cloud SDK 5xx.x.x
                  ACTIVE  ACCOUNT
*                         student@example.com
Updated property [core/project].
PROJECT_ID

The SDK number depends on the release you have. If gcloud --version is old, run gcloud components update (not available when gcloud was installed through a package manager; use that package manager instead).

gcloud services enable compute.googleapis.com --project=PROJECT_ID
gcloud services list --enabled --project=PROJECT_ID --filter="config.name=compute.googleapis.com"
NAME                 TITLE
compute.googleapis.com  Compute Engine API

Enabling the API is a metadata change, free in itself. If you plan to do Module 5, also enable the Network Connectivity API: gcloud services enable networkconnectivity.googleapis.com --project=PROJECT_ID.

3. Region and quota

  • Pick one region for the whole hour, for example the one closest to you, and set a shell variable: REGION=europe-west4. If an organization policy restricts locations, use an allowed region (Hour 3 explains gcp.resourceLocations).
  • Check that your project can create the lab objects. The relevant quotas are networks, routers, VPN gateways and VPN tunnels. List the regional quotas with gcloud compute regions describe REGION --project=PROJECT_ID and look at the quotas section. A new project normally has enough for this hour.
  • Choose lab names with a common prefix (lab5- or the names from the lessons), so cleanup can find everything: gcloud compute networks list --filter="name~^vpc-|^hub-".

4. Budget and cost

Most of the hour is free. These are the billable objects, so you know what to watch:

  • HA VPN gateways and tunnels (Module 3 and the optional part of Module 7): billed for as long as they exist, plus data transfer. Low for a short lab (usually well under a few USD), but a forgotten gateway keeps billing.
  • Test VMs (optional ping test): billed while running. Delete them straight after the test.
  • Cloud Router, VPC, subnets: no charge as configuration objects when no tunnel, attachment or NAT uses them. Check the current pricing page if you leave them for long.
  • Interconnect, load balancer and Cloud Armor: not created in the Module 4 lab; check the cost line on the Module 5 and 6 labs before you create anything.

Create a budget alert before you start (Hour 1, Module 3). Budgets send alerts and do not cap spend, so the cleanup commands are your real control. Verify the alert exists:

gcloud billing budgets list --billing-account=BILLING_ACCOUNT_ID
DISPLAY_NAME     AMOUNT
sandbox-budget   (configured)

If you have no billing permission, ask the billing administrator to confirm a budget on the project.

5. What to do without an organization

  • Use a personal or sandbox project. Everything in Modules 1 to 4 and 7 to 8 is project-level.
  • Skip any step that mentions folders, organization policy or organization firewall policies; the lesson will say when a step needs an organization and what to read instead.
  • Network Connectivity Center and Cloud Armor commands are project-level, so you can follow them in a personal project, subject to cost and quota.
  • Do not create a real connection to a company network from a personal project. Use the GCP-to-GCP form of HA VPN.

6. Working rules for the labs

  • Never type or paste a real pre-shared key. The HA VPN lab generates a random secret in the shell and discards it at cleanup. For real connections, store the secret in Secret Manager.
  • Use non-overlapping lab ranges: 10.10.0.0/24 for the first VPC and 10.20.0.0/24 for the second.
  • Run the cleanup at the end of each lab that creates a gateway or tunnel, and confirm with the list commands that the result is Listed 0 items.
  • If a command fails, read the error, check the triage order on the Troubleshooting tab of the module, and do not retry blindly in a loop.

7. Final readiness check

gcloud compute networks list --project=PROJECT_ID
gcloud compute routers list --project=PROJECT_ID
gcloud compute vpn-gateways list --project=PROJECT_ID
gcloud compute vpn-tunnels list --project=PROJECT_ID

A fresh sandbox prints Listed 0 items. or only the default network. If any VPN gateway or tunnel is listed, find out who owns it before you continue.

Tip. Keep two terminal tabs: one for the lab commands and one running gcloud compute vpn-gateways list and vpn-tunnels list, so billable objects are always visible.

Module 1 · Connectivity options

00–06 · HA VPN, Dedicated and Partner Interconnect, cross-cloud links, and how to choose between them
HybridHA VPNInterconnectDecision table6 min
Learning objectives
  • Name the hybrid connectivity options on Google Cloud (HA VPN, Dedicated Interconnect, Partner Interconnect, Cross-Cloud Interconnect) and say what each one is made of.
  • Choose an option from bandwidth, latency, availability target, encryption need, lead time and cost shape.
  • Explain why every option needs dynamic routing with Cloud Router, and why connectivity is a landing-zone design decision made once for the organization.

The short answer

Hybrid connectivity (混合云连接) is how a VPC network reaches networks outside Google Cloud: a data centre, a branch office, or another cloud. Google Cloud offers four building blocks. HA VPN is IPsec over the public internet. Dedicated Interconnect is a physical circuit you own at a colocation facility. Partner Interconnect is a circuit that a service provider sells you. Cross-Cloud Interconnect is a Google-managed circuit to another cloud provider. All four terminate in a VPC through Cloud Router and BGP, so the later modules (Network Connectivity Center, firewall policies, DNS forwarding) work the same way on top of any of them.

What: the options in detail

OptionMade ofPathEncrypted by default
HA VPNHA VPN gateway (2 interfaces), tunnels, Cloud RouterPublic internetYes (IPsec, IKEv2)
Dedicated Interconnect10 or 100 Gbps circuits at a colocation facility, VLAN attachments, Cloud RouterPrivate, direct to GoogleNo (MACsec is available on supported connections)
Partner InterconnectService provider connection, VLAN attachments, Cloud RouterPrivate, through the providerNo (add HA VPN over Interconnect)
Cross-Cloud InterconnectGoogle-managed circuits to another cloud, VLAN attachments, Cloud RouterPrivate, cloud to cloudNo by default; check the supported encryption options
HA VPN over InterconnectHA VPN gateway on top of VLAN attachmentsPrivate circuit, IPsec inside itYes
Check the docs for limits. Circuit sizes, attachment capacities, the list of supported locations and the exact tunnel throughput change over time. Treat any number in a course as a starting point and confirm it on the product pages listed on the sources page.

Why: the decision is about four things

  • Bandwidth. A single HA VPN tunnel is limited to a few Gbps, and you scale by adding tunnels and relying on equal-cost multipath. Interconnect scales in circuit-sized steps (10 or 100 Gbps) and in attachment capacities.
  • Latency and jitter. The internet path of a VPN varies. A private circuit is steadier, which matters for database replication, storage migration and real-time workloads.
  • Availability target. Both HA VPN and Interconnect publish an availability target for specific redundant topologies. A single tunnel or a single circuit is not covered by the higher target.
  • Time and cost shape. A VPN is created in minutes and billed by usage. An Interconnect needs ordering, cross-connects or a provider contract, and often weeks of lead time. The cost shape differs, so compare totals for your traffic instead of the unit prices alone.

How it works internally

Every option ends the same way. A virtual interface (a VPN tunnel, or a VLAN attachment) is bound to a Cloud Router in a region. The Cloud Router opens a BGP session with the peer, learns the on-premises prefixes, and installs them in the VPC as dynamic routes. It also advertises the VPC subnets back. The VPC's dynamic routing mode (regional or global) decides in which regions the learned routes are visible. Module 2 covers this in depth.

Decision table

RequirementHA VPNPartner InterconnectDedicated InterconnectCross-Cloud Interconnect
Starts in minutesYesNo (provider lead time)No (ordering and cross-connect)No
Bandwidth need under a few GbpsGood fitGood fitUsually more than neededNot applicable
Tens of Gbps, steadyMany tunnels, complexPossible, provider-dependentBest fitBest fit for cloud to cloud
Predictable latencyVariable (internet)GoodBestGood
Encryption requiredBuilt inAdd HA VPN over InterconnectMACsec or HA VPN over InterconnectCheck supported options
No colocation presenceYesYesNoNot applicable
Typical useBranch offices, migrations, backup pathRemote sites, medium bandwidthData centre cores, data-heavy workloadsMulticloud data movement

When to use each (rules of thumb)

  • Start with HA VPN for the first connection, for a disaster recovery path, and for any site that does not need more than a few Gbps.
  • Add Interconnect when sustained throughput, latency stability or a "no public internet" policy makes the VPN path unsuitable.
  • Keep an HA VPN as backup for an Interconnect when the business accepts lower bandwidth during a failure. Use route priorities (Module 2) to prefer the Interconnect.
  • Use Cross-Cloud Interconnect when another cloud is a real long-term peer and you move data volumes that make internet VPN impractical.

What it is confused with

Looks similarDifference
VPC Network PeeringConnects two VPC networks inside Google Cloud. It is not hybrid connectivity and it is not transitive.
Direct Peering and Carrier PeeringExchange public routes with Google at an edge point of presence. They do not give private RFC 1918 reachability to VPC networks. Interconnect is the supported product for that.
Classic VPNThe older single-interface gateway. New designs should use HA VPN; check the current deprecation notes on the product page before you reuse an old Classic gateway.
Cloud NATLets private VMs reach the internet. It does not connect to on-premises networks.
Private Service ConnectPublishes or consumes a service through a private endpoint. It does not join two networks.

Three common misunderstandings

"A VPN is automatically highly available." One tunnel is a single point of failure, even on an HA VPN gateway. The availability target applies only when you build the documented redundant topology: both gateway interfaces, tunnels to the peer's redundant interfaces, and BGP on each tunnel.
"Interconnect is encrypted because it is private." It is private, not encrypted. Decide on MACsec or IPsec explicitly, with your security team.
"We can fix the IP plan later." Overlapping on-premises and VPC ranges cannot be routed. Fix the address plan before the first tunnel exists (Hour 4, Module 3).
On-premises data centre · branches VPN device Colo router Provider edge Other cloud Path Internet · IPsec Private circuit Provider network Cloud-to-cloud circuit Google Cloud per region HA VPN gateway + tunnels Dedicated VLAN attachment Partner VLAN attachment Cross-Cloud attachment

Figure 1. Four ways in. Each row ends on a Cloud Router in a region (Module 2). The row you choose changes the path and the lead time, not the routing model.

New hybrid connection Need more than a few Gbps,or stable latency? no HA VPN2 tunnels · BGP yes Presence in a Googlecolocation facility? yes no DedicatedInterconnect PartnerInterconnect Add a second path in every case: redundant tunnels or circuits, plus HA VPN as backup

Figure 2. A simplified decision flow. Look at the dashed zone: whichever box you reach, a single path is not a design. Redundancy is added on every branch.

What to look at. In Figure 1, follow one row from left to right and notice that only the middle column changes. In Figure 2, note that the first question is about bandwidth and latency, because those are the requirements that a VPN cannot always meet.

The animation follows a healthy HA VPN connection from the first IKE message to a VM reaching an on-premises host. Each step is a real event: a tunnel state change, a BGP state, a route that appears in the VPC routing table.

Every command on this tab is read-only unless it is marked as a write. Replace uppercase placeholders (PROJECT_ID, REGION) with your values. Check gcloud … --help for the flags in your SDK version.

gcloud services enable compute.googleapis.com (write, free)

Purpose. Enables the Compute Engine API, which hosts VPN gateways, Cloud Routers and Interconnect objects. Enabling an API is a metadata change and does not cost money by itself.

gcloud services enable compute.googleapis.com --project=PROJECT_ID
Operation "operations/acf.p2-123456789012-aaaa-bbbb-cccc" finished successfully.

Flags. --project selects the project explicitly, so the command never depends on the active configuration. Common errors. PERMISSION_DENIED means you lack serviceusage.services.enable (for example roles/serviceusage.serviceUsageAdmin). Production use. API enablement belongs in the project factory (Hour 7), not in an engineer's shell history.

gcloud compute networks list

Purpose. Lists VPC networks and shows the subnet mode and BGP routing mode. The BGP routing mode (REGIONAL or GLOBAL) decides where learned on-premises routes are usable.

gcloud compute networks list --project=PROJECT_ID --format="table(name,subnet_mode,bgp_routing_mode)"
NAME     SUBNET_MODE  BGP_ROUTING_MODE
hub-vpc  CUSTOM       GLOBAL

Flags. --format="table(...)" selects columns. Common errors. An empty result with no error means no VPC exists yet, or the API is disabled. IDs in the expected output are illustrative.

gcloud compute vpn-gateways list

Purpose. Lists HA VPN gateways across regions. It is the first check when someone says "we already have a VPN".

gcloud compute vpn-gateways list --project=PROJECT_ID
NAME        INTERFACE0     INTERFACE1     NETWORK  REGION
gw-onprem   203.0.113.10   203.0.113.11   hub-vpc  europe-west4

Flags. Add --filter="region:REGION" to limit the list. Production use. Inventory gateways and tunnels on a schedule (Hour 6, Cloud Asset Inventory) so an unmanaged VPN created by a team is found quickly.

gcloud compute interconnects locations list

Purpose. Lists the colocation facilities where Dedicated Interconnect can be ordered. Use it during design to see whether a facility near your data centre exists.

gcloud compute interconnects locations list --project=PROJECT_ID --format="table(name,description,city,continent)"

Flags. The table format avoids a long JSON output. Output depends on the live facility list, so none is shown here. Cost. Free, read-only.

gcloud compute interconnects list and attachments list

Purpose. Shows existing physical Interconnects and VLAN attachments in the project. An empty list means the project owns no Interconnect objects.

gcloud compute interconnects list --project=PROJECT_ID
gcloud compute interconnects attachments list --project=PROJECT_ID
Listed 0 items.

Common errors. Interconnect objects often live in a dedicated "connectivity" project that the platform team owns. If your list is empty but the business has an Interconnect, you are looking at the wrong project.

gcloud compute routers list

Purpose. Lists Cloud Routers. Every hybrid connection has one, so this is the quickest inventory of the existing connections.

gcloud compute routers list --project=PROJECT_ID --format="table(name,region.basename(),network.basename())"
NAME        REGION        NETWORK
rtr-onprem  europe-west4  hub-vpc
Production use. Decide where hybrid objects live. A common landing-zone pattern is a dedicated network hub project (or a host project) that owns the VPN gateways, Cloud Routers and Interconnect attachments, with IAM granted only to the network team (roles/compute.networkAdmin).

Lab 1: choose and justify a connection design (about 10 minutes, free)

Goal. Record what already exists in your sandbox, and write a one-page connectivity decision for an imaginary branch office, using the decision table from the Concepts tab.

Prerequisites. A sandbox project with roles/compute.viewer or higher, and gcloud authenticated (Cloud Shell works). No organization is required: every command here works at project level. IDs in the expected output are illustrative.

  1. Set the project for the session: gcloud config set project PROJECT_ID.
  2. Check the API is enabled: gcloud services list --enabled --filter="config.name=compute.googleapis.com". If it is empty, enable it with the command from the previous tab.
  3. Inventory VPC networks, routers and gateways with the three list commands from the previous tab.
  4. List the Interconnect locations and note the closest facility to a city of your choice.
  5. Write the requirements of the imaginary branch: peak Mbps, one-way latency target, availability target, whether encryption is mandatory, how soon it must be live.
  6. Walk the decision table row by row and mark each option as fits, fits with extra work, or does not fit.
  7. Write the final choice and the backup path in two sentences (for example "HA VPN, two tunnels, BGP; later a Partner Interconnect with HA VPN as backup").

Verification. Run gcloud compute routers list --format="value(name)" | wc -l. The number must match the routers you wrote down in step 3.

0

Expected result. A short inventory (likely zero networks, routers and gateways in a new sandbox) and a written decision that names the option, the number of tunnels or circuits, the routing protocol and the backup.

Cost. Free. Only read-only calls and an API enablement are used.

Cleanup. None. If you enabled the Compute Engine API only for this lab, it can stay enabled; it does not bill by itself.

Lab 2 (optional): requirements worksheet

Fill in the table below for a real site in your organization and ask the site owner to confirm it. The numbers decide the option more reliably than a vendor brochure.

QuestionYour answerEffect on the choice
Peak and average throughput to Google CloudAbove a few Gbps sustained points to Interconnect
Latency and jitter toleranceStrict tolerance points to a private circuit
Required availabilityDefines the redundant topology (tunnels or circuits)
Encryption policyIPsec, MACsec or HA VPN over Interconnect
On-premises address rangesMust not overlap any VPC subnet
Lead time availableShort lead time points to HA VPN first

Typical cases

  • VPN first, Interconnect later. A company migrating a first set of applications used two HA VPN tunnels for six months while a Partner Interconnect contract was negotiated. Because the routing used BGP from the start, the cutover was a route-priority change, not a redesign. The VPN stayed as the backup path.
  • Single tunnel "temporary". A proof of concept used one tunnel. It became production, and a maintenance window on the peer device took the connection down for several hours. The fix was the second tunnel on the second gateway interface and a second peer interface, which the team could have created on day one.
  • Interconnect without encryption review. A regulated workload moved to a Dedicated Interconnect and the project assumed "private means encrypted". An audit found plaintext on the circuit. The remedy was HA VPN over Interconnect for the regulated subnets, with the encryption requirement written into the design standard.

Practices

  • Create the connectivity hub as its own project in the network folder, and keep the gateways, routers and attachments in Terraform.
  • Use a documented address plan and reserve the on-premises ranges in IPAM before anything connects.
  • Always build two paths. Test the failover by taking one path down in a maintenance window and confirm the traffic moves.
  • Pick the BGP routing mode (regional or global) on purpose, and write down why.
  • Export bandwidth and tunnel status metrics to Cloud Monitoring, and alert on tunnel and BGP state changes (Hour 6).
Security note. A hybrid link extends the trust boundary. Anything reachable from on-premises can now reach routed VPC addresses unless firewall policies stop it. Apply ingress firewall policies on the VPC side that restrict on-premises source ranges to the ports they need, and never accept 0.0.0.0/0 from the hybrid range.

Symptoms and first checks

SymptomLikely causeFirst check
Design review rejects the VPN for "internet exposure"Misunderstanding of IPsec, or a real compliance requirementConfirm the requirement. If it is a hard rule, plan Interconnect, with HA VPN over Interconnect when encryption is also required
On-premises ranges clash with a VPC subnetOverlapping CIDR blocksgcloud compute networks subnets list --format="table(name,ipCidrRange)" and compare with the IPAM list
Throughput stays far below the expected bandwidthOne tunnel, single-flow limits, or a peer device bottleneckCheck the number of tunnels and whether the flow hashes onto one of them (ECMP). Test with several parallel flows
Interconnect ordered but no attachment can be createdThe physical circuit is not provisioned, or the wrong project is usedgcloud compute interconnects describe NAME and read the state and operational status
Two sites reach Google but not each otherTraffic between two hybrid connections is not transitive through the VPC by defaultReview custom route advertisements and Network Connectivity Center (Module 5)
Availability target not met after an outageThe redundant topology was not completeCheck that both gateway interfaces have tunnels and both have an Established BGP session

Triage order

  1. Confirm which project and region own the objects: gcloud compute routers list --project=PROJECT_ID.
  2. Check the virtual interface state (tunnel or VLAN attachment).
  3. Check the BGP session state on the Cloud Router (Module 2).
  4. Check the learned and advertised routes.
  5. Check firewall policies and rules, then the peer side.

Product videos change often, so the links below are search pages rather than pinned video links. Check the date of a video against the version of the documentation you use.

Official reading: Choosing a Network Connectivity product · Cloud VPN overview · Cloud Interconnect overview.

or score ≥ 70% on the quiz

Module 2 · Cloud Router and BGP

06–13 · ASNs, dynamic routing modes, advertisement modes, custom advertised routes and route priority
Cloud RouterBGPASNAdvertised routes7 min
Learning objectives
  • Explain what Cloud Router does, what an ASN is, and how a BGP session turns on-premises prefixes into VPC dynamic routes.
  • Choose between regional and global dynamic routing, and between default and custom route advertisement.
  • Create a Cloud Router and read its state with describe and get-status.
  • Use advertised route priority (MED) to prefer one path over another.

The short answer

Cloud Router (云路由器) is a managed BGP speaker attached to one VPC network in one region. It has no data plane. It opens BGP sessions over a VPN tunnel or a VLAN attachment, learns the peer's prefixes, programs them into the VPC as dynamic routes, and advertises the VPC's subnet ranges to the peer. When a tunnel fails, the session drops and the routes are withdrawn, so traffic moves to a second path without a person editing a route table.

What: the vocabulary

TermMeaningWhere you set it
ASN (自治系统号)Identity of a network in BGP. Each Cloud Router has one, and the peer has another.routers create --asn
BGP sessionThe neighbour relationship between the Cloud Router interface and the peer.routers add-bgp-peer
Link-local addressesA /30 from 169.254.0.0/16 used on the two ends of a tunnel for BGP.routers add-interface --ip-address --mask-length
Dynamic routing modeRegional or global visibility of learned routes.networks update --bgp-routing-mode
Advertisement modeWhich prefixes are announced: default or custom.routers update --advertisement-mode
Advertised route priority (MED)Preference signalled to the peer. Lower wins.add-bgp-peer --advertised-route-priority

The ASN you choose should be a private ASN (16-bit 64512–65534, or 32-bit 4200000000–4294967294) that is not already used by the peer or elsewhere in the connected networks. For Partner Interconnect the Cloud Router must use ASN 16550; Dedicated Interconnect and HA VPN accept your private choice.

Why: manual routes do not survive growth

Static routes work for one subnet and one tunnel. They fail when you add a region, a second site, or a second path. BGP gives you four things that static routes cannot: automatic failover (the route is withdrawn when the session drops), automatic propagation of new subnets, path preference through attributes such as MED, and a visible session state that you can alert on. HA VPN requires BGP for its availability target, and every VLAN attachment needs a Cloud Router.

How it works internally

  1. You create a Cloud Router in a region, attached to a VPC, with an ASN.
  2. You attach a router interface to a tunnel or VLAN attachment. This gives the router a link-local IP on the circuit.
  3. You define a BGP peer: the peer's link-local IP and the peer's ASN.
  4. The session goes through the BGP states (Idle, Connect, Active, OpenSent, OpenConfirm, Established). Only Established exchanges routes.
  5. Received prefixes become dynamic routes in the VPC. Their priority comes from the peer's MED plus a regional penalty (see below).
  6. Cloud Router advertises prefixes according to the advertisement mode.

Dynamic routing mode: regional or global

ModeLearned routes visible inAdvertises subnets fromUse when
Regional (the default for new networks)The Cloud Router's region onlySubnets in the Cloud Router's regionThe hybrid link serves one region, or you want strict regional isolation
GlobalAll regions of the VPCSubnets in all regionsOne hybrid hub should serve workloads in many regions, which is the typical hub design

With global routing, a route learned in region A is imported into other regions with an inter-region cost added to its priority, so a local path is preferred over a path that crosses regions. Check the exact penalty in the Cloud Router documentation, because it can change.

Rule of thumb. Use global dynamic routing for a network hub with workloads in several regions. Use regional for isolated, single-region environments. Set it on purpose, because the default is regional.

Advertisement modes

  • Default: advertises all subnet ranges of the VPC (per the dynamic routing mode). Subnet routes only; no custom ranges.
  • Custom: you select groups (all_subnets) and/or explicit prefixes. Use it to advertise ranges that are not VPC subnets (a peered VPC, a Private Service Connect range, a summary), or to hide subnets that on-premises should not reach.

Custom advertisement can be set on the router (all sessions) or per BGP session (override for one peer), which is how you give different sites different views.

Route priority and MED

The advertised route priority is a number from 0 to 65535 (default 100). Lower is preferred. If a VPC receives the same on-premises prefix from two sessions, it prefers the one with the lower MED. In the other direction, your on-premises router uses the MED that Cloud Router sends it, so set the same intention on both ends: primary path = low MED, backup path = high MED. If you need identical paths (active-active), give both sessions the same priority and ECMP shares the traffic.

When to use what

NeedSetting
One region, one siteRegional routing, default advertisement
One hub serving many regionsGlobal routing, default advertisement
Peered or Private Service Connect ranges reachable from on-premisesCustom advertisement with the extra prefixes
Primary Interconnect, backup VPNLower MED on the Interconnect sessions, higher on the VPN sessions
Two equal tunnelsSame MED on both, ECMP

What it is confused with

Looks similarDifference
Static routesFixed next hop that you maintain. No health awareness, so they do not withdraw when a tunnel fails unless you add logic around them.
Cloud NATAlso needs a Cloud Router, but only as an anchor for NAT configuration. It does not need to run BGP sessions.
VPC Network PeeringExchanges subnet routes between VPCs without BGP. Peered routes are not re-advertised to on-premises unless you add custom advertisements.
Policy-based routingSelects next hops by packet attributes. BGP selects by prefix and attributes in the control plane.

Three common misunderstandings

"Cloud Router is in the data path." It is not. If Cloud Router restarts, packets continue to flow on existing routes while the control plane recovers. A router object does not add latency or throughput limits to the tunnel.
"The same ASN on both sides is fine." Two different ASNs give an eBGP session. Using the same ASN makes it iBGP behavior and is not what the standard topologies use. Pick different private ASNs.
"Default advertisement shows everything." The default shows the VPC subnet ranges only. It never includes ranges learned from other places, or peered VPC subnets.
On-premises router AS 65002 192.168.0.0/16 172.16.0.0/12 169.254.0.2 Google Cloud VPC hub-vpc · global routing Cloud RouterAS 64514 · 169.254.0.1 VPC routesdynamic · priority 100 Subnet 10.10.0.0/24 UPDATE: learn 192.168.0.0/16, 172.16.0.0/12 UPDATE: advertise 10.10.0.0/24, MED 100 BGP session over the tunnel (eBGP) Established → routes exchanged Down → routes withdrawn

Figure 1. Cloud Router is the control plane. The arrows show route advertisements, not packets. Packets use the dynamic routes after they are installed.

Regional dynamic routing europe-west4Cloud Routerlearns 192.168.0.0/16 us-central1no route to192.168.0.0/16 Learned routes stay in the region of the Cloud Router. Safe for single-region sites. Global dynamic routing europe-west4Cloud Routerlearns 192.168.0.0/16 us-central1route imported,higher priority value Learned routes are visible in all regions with an added cost. Typical for a network hub.

Figure 2. The same on-premises prefix in two modes. With global routing, workloads in a second region can reach on-premises through the hub's hybrid link.

What to look at. In Figure 1, notice that the two arrows are control-plane messages in both directions, and that the dashed box says what happens on session loss. In Figure 2, notice that the router stays in one region in both modes; only the visibility of the routes changes.

The animation follows one Cloud Router from creation to a stable session. The messages are BGP events: OPEN, UPDATE and the route installation that follows. Watch the order, because a route is never installed before the session is Established.

Commands that create objects are marked as writes. Cloud Router objects are control-plane objects and have no traffic of their own. Check gcloud compute routers --help for the flags in your SDK version.

gcloud compute networks create with global routing (write, free)

Purpose. Creates a custom-mode VPC with global dynamic routing for the lab. An empty VPC is a metadata object.

gcloud compute networks create hub-vpc \
  --subnet-mode=custom \
  --bgp-routing-mode=global \
  --project=PROJECT_ID
NAME     SUBNET_MODE  BGP_ROUTING_MODE  IPV4_RANGE  GATEWAY_IPV4
hub-vpc  CUSTOM       GLOBAL

Flags. --subnet-mode=custom avoids automatic subnets. --bgp-routing-mode is regional or global. Common errors. quota 'NETWORKS' exceeded means the project already has too many networks; remove an old lab VPC. IDs in the expected output are illustrative.

gcloud compute networks subnets create (write, free)

Purpose. Adds a subnet whose range the Cloud Router will advertise by default.

gcloud compute networks subnets create hub-subnet \
  --network=hub-vpc \
  --region=REGION \
  --range=10.10.0.0/24 \
  --project=PROJECT_ID

Flags. --range must not overlap an on-premises range. Cost. Free; a subnet costs nothing until resources use it.

gcloud compute routers create (write, free for an idle router)

Purpose. Creates the Cloud Router for the VPC in one region.

gcloud compute routers create rtr-hub \
  --network=hub-vpc \
  --region=REGION \
  --asn=64514 \
  --project=PROJECT_ID
Creating router [rtr-hub]...done.
NAME     REGION        NETWORK
rtr-hub  europe-west4  hub-vpc

Flags. --asn is your private ASN. --advertisement-mode defaults to default. Common errors. Invalid value for field 'resource.bgp.asn' means the ASN is not in a valid range; use a private ASN. Cost. The router has no data plane. Check the current pricing page for any router-related charge before you leave one running with attachments.

gcloud compute routers describe

Purpose. Shows the configuration: ASN, interfaces, BGP peers and advertisement settings.

gcloud compute routers describe rtr-hub --region=REGION --project=PROJECT_ID
bgp:
  advertiseMode: DEFAULT
  asn: 64514
  keepaliveInterval: 20
kind: compute#router
name: rtr-hub
network: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/hub-vpc
region: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/europe-west4

Common errors. was not found means the region is wrong; Cloud Routers are regional.

gcloud compute routers get-status

Purpose. Shows the live state: BGP peers, best routes learned and routes advertised. It is the first command to run when a session looks wrong.

gcloud compute routers get-status rtr-hub --region=REGION --project=PROJECT_ID \
  --format="yaml(result.bgpPeerStatus)"
result:
  bgpPeerStatus:
  - ipAddress: 169.254.0.1
    name: bgp-peer-0
    peerIpAddress: 169.254.0.2
    state: Established
    status: UP
    numLearnedRoutes: 2
    uptime: 4 hours, 12 minutes

Flags. --format="yaml(...)" trims the output to the peer status. The exact fields depend on the SDK and API version; run it once without --format to see all of them. With no BGP peer yet, bgpPeerStatus is empty. Production use. Alert on state and on a drop in numLearnedRoutes.

gcloud compute routers update for custom advertisement (write)

Purpose. Advertises the subnets plus an explicit range, such as a peered VPC or a summary route, to all sessions on the router.

gcloud compute routers update rtr-hub \
  --region=REGION \
  --advertisement-mode=custom \
  --set-advertisement-groups=all_subnets \
  --set-advertisement-ranges=10.50.0.0/16 \
  --project=PROJECT_ID

Flags. --set-advertisement-groups=all_subnets keeps the subnet routes; --set-advertisement-ranges adds prefixes and replaces the existing custom list. Use --add-advertisement-ranges to append. Common errors. Forgetting all_subnets stops advertising the subnets and breaks return traffic. Cost. Free; it is a configuration change.

gcloud compute routes list

Purpose. Confirms which routes exist in the VPC, including dynamic routes learned over BGP.

gcloud compute routes list --project=PROJECT_ID \
  --filter="network:hub-vpc" \
  --format="table(name,destRange,priority,nextHopVpnTunnel.basename())"
NAME                         DEST_RANGE       PRIORITY  NEXT_HOP_VPN_TUNNEL
default-route-aaaa1111       0.0.0.0/0        1000
peering-route-bbbb2222       10.10.0.0/24     0
dynamic-route-cccc3333       192.168.0.0/16   100       tun-hub-0

Dynamic route names are generated. Learned routes appear here only after a session is Established. The lab VPC has no default internet route if you removed it.

Production use. Save get-status output before and after a change window. Compare learned and advertised prefix counts. A sudden drop in learned routes is the first sign of a peer-side problem.

Lab 2: create a lab VPC and Cloud Router, then read the state (about 12 minutes, free)

Goal. Create a custom VPC with a subnet and a Cloud Router, change the advertisement mode, and read describe and get-status. No tunnel is created in this lab, so no BGP session exists yet; Module 3 adds the tunnels.

Prerequisites. A sandbox project with billing linked and a budget set (Hour 1, Module 3), the Compute Engine API enabled, and roles/compute.networkAdmin. If you have no organization, the lab works unchanged in a personal project. IDs in the expected output are illustrative.

  1. Set variables: PROJECT_ID=your-sandbox-project, REGION=europe-west4 (any region you are allowed to use).
  2. Create the VPC with global routing: the networks create command from the previous tab.
  3. Verify: gcloud compute networks describe hub-vpc --format="value(routingConfig.routingMode)" must print GLOBAL.
  4. Create the subnet hub-subnet with 10.10.0.0/24 in the region.
  5. Create the router rtr-hub with ASN 64514.
  6. Verify the router: gcloud compute routers describe rtr-hub --region=$REGION --format="value(bgp.asn,bgp.advertiseMode)".
  7. Switch to custom advertisement with 10.50.0.0/16 added, then describe again and confirm advertiseMode: CUSTOM.
  8. Read the status: gcloud compute routers get-status rtr-hub --region=$REGION. Note that no BGP peers are listed.
  9. Switch back to default advertisement: gcloud compute routers update rtr-hub --region=$REGION --advertisement-mode=default.

Verification outputs.

GLOBAL
64514	DEFAULT

Expected result. A VPC in global routing mode, one subnet, one Cloud Router with an ASN, and a status response with no BGP peers. You have seen both advertisement modes.

Cost. Free for the VPC, subnet and router configuration, because no tunnels, gateways or VMs exist. Confirm on the Cloud Router pricing note if you keep it for days.

Cleanup. Keep the VPC and router for Module 3, or delete them now: gcloud compute routers delete rtr-hub --region=$REGION, then gcloud compute networks subnets delete hub-subnet --region=$REGION, then gcloud compute networks delete hub-vpc. Delete in this order, because a subnet cannot be removed while the router or other resources still reference the network.

Lab 2b (optional): design an advertisement plan

Write the list of prefixes that your hub should advertise to on-premises (subnets, a peered VPC, a Private Service Connect range) and the list it must not advertise (sandbox subnets, test ranges). Express it as a --set-advertisement-ranges value and decide whether it belongs on the router or on a single BGP session.

Typical cases

  • Peered VPC invisible to on-premises. A data platform sat in a peered VPC. On-premises users reached the hub subnets but not the platform, because default advertisement does not include peered ranges. The team added the peered range as a custom advertised prefix on the hub router and enabled export of custom routes on the peering. The fix took one change, but finding it took a day because nobody had read the advertised-route list.
  • Failover that never failed over. Two sessions had the same MED, so traffic used both paths. When one tunnel degraded, packets were still hashed onto it until BGP dropped. The team set a primary and a backup (low and high MED), and added BFD on supported sessions to shorten detection time.
  • ASN collision. A merger brought a second on-premises network that used the same private ASN as the Cloud Router. BGP loop prevention dropped the routes. Renumbering one side with a documented ASN registry solved it. The lesson is to keep an ASN register in the landing-zone repository.

Practices

  • Keep a register of ASNs, link-local /30 allocations and advertised prefixes. Conflicts hide in spreadsheets.
  • Use custom advertisement deliberately. Advertise summaries, not every subnet, when on-premises routers have limited route tables.
  • Set MED explicitly on every session, even when "equal", so the intent is readable in code.
  • Use MD5 authentication on BGP sessions where the peer supports it, and store the key in Secret Manager.
  • Treat a Cloud Router change as a network change: plan, review, apply from Terraform (Hour 7), and keep a rollback.
Security note. BGP accepts what the peer announces. Filter inbound prefixes on the peer side and review the learned routes. A mistaken broad prefix learned from on-premises (for example 10.0.0.0/8) can attract traffic that belongs to VPC ranges that are more specific only in some regions. Use the narrowest ranges and apply firewall policies as a second control.

Symptoms and first checks

SymptomLikely causeFirst check
BGP state stays Idle or ConnectTunnel not up, wrong peer IP, or wrong ASNgcloud compute routers get-status ROUTER --region=REGION and the tunnel status
Session Established but numLearnedRoutes is 0The peer does not advertise, or a route filter drops the prefixesCheck the peer's advertised-routes list and its outbound policy
VPC subnet unreachable from on-premisesSubnet not advertised: custom mode without all_subnets, or regional mode in another regionrouters describe for advertiseMode; networks describe for the routing mode
Region B cannot reach on-premisesRegional dynamic routinggcloud compute networks update NETWORK --bgp-routing-mode=global (plan the change)
Traffic uses the backup pathMED values reversed or equalCompare advertisedRoutePriority on each BGP peer and the peer's local preference
Routes flap every few minutesUnstable tunnel, timer mismatch, or an overloaded peerCheck tunnel logs, keepalive and hold timers on both sides
BGP session rejected after an ASN changeThe peer still expects the old ASNUpdate --peer-asn on the BGP peer and the peer config together

Triage order

  1. Is the virtual interface (tunnel or attachment) up?
  2. Does the link-local addressing match on both ends, and do both ASNs match the configuration?
  3. Is the BGP state Established?
  4. Are the expected prefixes learned and advertised?
  5. Are the dynamic routes in routes list with the expected priority?
  6. Only then look at firewall policies and the peer's route filters.

Video links are search pages so that no outdated or invented video is pinned. Prefer videos from the Google Cloud channel and check the date.

Official reading: Cloud Router overview · Advertised routes · Routes.

or score ≥ 70% on the quiz

Module 3 · HA VPN

13–21 · Gateways with two interfaces, peer gateways, tunnels, BGP sessions and the two-tunnel availability design
HA VPNIPsecTunnelsBGPBillable lab8 min
Learning objectives
  • Describe the parts of an HA VPN connection: HA VPN gateway, peer gateway, tunnels, Cloud Router interfaces and BGP peers.
  • Build a redundant HA VPN between two VPC networks with gcloud, and verify tunnels, BGP sessions and learned routes.
  • Explain what the availability target requires, and clean up billable gateways and tunnels in the right order.

The short answer

HA VPN (高可用 VPN) is a managed IPsec VPN service. An HA VPN gateway is a regional object with two interfaces, each with its own external IP address. You connect each interface to a peer gateway through an IPsec tunnel, and each tunnel runs a BGP session on a Cloud Router. When one tunnel or one interface fails, BGP withdraws its routes, and traffic continues on the other. This pair of tunnels is the design that carries Google's availability target for HA VPN.

What: the parts of a connection

ObjectWhat it isCommand group
VPC networkWhere the learned routes are installed.gcloud compute networks
Cloud RouterBGP speaker with an ASN, in the gateway's region.gcloud compute routers
HA VPN gatewayTwo interfaces, two external IPs.gcloud compute vpn-gateways
Peer gatewayAnother HA VPN gateway, or an external VPN gateway resource for on-premises or another cloud.gcloud compute external-vpn-gateways
VPN tunnelAn IPsec connection from a gateway interface to a peer interface, with a shared secret and a Cloud Router.gcloud compute vpn-tunnels
Router interfaceBinds a tunnel to the Cloud Router and gives it a link-local IP.gcloud compute routers add-interface
BGP peerThe neighbour on the tunnel: its link-local IP and ASN.gcloud compute routers add-bgp-peer

Why: the availability design

Google publishes an availability target of 99.99% for HA VPN. It applies to the Google side of the connection when you follow a documented topology. The common ones are:

  • HA VPN to HA VPN (two Google Cloud networks): two tunnels, interface 0 to interface 0 and interface 1 to interface 1, with BGP on each.
  • HA VPN to a peer with two interfaces (one on-premises device with two public IPs, or two devices): two tunnels to the peer's two interfaces.
  • HA VPN to a peer with one interface: two tunnels from the two gateway interfaces to the same peer IP. This is supported for the Google side, but the availability of your device is your risk.
  • HA VPN to a peer with four interfaces: four tunnels, for larger designs.

Whatever the shape, the rules are the same: both gateway interfaces are used, every tunnel has a BGP session, and the peer is configured to match. Check the exact topologies and the SLA wording in the current documentation before you quote the target to a customer.

How it works internally

  1. Gateway creation. Google allocates two regional external IP addresses to the gateway interfaces.
  2. Peer description. For on-premises, you create an external-vpn-gateways resource listing the peer's public IPs and the redundancy type.
  3. Tunnel creation. Each tunnel names its gateway and interface, its peer interface, the IKE version (2) and the shared secret, and is bound to a Cloud Router. The tunnel starts negotiating IKE as soon as the peer also has a matching configuration.
  4. Router interface and BGP peer. You attach a link-local /30 (from 169.254.0.0/16) to the tunnel and define the peer's link-local IP and ASN. Link-local addresses must be unique per tunnel and must not clash with reserved ranges.
  5. Route exchange. When BGP is Established, routes are learned and advertised (Module 2). The VPC routing table now holds dynamic routes with the tunnels as next hops.
  6. Packet forwarding. Packets to a learned prefix are encrypted into ESP and sent on a tunnel. With equal MED, traffic is spread over both tunnels (ECMP), each carrying a share by flow.

When to use HA VPN

  • You need a connection in minutes, with encryption, and a few Gbps of bandwidth is enough.
  • You need a backup path for an Interconnect.
  • You connect two VPC networks in different projects or organizations with a simple, private path (when VPC Network Peering is not suitable, for example overlapping policy requirements or transit needs).
  • You connect to another cloud provider's VPN gateway (it supports the same IKEv2 and BGP standards).

Limits and design numbers to check

TopicDetail
Throughput per tunnelA tunnel has a documented maximum (a few Gbps); the exact figure and packet-per-second limits are in the Cloud VPN quotas page. Add tunnels to scale and rely on ECMP.
Single flowOne flow uses one tunnel. A transfer with one TCP connection does not use the combined bandwidth.
MTUIPsec adds overhead. Use the documented gateway MTU and set the MSS on the peer accordingly, or fragmentation will hurt throughput (see Troubleshooting).
Ports and protocolsUDP 500, UDP 4500 (NAT-T) and ESP (IP protocol 50) must be allowed on the peer side's firewall.
RoutingBGP via Cloud Router. Static routing exists for Classic VPN only; do not use it for new designs.

What it is confused with

Looks similarDifference
Classic VPNOlder gateway with one interface and static or policy-based options. New designs should use HA VPN. Check the product page for the Classic VPN deprecation status before migrating.
VPC Network PeeringNon-encrypted, non-transitive link between two VPCs over Google's network, no gateway. HA VPN between VPCs is encrypted and can be used with custom advertisement for transit.
Cloud InterconnectPrivate circuit. HA VPN uses the internet unless it runs over Interconnect.
Identity-Aware Proxy TCP forwardingGives people access to a VM. It is not a network-to-network link.

Three common misunderstandings

"HA VPN is always 99.99%." Only with the redundant topology. One tunnel, tunnels on one interface, or no BGP do not qualify.
"More tunnels give one fast connection." More tunnels give more aggregate bandwidth across many flows. A single flow stays on one tunnel and keeps that tunnel's limit.
"The shared secret is only a setup detail." It is a credential. A leaked or weak secret weakens the whole connection, so generate it randomly, store it in Secret Manager, and rotate it with a planned change.
vpc-a · 10.10.0.0/24 region REGION Cloud Router rtr-aAS 65001 HA VPN gateway gw-a interface 0 · IP a0 interface 1 · IP a1 vpc-b · 10.20.0.0/24 region REGION Cloud Router rtr-bAS 65002 HA VPN gateway gw-b interface 0 · IP b0 interface 1 · IP b1 tunnel 0 · IPsec IKEv2 tunnel 1 · IPsec IKEv2 BGP session 0 169.254.0.1 ↔ .2 BGP session 1 169.254.1.1 ↔ .2 Interface 0 pairs with interface 0, interface 1 with interface 1.

Figure 1. The redundant GCP-to-GCP topology used in the lab. Four tunnel resources exist (two on each gateway), forming two tunnel pairs. Each pair has its own BGP session.

1 · VPCssubnets, firewall 2 · RoutersASN per side 3 · Gateways2 IPs each (billable) 4 · Tunnelssame secret (billable) 5 · BGPinterface + peer 6 · Verify: tunnel ESTABLISHED · BGP Established · dynamic routes · test traffic Verify after steps 4 and 5, not only at the end. Cleanup is the reverse: tunnels, routers, gateways, subnets, networks. Amber boxes bill while they exist.

Figure 2. The order of creation. The amber boxes (gateways and tunnels) are the billable objects in the lab, so the cleanup step is part of the design.

What to look at. In Figure 1, check that each tunnel connects the same interface number on both sides, and that BGP uses a different /30 per tunnel. In Figure 2, notice that verification is a step, not an afterthought, and that cleanup reverses the order.

The animation follows a GCP-to-GCP HA VPN build from gateway creation to learned routes. Each message is a real status: the interface IPs the API returns, a tunnel state, a BGP state, and a dynamic route in the VPC table.

Cost. HA VPN gateways and tunnels are metered resources. Commands that create them are labelled billable. Cost is low for a short lab (usually well under a few USD for an hour with idle tunnels), but a forgotten connection keeps billing every day. Budgets send alerts and do not cap spend.

Placeholders: PROJECT_ID, REGION. Check gcloud compute vpn-tunnels create --help for the flags in your SDK version.

gcloud compute vpn-gateways create (write, billable)

Purpose. Creates an HA VPN gateway with two interfaces in a region and attaches it to a VPC.

gcloud compute vpn-gateways create gw-a \
  --network=vpc-a \
  --region=REGION \
  --project=PROJECT_ID
Created [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/europe-west4/vpnGateways/gw-a].
NAME  INTERFACE0     INTERFACE1     NETWORK  REGION
gw-a  203.0.113.10   203.0.113.11   vpc-a    europe-west4

Flags. --network binds the gateway to the VPC. The gateway is regional. Common errors. quota 'VPN_GATEWAYS' exceeded means the regional gateway quota is reached. IDs and addresses in the expected output are illustrative.

gcloud compute external-vpn-gateways create (write, free)

Purpose. Describes an on-premises or other-cloud peer. It is only needed when the peer is not another Google HA VPN gateway.

gcloud compute external-vpn-gateways create peer-onprem \
  --interfaces=0=PEER_IP_0,1=PEER_IP_1 \
  --project=PROJECT_ID

Flags. --interfaces lists interface IDs and the peer's public IPs. Use one, two or four interfaces to match the peer's redundancy. Check gcloud compute external-vpn-gateways create --help for the redundancy flags in your SDK version. Cost. Free, it is a description object.

gcloud compute vpn-tunnels create (write, billable)

Purpose. Creates one IPsec tunnel from a gateway interface to a peer interface, bound to a Cloud Router.

VPN_SECRET="$(openssl rand -base64 24)"

gcloud compute vpn-tunnels create tun-a0 \
  --region=REGION \
  --vpn-gateway=gw-a \
  --interface=0 \
  --peer-gcp-gateway=gw-b \
  --router=rtr-a \
  --ike-version=2 \
  --shared-secret="$VPN_SECRET" \
  --project=PROJECT_ID
Created [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/europe-west4/vpnTunnels/tun-a0].
NAME    REGION        GATEWAY  VPN_INTERFACE  PEER_ADDRESS  PEER_GCP_GATEWAY
tun-a0  europe-west4  gw-a     0                            gw-b

Flags. --vpn-gateway and --interface select the local interface. --peer-gcp-gateway is used when the peer is another HA VPN gateway; for an external peer use --peer-external-gateway and --peer-external-gateway-interface instead. --router binds the tunnel to the Cloud Router. --ike-version=2 is required for HA VPN. Security. The secret is generated at the moment of use and kept only in the shell variable; for a real connection, create it once and store it in Secret Manager. Common errors. A mismatched secret on the two sides leaves the tunnel in NEGOTIATION_FAILURE or FIRST_HANDSHAKE.

gcloud compute routers add-interface (write, free)

Purpose. Binds a tunnel to the Cloud Router and assigns the router's link-local IP.

gcloud compute routers add-interface rtr-a \
  --interface-name=if-a0 \
  --ip-address=169.254.0.1 \
  --mask-length=30 \
  --vpn-tunnel=tun-a0 \
  --region=REGION \
  --project=PROJECT_ID

Flags. --ip-address and --mask-length give the Cloud Router side of the /30. The peer uses the other usable address. Common errors. Invalid value for field 'resource.interfaces[0].ipRange' means the range is outside the allowed 169.254.0.0/16 link-local range, or collides with a reserved block.

gcloud compute routers add-bgp-peer (write, free)

Purpose. Defines the BGP neighbour on that interface.

gcloud compute routers add-bgp-peer rtr-a \
  --peer-name=bgp-a0 \
  --interface=if-a0 \
  --peer-ip-address=169.254.0.2 \
  --peer-asn=65002 \
  --advertised-route-priority=100 \
  --region=REGION \
  --project=PROJECT_ID

Flags. --peer-ip-address is the other end of the /30. --peer-asn is the neighbour's ASN. --advertised-route-priority sets the MED. For HA VPN, Google can also allocate link-local addresses automatically with some flags; check gcloud compute routers add-bgp-peer --help in your SDK version.

gcloud compute vpn-tunnels describe

Purpose. Reads the live tunnel status.

gcloud compute vpn-tunnels describe tun-a0 --region=REGION --project=PROJECT_ID \
  --format="value(status,detailedStatus)"
ESTABLISHED	Tunnel is up and running.

Common statuses. PROVISIONING (being created), WAITING_FOR_FULL_CONFIG (the peer side is missing), FIRST_HANDSHAKE (negotiating), ESTABLISHED (up), NO_INCOMING_PACKETS (nothing from the peer), NEGOTIATION_FAILURE (parameters or secret mismatch), REJECTED, FAILED, STOPPED. The detailed text varies.

gcloud compute routers get-status and routes list

Purpose. Confirms the BGP session and the learned routes. Run these after each tunnel is added.

gcloud compute routers get-status rtr-a --region=REGION --project=PROJECT_ID \
  --format="yaml(result.bgpPeerStatus)"

gcloud compute routes list --project=PROJECT_ID --filter="network:vpc-a" \
  --format="table(name,destRange,priority)"
result:
  bgpPeerStatus:
  - name: bgp-a0
    peerIpAddress: 169.254.0.2
    state: Established
    status: UP
  - name: bgp-a1
    peerIpAddress: 169.254.1.2
    state: Established
    status: UP
NAME                        DEST_RANGE     PRIORITY
dynamic-route-aaaa1111      10.20.0.0/24   100
dynamic-route-bbbb2222      10.20.0.0/24   100

Two equal routes confirm that ECMP is available for 10.20.0.0/24.

Production use. Generate the secret in Terraform with a random resource or Secret Manager, never in a ticket or chat. Create tunnels, router interfaces and BGP peers from one module, so they cannot drift apart.

Lab 3: HA VPN between two lab VPCs (about 25 minutes, billable)

Billable resources. This lab creates two HA VPN gateways and four tunnels. They bill while they exist. Cost is low if you finish and clean up within the hour (usually well under a few USD), and keeps accruing if you forget. Set a budget first. Budgets send alerts and do not cap spend. Run the cleanup in this lab even if a step fails.

Goal. Build the redundant topology from Figure 1, prove the tunnels and BGP sessions are up, and read the learned routes.

Prerequisites. A sandbox project with a budget alert, the Compute Engine API enabled, and roles/compute.networkAdmin. An organization is not required. If an organization policy blocks VPN or restricts regions, use the allowed region or ask the platform team. No real secrets are used: the pre-shared key is random and lives in the shell session. IDs in the expected output are illustrative.

  1. Set variables: PROJECT_ID, REGION=europe-west4. Create the networks and subnets: vpc-a with subnet sub-a (10.10.0.0/24) and vpc-b with subnet sub-b (10.20.0.0/24), both in custom mode with global routing, as in Module 2.
  2. Create the routers: rtr-a with ASN 65001 on vpc-a, and rtr-b with ASN 65002 on vpc-b.
  3. Create the gateways gw-a and gw-b. Verify: gcloud compute vpn-gateways list shows two IPs for each.
  4. Create the shared secret once: VPN_SECRET="$(openssl rand -base64 24)". Do not print it.
  5. Create four tunnels with the same secret: tun-a0 (gw-a interface 0 to gw-b), tun-a1 (gw-a interface 1), tun-b0 (gw-b interface 0 to gw-a), tun-b1 (gw-b interface 1). Each tunnel uses its own side's router. With --peer-gcp-gateway, interface 0 pairs with interface 0.
  6. Verify: gcloud compute vpn-tunnels list --filter="region:REGION" shows all four. Status may remain WAITING_FOR_FULL_CONFIG until both sides exist, then ESTABLISHED after a minute.
  7. Add router interfaces and BGP peers. Pair 0 uses 169.254.0.0/30: rtr-a is 169.254.0.1 and rtr-b is 169.254.0.2. Pair 1 uses 169.254.1.0/30. Peer ASNs are 65002 on rtr-a and 65001 on rtr-b.
  8. Verify: get-status on both routers shows Established on two BGP peers each.
  9. Verify: gcloud compute routes list --filter="network:vpc-a" shows two dynamic routes to 10.20.0.0/24, and the same in vpc-b for 10.10.0.0/24.
  10. Failover test (optional, free): delete tun-a0 and tun-b0, wait a minute, and confirm one dynamic route remains and the pair-1 session stays Established.

Verification of data traffic (optional). Create one small VM in each VPC without an external IP and allow ICMP from the other subnet. Use IAP TCP forwarding to log in and run a ping to the other VM's internal IP. The VMs are billable, so delete them right after the ping. If you skip this, the route and BGP checks prove the control plane, and Hour 5's Module 7 covers the data plane test.

Expected result. Four tunnels in ESTABLISHED, four BGP sessions in Established, and two dynamic routes on each side.

Cost. Billable: two gateways, four tunnels, egress for any test traffic, and optional VMs. Low if cleaned up within the hour.

Cleanup (in this order).

for T in tun-a0 tun-a1 tun-b0 tun-b1; do
  gcloud compute vpn-tunnels delete $T --region=REGION --quiet --project=PROJECT_ID
done
gcloud compute routers delete rtr-a --region=REGION --quiet --project=PROJECT_ID
gcloud compute routers delete rtr-b --region=REGION --quiet --project=PROJECT_ID
gcloud compute vpn-gateways delete gw-a --region=REGION --quiet --project=PROJECT_ID
gcloud compute vpn-gateways delete gw-b --region=REGION --quiet --project=PROJECT_ID
gcloud compute networks subnets delete sub-a sub-b --region=REGION --quiet --project=PROJECT_ID
gcloud compute networks delete vpc-a vpc-b --quiet --project=PROJECT_ID
unset VPN_SECRET

Final check. gcloud compute vpn-gateways list and gcloud compute vpn-tunnels list must print Listed 0 items. Then check the billing report the next day for any remaining VPN line.

Lab 3b (optional): on-premises peer description

Without a real device, practise the on-premises shape on paper. Write the external-vpn-gateways create command with two peer IPs, and the two vpn-tunnels create commands that use --peer-external-gateway and --peer-external-gateway-interface. Compare them with the GCP-to-GCP version and note which two flags change.

Typical cases

  • Backup path that was never tested. A team built two tunnels but only monitored one. The second had a typo in the peer ASN and never reached Established. The first tunnel failed during a peer maintenance, and the "highly available" connection was down for an hour. The fix was an alert on every BGP peer, plus a quarterly failover test.
  • Throughput complaint from a single transfer. A backup job used one TCP stream over HA VPN and saw only a fraction of the expected bandwidth. The job was changed to use parallel streams, which let ECMP use both tunnels. For permanent high bandwidth, the design was extended with more tunnels and later with an Interconnect.
  • Secret in a ticket. A pre-shared key was pasted into a support ticket. It was rotated, and the process was changed so the key lives only in Secret Manager and in the Terraform state with restricted access.

Practices

  • Always use two tunnels at minimum, on both gateway interfaces, with BGP on each.
  • Pick unique link-local /30 ranges per tunnel and store them in the network register.
  • Monitor tunnel status, BGP session state and tunnel throughput. Alert on state changes (Hour 6).
  • Test failover on a schedule, in a window, and measure the failover time.
  • Rotate the shared secret on a schedule with a planned change that updates both sides.
  • Tag the objects with labels so cost reports show which team owns each gateway. Check which resources accept labels in your SDK version.
Security note. IPsec protects traffic on the internet path, but the network behind the tunnel is now reachable. Restrict ingress from the peer ranges with firewall policies. Do not use a weak or reused secret. Limit who can create or delete gateways with roles/compute.networkAdmin, and log changes through Cloud Audit Logs.

Symptoms and first checks

SymptomLikely causeFirst check
Tunnel status WAITING_FOR_FULL_CONFIGRouter interface, peer gateway or peer side not yet configuredvpn-tunnels describe, then check the router interface and the peer's tunnel
Tunnel status NEGOTIATION_FAILURE or stuck in FIRST_HANDSHAKEShared secret mismatch, wrong IKE version, or incompatible cipher settings on the peerRecreate with the correct secret; confirm IKEv2 and the supported ciphers on the peer
Tunnel status NO_INCOMING_PACKETSWrong peer IP, peer device down, firewall blocking UDP 500, UDP 4500 or ESPVerify the peer public IP in vpn-tunnels describe and the peer firewall
Tunnel up, BGP stays Idle or ActiveLink-local IPs or ASNs do not match on the two sidesrouters describe and compare with the peer's neighbour configuration
BGP Established, no trafficFirewall rules or policies block it, or routes are missing on the peerroutes list; test with Connectivity Tests and check firewall logs
Only one tunnel carries trafficUnequal MED, or a single flowCompare advertisedRoutePriority on both BGP peers; test with parallel flows
Large transfers stall, small pings workMTU or MSS mismatch causing fragmentation dropsTest with ping and the don't-fragment flag; lower the MSS on the peer (Module 8)

Triage order

  1. Tunnel status (vpn-tunnels describe): this tells you whether IKE works.
  2. Router interface and BGP peer configuration: link-local addresses and ASNs.
  3. BGP state and learned or advertised routes (get-status).
  4. VPC routes and firewall policies.
  5. Peer device logs and its firewall.
  6. Logs of the tunnel in Cloud Logging (the VPN gateway resource type), for IKE-level messages.

Video links are search pages so that no outdated or invented video is pinned. Prefer official Google Cloud content and confirm the date.

Official reading: Cloud VPN overview · Create an HA VPN gateway to another VPC network · Cloud VPN topologies · Troubleshooting Cloud VPN.

or score ≥ 70% on the quiz

Module 4 · Cloud Interconnect

21–28 · Dedicated and Partner Interconnect, VLAN attachments, redundancy topologies and Cloud Router
InterconnectVLAN attachmentRedundancyMACsec7 min
Learning objectives
  • Describe Dedicated Interconnect, Partner Interconnect and Cross-Cloud Interconnect, and the role of the VLAN attachment and the Cloud Router.
  • Choose a redundancy topology that matches the availability target, and explain why a single circuit is not enough.
  • Inspect Interconnect objects with read-only gcloud commands and plan an order without creating billable circuits in a lab.

The short answer

Cloud Interconnect (互联) provides a private connection between your network and Google Cloud that does not cross the public internet. There are three kinds. Dedicated Interconnect is a direct physical link between your router and Google at a colocation facility, in 10 Gbps or 100 Gbps circuits. Partner Interconnect reaches Google through a supported service provider, in smaller capacities, with no equipment in a Google facility. Cross-Cloud Interconnect is a Google-managed circuit between Google Cloud and another cloud provider. In every case a VLAN attachment binds the connection to a VPC network through a Cloud Router.

What: the objects

ObjectWhat it isWho creates it
Interconnect (Dedicated)The physical circuit order: location, link type (10 or 100 Gbps), number of links, and the Letter of Authorization.You, then Google provisions; you cross-connect at the facility
Interconnect attachment (VLAN attachment)A VLAN on an Interconnect or a partner connection, with bandwidth and a Cloud Router.You
Pairing key (Partner)A token that identifies the attachment to the service provider.Google, returned by the attachment
Cloud RouterBGP speaker for the attachment.You (Module 2)
Edge availability domainFailure domain inside a metropolitan area, used to place redundant attachments.You choose it on Partner; Google allocates it on Dedicated links

Why: when a VPN is not enough

  • Bandwidth and cost shape. Sustained high volumes (data replication, analytics ingest, migrations) are cheaper and more predictable over a circuit than over many VPN tunnels.
  • Latency stability. A private path avoids the variable internet route.
  • Policy. Some policies forbid sending regulated traffic over the public internet, even encrypted.
  • Cost of egress. Data transfer over Interconnect is billed on a different rate card than internet egress. Compare totals for your volume with the Google Cloud pricing calculator before deciding; this course does not state prices.

How it works: the Dedicated path

  1. Order. You request an Interconnect in a location (gcloud compute interconnects create with the link type and number of links) and Google returns a Letter of Authorization.
  2. Cross-connect. The facility provider connects your router to Google's edge. Google tests the link (state moves through PROVISIONED and operational status).
  3. Attach. You create a VLAN attachment on the Interconnect in a region, with a bandwidth and a Cloud Router.
  4. Peer. You configure the VLAN and BGP on your router using the values from the attachment (the link-local /29 and the Cloud Router's ASN). Once BGP is Established, routes flow.

How it works: the Partner path

  1. Create the attachment with attachments partner create in a region, choosing the edge availability domain. The state is PENDING_PARTNER, and Google returns a pairing key.
  2. Order from the provider and give them the key. The provider configures its side.
  3. Activate. When the state is PENDING_CUSTOMER, you enable the attachment. Partner attachments are not usable until you activate them.
  4. Peer. The Cloud Router (ASN 16550) and your router (or the provider's router, for a layer 3 service) exchange routes by BGP.

Providers offer layer 2 (you run BGP) or layer 3 (the provider runs BGP for you). The ownership of the router configuration is the key difference.

Redundancy topologies

TargetTopology (summary)Failure it survives
No SLAOne connection in one locationNone. Use only for non-critical or development
99.9%Two connections in one metro, in different edge availability domains, with attachments and Cloud Routers per the documentationA single device or domain failure
99.99%Four connections in two metros, two in each, in different edge availability domains, with a Cloud Router in each of two regionsA facility, edge domain or metro failure

For both Dedicated and Partner, check the current "production-level" and "critical" topology diagrams, because wording and requirements (for example the use of global dynamic routing and the number of Cloud Routers) are specific.

Encryption options

OptionLayerNotes
None-Private path, plaintext on the wire. Acceptable only if policy allows it
MACsec2Between your router and Google's edge on supported Dedicated connections; check which link types and locations support it
HA VPN over Interconnect3IPsec tunnels over VLAN attachments, with its own gateways and Cloud Routers; works with Dedicated and Partner
Application-level TLS4–7Always recommended in addition

Cross-Cloud Interconnect

For multicloud, Google can provision a direct circuit between Google's network and another supported cloud provider's network. You request it in a supported location, and Google manages the cross-connect on its side. It still ends as a VLAN attachment and a Cloud Router. Use it when cloud-to-cloud data movement is large and recurring.

When to use what

SituationChoice
Data centre in a city with a Google colocation facility, tens of GbpsDedicated Interconnect
Remote branches, 50 Mbps to a few Gbps, no colocation presencePartner Interconnect
Encryption mandatory, private pathDedicated with MACsec, or HA VPN over Interconnect
Interconnect primary, cheap backupHA VPN with a higher MED
Large recurring cloud-to-cloud transfersCross-Cloud Interconnect

What it is confused with

Looks similarDifference
Direct Peering and Carrier PeeringPublic routing to Google at edge points of presence. They reach Google public services, but not private VPC addresses.
HA VPNInternet path with IPsec. Needs no physical order and is available in minutes.
VPC Network PeeringConnects two VPCs, not to an outside network.
Partner "Interconnect" from a provider's own productOnly attachments created in Google Cloud with a pairing key are Google Cloud Partner Interconnect. A provider's separate internet VPN product is not.

Three common misunderstandings

"One 10 Gbps circuit is a highly available design." A single circuit, even a large one, is a single point of failure. Availability comes from the topology, not from the speed.
"Private means encrypted." Interconnect is not encrypted by default. Decide on MACsec, HA VPN over Interconnect or application TLS and document it.
"Create the attachment and it works." Partner attachments wait for the provider and for your activation. Dedicated attachments need a working cross-connect and your router's VLAN and BGP configuration.
On-premises two data centres Router DC-1metro 1 Router DC-2metro 2 Metro 1 · colocation Connection 1 · domain 1 Connection 2 · domain 2 Metro 2 · colocation Connection 3 · domain 1 Connection 4 · domain 2 Google Cloud VPC global dynamic routing Region 1 · Cloud Router2 VLAN attachments Region 2 · Cloud Router2 VLAN attachments Workloads in any region use both metros.

Figure 1. The highest-availability topology. Each metro has two connections in different edge availability domains, and each region has its own Cloud Router. This is a summary; use the current Google diagram for the exact requirements.

Createattachments partner create PENDING_PARTNERpairing key issued PENDING_CUSTOMERprovider is ready ACTIVEyou activate; BGP can start you send the key to the provider you review and enable the attachment The attachment bills and carries traffic only after it is active and BGP is Established. State names are from the API; check the current attachment documentation for the full list.

Figure 2. The life cycle of a Partner attachment. The handover to the provider happens between the first two states.

What to look at. In Figure 1, count the failure domains: two edge availability domains in each of two metros. Removing any one of them still leaves a path. In Figure 2, notice that there are two human steps (send the key, activate), so a forgotten activation looks like "the provider is slow".

The animation follows a Partner Interconnect attachment from creation to a BGP session. The states are real attachment states, and the last two steps are the BGP session and the route exchange on the Cloud Router.

Cost. Dedicated circuits, Partner attachments and the data transfer over them are billable and need a business agreement or a provider order. The commands marked read-only are free. The commands that create attachments are shown so you recognise them, and the lab does not run them.

Placeholders: PROJECT_ID, REGION, LOCATION. Check gcloud compute interconnects --help and gcloud compute interconnects attachments --help for the flags in your SDK version. Output shapes are illustrative, because real output depends on a live circuit.

gcloud compute interconnects locations list (read-only, free)

Purpose. Lists facilities where Dedicated Interconnect is available, to choose a location near your data centre.

gcloud compute interconnects locations list --project=PROJECT_ID \
  --format="table(name,city,continent,availableLinkTypes.list())"

Flags. The table format shows a few columns instead of the full resource. Common errors. An empty result with no error means the Compute Engine API is disabled or the identity lacks compute.interconnectLocations.list.

gcloud compute interconnects list and describe (read-only, free)

Purpose. Lists the Dedicated Interconnects in a project and reads the state and operational status of one.

gcloud compute interconnects list --project=PROJECT_ID
gcloud compute interconnects describe INTERCONNECT_NAME --project=PROJECT_ID \
  --format="yaml(name,state,operationalStatus,linkType,location,expectedOutages)"
Listed 0 items.

Reading it. A healthy Dedicated Interconnect reports an active state and an operational status of OS_ACTIVE. Run describe on a real Interconnect to see the exact values for your SDK version. In a sandbox the list is empty. Production use. Watch expectedOutages, which carries scheduled maintenance notices.

gcloud compute interconnects get-diagnostics (read-only, free)

Purpose. Shows link-level data for a Dedicated Interconnect: light levels, LACP state, ARP entries and the bundle state. It is the first check when a cross-connect does not come up.

gcloud compute interconnects get-diagnostics INTERCONNECT_NAME --project=PROJECT_ID

Reading it. No sample output is shown because it requires a real circuit. Compare receive and transmit light levels with the facility's expected range, and check that the LACP member is up. Use the output when you open a case with the facility provider.

gcloud compute interconnects attachments list and describe (read-only, free)

Purpose. Lists VLAN attachments with their region, router and state.

gcloud compute interconnects attachments list --project=PROJECT_ID \
  --format="table(name,region.basename(),type,state,router.basename(),bandwidth)"

gcloud compute interconnects attachments describe ATTACHMENT_NAME --region=REGION \
  --project=PROJECT_ID \
  --format="yaml(name,type,state,edgeAvailabilityDomain,bandwidth,router,pairingKey,cloudRouterIpAddress,customerRouterIpAddress,vlanTag8021q)"

Flags. The yaml(...) projection selects fields. cloudRouterIpAddress and customerRouterIpAddress are the two ends of the BGP link, and vlanTag8021q is the VLAN ID your router must use. Common errors. was not found usually means the wrong region.

gcloud compute interconnects attachments partner create (write, billable once active)

Purpose. Creates a Partner VLAN attachment in a region and returns the pairing key for the service provider.

gcloud compute routers create rtr-ic-REGION \
  --network=hub-vpc --region=REGION --asn=16550 --project=PROJECT_ID

gcloud compute interconnects attachments partner create ic-att-1 \
  --region=REGION \
  --router=rtr-ic-REGION \
  --edge-availability-domain=availability-domain-1 \
  --project=PROJECT_ID

Flags. The router for a Partner attachment must use ASN 16550. --edge-availability-domain places this attachment in a failure domain; create the second attachment in availability-domain-2. Cost. The attachment is metered after activation and the circuit comes from the provider. Do not run it in a lab without a plan. Check gcloud compute interconnects attachments partner create --help for additional flags in your SDK version.

gcloud compute interconnects attachments dedicated create (write, billable)

Purpose. Creates a VLAN attachment on a Dedicated Interconnect you already have.

gcloud compute interconnects attachments dedicated create ic-att-ded-1 \
  --region=REGION \
  --router=rtr-hub \
  --interconnect=INTERCONNECT_NAME \
  --bandwidth=BANDWIDTH \
  --vlan=VLAN_ID \
  --project=PROJECT_ID

Flags. --interconnect names the physical link; --bandwidth and --vlan are required choices that you take from your design (see --help for the accepted values). After creation, read the values with attachments describe and configure your router.

Production use. Keep Interconnect objects in a dedicated connectivity project, managed in Terraform by the network team. Export expectedOutages and attachment state to monitoring, and subscribe the network team to the maintenance notifications for the facility.

Lab 4: inspect and plan an Interconnect design (about 10 minutes, free)

Goal. Run the read-only Interconnect commands, identify what would be needed for each topology, and write a build plan. This lab does not order a circuit and does not create attachments, because they are billable and need a provider or a facility.

Prerequisites. A sandbox project, the Compute Engine API enabled, and roles/compute.networkViewer or higher. An organization is not required. IDs in the expected output are illustrative.

  1. Set the project: gcloud config set project PROJECT_ID.
  2. List locations and pick two in different metros: gcloud compute interconnects locations list --format="table(name,city,continent)".
  3. List Interconnects and attachments: expect Listed 0 items. in a sandbox.
  4. Write the topology you need (99.9% or 99.99%) and list the objects it requires: number of Interconnects or partner connections, number of attachments, edge availability domains used, number of Cloud Routers, and regions.
  5. Write the Cloud Router ASN for each router (16550 for Partner) and the BGP link-local ranges the attachments will allocate.
  6. Write the encryption decision (none, MACsec, or HA VPN over Interconnect) with the reason.
  7. Write the backup: the HA VPN from Module 3 with a higher MED, and the failover test you will run before go-live.

Verification. Run gcloud compute interconnects attachments list --format="value(name)" | wc -l. A sandbox with no Interconnect prints 0, which confirms that nothing billable exists.

0

Expected result. A one-page build plan with an object count per topology, a risk list (provider lead time, cross-connect, ASN conflicts) and the encryption and backup decisions. A reviewer should be able to order the circuits from the plan.

Cost. Free; all commands are read-only.

Cleanup. None. If you created a Cloud Router from Module 2 for planning, you can keep it for Module 5, which uses a hub that connects spokes.

Lab 4b (optional): compare two topologies

Draw the 99.9% and 99.99% topologies for your own sites as a table of objects (circuits, attachments, routers, regions, domains). Count the failure that each topology survives and the objects you must monitor. The difference in object count is a reasonable estimate of the extra effort.

Typical cases

  • Single circuit, planned maintenance. A company ran one Dedicated Interconnect with an HA VPN backup at low bandwidth. A scheduled maintenance on the facility took the circuit down for hours, and the VPN could not carry the replication traffic. The fix was a second circuit in a different edge availability domain and a higher VPN capacity for the critical flows.
  • Provider handover delay. A Partner attachment sat in PENDING_PARTNER for weeks because the provider order was not placed. Pairing keys belong in the project plan with an owner, so the order is tracked like any other lead-time item.
  • Encryption added late. A bank moved to Interconnect and then added HA VPN over Interconnect for regulated subnets after its audit. Bandwidth for those subnets dropped to the tunnel limits, and the team had to scale the number of tunnels. Planning encryption before ordering the circuits avoids re-sizing.

Practices

  • Choose the topology from the availability requirement, and write the requirement in the design record.
  • Use global dynamic routing and a Cloud Router per region for multi-region workloads.
  • Keep an HA VPN as a tested backup with a higher MED.
  • Subscribe to maintenance notifications for the facility, and monitor attachment state and BGP.
  • Keep ownership clear: the connectivity project is owned by the network team, with changes through code review.
  • Label attachments and routers so cost is attributed to the business unit that uses the bandwidth.
Security note. A private circuit still extends your internal network into Google Cloud. Use firewall policies that default to deny from on-premises ranges, restrict who can create attachments (roles/compute.networkAdmin), log changes through Cloud Audit Logs, and decide on MACsec or IPsec explicitly. For regulated data, combine private connectivity with VPC Service Controls (Hour 3) so private access does not become a data exfiltration path.

Symptoms and first checks

SymptomLikely causeFirst check
Attachment stays PENDING_PARTNERThe provider has not received the pairing key or has not finished its sideattachments describe for the state and key; confirm the order with the provider
Attachment is PENDING_CUSTOMER but nothing worksYou have not activated itEnable the attachment with attachments partner update and the activation flag from --help
Dedicated Interconnect has no linkCross-connect not completed, light level out of range, or LACP downinterconnects get-diagnostics and the facility provider's cross-connect ticket
Attachment active, BGP not EstablishedWrong VLAN ID, link-local IPs or ASN on your routerattachments describe for vlanTag8021q and the IPs; compare with your router
Partner attachment creation fails on the routerCloud Router ASN is not 16550routers describe and recreate the router with the correct ASN
Traffic only works from one regionRegional dynamic routingSet the VPC to global dynamic routing and plan a Cloud Router per region
Failover to the backup VPN did not happenInterconnect routes have equal or worse MED than the VPN, or BGP did not dropCompare MED values; consider BFD for faster detection if supported

Triage order

  1. Physical or provider layer: circuit state and diagnostics, or the provider's ticket.
  2. Attachment state (and your activation step).
  3. VLAN ID, link-local IPs and ASN on both sides.
  4. BGP state and prefixes (routers get-status).
  5. VPC routing mode, routes, then firewall policies.
or score ≥ 70% on the quiz

Module 5 · Network Connectivity Center

28–36 · Hubs and spokes that replace a mesh of peerings and tunnels with one managed topology
HubSpokesVPC spokeHybrid spoke8 min
Learning objectives
  • Describe a Network Connectivity Center hub and the spoke types (VPC, VPN tunnels, VLAN attachments, router appliance) that attach to it.
  • Decide when a hub-and-spoke design is better than VPC Network Peering, a full mesh of tunnels, or a single Shared VPC.
  • Create a hub and a VPC spoke with gcloud network-connectivity, and check the state of both before you rely on them.

The short answer

Network Connectivity Center (网络连接中心, NCC) is a managed hub-and-spoke service. You create a hub (枢纽) and attach spokes (辐条): VPC networks, HA VPN tunnels, Cloud Interconnect VLAN attachments, or router appliances. The hub exchanges routes between the spokes, so every attached network can reach every other one without a connection per pair.

What: the pieces

  • Hub. A global resource inside a project. Spokes from several projects can attach to one hub, so the hub project is usually a shared network project owned by the platform team.
  • VPC spoke. Attaches a VPC network. Its subnet routes are exported to the hub, and routes from other spokes are imported. A Shared VPC host project is attached once, and all service projects follow.
  • Hybrid spokes. Either VPN tunnels (HA VPN) or VLAN attachments (Cloud Interconnect). They bring on-premises routes learned by Cloud Router into the hub.
  • Router appliance spoke. A virtual machine with routing software (for example an SD-WAN or firewall vendor image) that peers with a Cloud Router. Use it when you need a function the hub itself does not provide.
  • Site-to-site data transfer. A setting on a hybrid spoke that lets traffic flow between two on-premises sites over Google's network. Without it the spoke only connects on-premises to Google Cloud.

Why: the mesh problem

A landing zone grows by networks: one per environment, one per region, one per acquisition, plus several on-premises sites. Connecting every pair does not scale. VPC Network Peering is not transitive, so a peering between A and B and between B and C does not let A reach C. A full mesh of HA VPN tunnels multiplies gateways, secrets, BGP sessions and limits. A hub gives you one place where the topology is declared, one list of attachments to audit, and routes that propagate as spokes are added.

Networks to connectPairwise connections in a full meshAttachments to a hub
333
6156
126612
3043530

How it works internally

  1. You create the hub. It has no routes of its own yet.
  2. You attach a spoke. For a VPC spoke the hub reads the subnet routes of the VPC network. For a hybrid spoke it reads the dynamic routes that the Cloud Router learned from the peer.
  3. The hub builds a route table per routing domain and programs the routes into every other spoke, as imported routes in the VPC network. You see them with gcloud compute routes list and in the Cloud Router status.
  4. Packets still go from VM to VM on Google's network, using the normal VPC data path. The hub is a control-plane service, so it adds no hop of its own.
  5. Your firewall rules, hierarchical firewall policies and Shared VPC permissions still decide whether a packet is allowed. Connectivity is not access.

When to use it

  • Several VPC networks must reach each other and on-premises, and the number of pairs is growing (production, non-production, shared services, a hub project for DNS and security tools).
  • You want on-premises sites to share one set of Interconnect attachments or VPN tunnels across many VPC networks.
  • You want a transit path between two on-premises sites over Google's backbone, with site-to-site data transfer.
  • You need a vendor appliance in the path and want to attach it as a spoke.

Do not reach for it when a single Shared VPC already contains all workloads. One VPC network needs no hub, and the best first design is often the simplest one.

What it is confused with

OptionTransitive?Scale and limitsBest for
VPC Network PeeringNoPer-network peering limit; each pair is a separate resourceA few networks that must reach each other directly
Shared VPCNot applicable (one network)Many projects share one network and one IP planMany teams in one routing domain
Network Connectivity CenterYes, through the hubOne attachment per network; route exchange is managedMany networks and sites, or on-premises transit
Full mesh of HA VPN tunnelsOnly if you build itMany tunnels, secrets and BGP sessions to operateSmall, temporary connections
Cloud Router with a router applianceYes, you implement itYou operate the appliance, its HA and its licencesWhen you need inspection or a vendor feature in the path

Common misunderstandings

The hub is not a firewall. A hub creates routes. It does not allow or deny traffic. You still need firewall policies on every VPC network, and you should assume that attaching a network makes it reachable, so review the rules first.
Overlapping ranges are not translated. The hub does not do NAT. If two spokes use 10.0.0.0/16, you must renumber or use a router appliance that translates.
Check limits and the available spoke options. The supported spoke types, quotas and features change between releases, and some are in preview. Read the current "Network Connectivity Center overview" before you design around a feature.
NCC hub hub-core · global VPC spoke: prod 10.20.0.0/16 VPC spoke: shared services 10.10.0.0/16 VPC spoke: non-prod 10.30.0.0/16 Hybrid spoke: HA VPN Cloud Router · site A Hybrid spoke: Interconnect VLAN attachments · site B Router appliance spoke VM with routing software Routes are exchanged through the hub · firewalls still decide what is allowed

Figure 1. One hub, three VPC spokes above and three hybrid or appliance spokes below. Each network needs one attachment, not one connection per partner.

How many networks must connect? One routing domain Shared VPC, no hub 2 to 4 networks VPC Network Peering Many networks or sites Network Connectivity Center Add a router appliance spoke only when you need inspection, NAT or a vendor feature. Check overlapping ranges and quotas before choosing any option.

Figure 2. A decision shortcut. The hub is not always the answer: a single Shared VPC or a few peerings can be simpler.

Look at where the lines end in Figure 1: every spoke connects to the hub, never to another spoke. That is why adding a seventh network adds one line, not six.

The animation follows a hub being built: the hub is created, two VPC spokes attach and share their subnet routes, then an on-premises route learned by Cloud Router appears in a VPC spoke. Each step is an API call or a route exchange, and the log is the line you would see in the operation or the router status.

The commands below use the gcloud network-connectivity group. Run gcloud network-connectivity --help and check the flags in your SDK version, because spoke subcommands vary with the release channel. The hub itself is global.

gcloud network-connectivity hubs create (write, no direct charge for the hub)

Purpose. Creates a hub in the network project. Costs: creating the hub is a metadata operation. Data transfer, VPN tunnels and Interconnect attached to spokes are billed separately, and some spoke types have their own charges, so read the current pricing page before you attach hybrid spokes.

gcloud network-connectivity hubs create hub-core \
  --project=PROJECT_ID \
  --description="Core production hub"

Flags. The hub name is positional. --description is free text. Add labels with --labels=env=prod if your SDK version supports it (check --help).

Create request issued for: [hub-core]
Waiting for operation [projects/PROJECT_ID/locations/global/operations/operation-1700000000000-abc] to complete...done.
Created hub [hub-core].

Common errors. PERMISSION_DENIED needs roles/networkconnectivity.hubAdmin (or an equivalent custom role). SERVICE_DISABLED means the Network Connectivity API is off: gcloud services enable networkconnectivity.googleapis.com --project=PROJECT_ID.

gcloud network-connectivity spokes linked-vpc-network create (write)

Purpose. Attaches a VPC network to the hub as a VPC spoke. The spoke is global.

gcloud network-connectivity spokes linked-vpc-network create spoke-prod \
  --hub=hub-core \
  --vpc-network=projects/PROJECT_ID/global/networks/vpc-prod \
  --global \
  --project=PROJECT_ID

Flags. --hub names the hub (use the full resource name when the hub is in another project). --vpc-network is the full network URI. --global places the spoke in the global location. Optional flags such as --exclude-export-ranges exist for ranges that must not be exported. Check gcloud network-connectivity spokes linked-vpc-network create --help.

Create request issued for: [spoke-prod]
Waiting for operation [projects/PROJECT_ID/locations/global/operations/operation-1700000000001-def] to complete...done.
Created spoke [spoke-prod].

gcloud network-connectivity spokes linked-vpn-tunnels create (write)

Purpose. Attaches HA VPN tunnels as a hybrid spoke. The tunnels must exist and use dynamic routing. The spoke is regional and should include both tunnels of an HA pair.

gcloud network-connectivity spokes linked-vpn-tunnels create spoke-hq-vpn \
  --hub=hub-core \
  --vpn-tunnels=tun-hq-0,tun-hq-1 \
  --region=REGION \
  --site-to-site-data-transfer \
  --project=PROJECT_ID

Flags. --vpn-tunnels is a comma separated list. --site-to-site-data-transfer lets traffic move between this site and other hybrid spokes on the hub. Leave it off when the site must reach Google Cloud only.

Cost. VPN tunnels are billed while they exist. Creating a spoke does not create tunnels but it does make the on-premises routes visible to every other spoke. Review the route table first.

gcloud network-connectivity hubs describe and spokes list (read, free)

Purpose. Check what is attached and in which state.

gcloud network-connectivity hubs describe hub-core --project=PROJECT_ID
gcloud network-connectivity spokes list --hub=hub-core --project=PROJECT_ID
name: projects/PROJECT_ID/locations/global/hubs/hub-core
state: ACTIVE
description: Core production hub
uniqueId: 11111111-2222-3333-4444-555555555555

NAME        HUB       STATE   TYPE
spoke-prod  hub-core  ACTIVE  VPC_NETWORK

IDs and column layout in the expected output are illustrative. Use --format="yaml" for the full record.

gcloud compute routes list (read, free)

Purpose. Verify that routes from other spokes appear in a VPC network as a result of the hub.

gcloud compute routes list --project=PROJECT_ID \
  --filter="network:vpc-prod" \
  --format="table(name,destRange,nextHopHub,priority)"

Common errors. If no route appears, the spoke may still be CREATING, the peer spoke may have rejected the range, or the range may overlap an existing subnet. The nextHopHub field may differ in your SDK version, so use --format=yaml to see the field names.

gcloud network-connectivity hubs delete and spoke deletion (write)

Purpose. Deleting a hub needs all spokes removed first. Deleting a spoke removes its routes from every other spoke immediately, so it is an outage for traffic that used those routes.

gcloud network-connectivity spokes delete spoke-prod --global --project=PROJECT_ID
gcloud network-connectivity hubs delete hub-core --project=PROJECT_ID
Production use. Put the hub in the network project, give only the platform team roles/networkconnectivity.hubAdmin, and let project teams ask for spokes through a pull request to the Terraform repository. Treat each spoke as a change to the whole company's routing.

Lab: build a hub with two VPC spokes (about 10 minutes of reading, 15 minutes with the console)

Goal. Create two small custom-mode VPC networks, attach them to a hub, and prove that the routes were exchanged. This lab is a design exercise. Module 7 contains the main hands-on lab for this hour.

Prerequisites. A sandbox project with billing linked and a budget set (Hour 1). The Network Connectivity API can be enabled. You hold roles/compute.networkAdmin and roles/networkconnectivity.hubAdmin on the sandbox project. No real secrets are used. IDs in the expected output are illustrative.

  1. Enable the API: gcloud services enable networkconnectivity.googleapis.com compute.googleapis.com --project=PROJECT_ID.
  2. Create two networks with non-overlapping ranges:
    gcloud compute networks create vpc-a --subnet-mode=custom --project=PROJECT_ID
    gcloud compute networks create vpc-b --subnet-mode=custom --project=PROJECT_ID
    gcloud compute networks subnets create sub-a --network=vpc-a --region=REGION --range=10.60.0.0/24 --project=PROJECT_ID
    gcloud compute networks subnets create sub-b --network=vpc-b --region=REGION --range=10.61.0.0/24 --project=PROJECT_ID
  3. Create the hub: gcloud network-connectivity hubs create hub-lab --project=PROJECT_ID.
  4. Attach both networks as VPC spokes using the command from the previous tab, once for vpc-a and once for vpc-b.
  5. Verify the spokes. gcloud network-connectivity spokes list --hub=hub-lab --project=PROJECT_ID. Both must show ACTIVE.
  6. Verify the routes. List the routes of vpc-a and look for 10.61.0.0/24. Do the reverse check in vpc-b. Routes can take a minute to appear.
  7. Write one sentence for each of these questions: what firewall rule would be needed for a VM in sub-a to ping a VM in sub-b? Which ranges would collide if you attached a third network that uses 10.60.0.0/16?

Expected result. Two ACTIVE spokes and a route to the other network's subnet in each VPC. Creating networks, subnets, hubs and spokes is metadata only, so the lab has no compute cost, provided you do not create VMs.

Cost. Free for the resources above. If you add test VMs for a ping test, they bill while they run: use the smallest machine type and delete them at the end. Budgets send alerts and do not cap spend.

Cleanup (in this order).

gcloud network-connectivity spokes delete spoke-a --global --project=PROJECT_ID --quiet
gcloud network-connectivity spokes delete spoke-b --global --project=PROJECT_ID --quiet
gcloud network-connectivity hubs delete hub-lab --project=PROJECT_ID --quiet
gcloud compute networks subnets delete sub-a sub-b --region=REGION --project=PROJECT_ID --quiet
gcloud compute networks delete vpc-a vpc-b --project=PROJECT_ID --quiet

If a command fails with a dependency message, delete the dependent resource first. Check gcloud network-connectivity spokes list returns an empty list before you delete the hub.

Real cases

  • Peering sprawl. A platform team had 14 VPC networks with 40 peerings, and every new project needed a ticket. Moving to one hub with 14 VPC spokes cut the ticket to one attachment, but the team had to finish the IP plan first, because three networks used the same 10.0.0.0/16 range and could not be attached until they were renumbered.
  • One set of Interconnects for many VPCs. A company had Dedicated Interconnect in two metros and wanted production and non-production in separate VPC networks. Attaching the VLAN attachments as a hybrid spoke gave both environments on-premises access without buying extra circuits. A firewall policy on each VPC network kept non-production from reaching on-premises production databases.
  • Branch-to-branch transit. Two data centres needed to talk, and the old WAN link was due for renewal. Using HA VPN spokes with site-to-site data transfer let the sites use Google's backbone as a transit path. The team documented that this is a routing feature and not a managed security service, and added monitoring on both Cloud Routers.

Practices

  • One hub per routing domain, and one owner. Do not mix production and non-production routes in the same hub unless you filter them.
  • Decide the IP plan before the hub. Record every range in one table (Hour 4, Module 3) and check for overlaps in the pull request.
  • Use separate hubs or route filters when a network must not learn on-premises routes.
  • Alert on spoke state, Cloud Router session status and tunnel state. A spoke that goes inactive removes routes silently.
  • Keep hub, spokes and Cloud Routers in Terraform, reviewed in the same repository as the network layer.
Security note. A hub makes lateral movement easier. Once two networks are connected, a compromised VM can try to reach everything the firewall allows. Use hierarchical firewall policies with default deny between environments, and use VPC Service Controls and IAM for data access: they are not replaced by network reachability.

Symptoms and first checks

SymptomLikely causeFirst check
Spoke stays CREATING or becomes INACTIVEAPI not enabled, missing permission on the linked resource, or a rejected overlapgcloud network-connectivity spokes describe SPOKE --global and read reasons
Routes from the other spoke are missingSpoke not ACTIVE, export ranges excluded, or overlap with a local subnetgcloud compute routes list --filter="network:NETWORK"
Routes exist but ping failsFirewall rules block the traffic, or the return path is missingFirewall Insights or a Connectivity Test (Module 8)
On-premises route not seen in a VPC spokeHybrid spoke missing, BGP session down, or the route is not advertised by the peergcloud compute routers get-status ROUTER --region=REGION
Two on-premises sites cannot reach each otherSite-to-site data transfer is off, or the peers do not advertise each other's rangesgcloud network-connectivity spokes describe and check the flag
Cannot delete the hubSpokes still attachedgcloud network-connectivity spokes list --hub=HUB
Attach fails with a permission error across projectsThe hub admin lacks a role on the project that owns the networkCheck the role on the linked resource's project, then retry

Triage order

  1. Is the spoke ACTIVE? Read the state and reasons.
  2. Does the destination prefix appear in the source network's route table?
  3. Is there an overlap between any two ranges?
  4. Does the firewall allow the packet in both directions?
  5. For hybrid spokes, is the tunnel or attachment up and the BGP session established?

Product pages change, so the links below are search pages and official documentation. Check the date of any video against the current documentation.

Official reading: Network Connectivity Center overview · VPC Network Peering.

or score ≥ 70% on the quiz

Module 6 · Ingress and Cloud Armor

36–43 · Controlled entry for internet traffic with an external Application Load Balancer and Cloud Armor policies
Load balancerCloud ArmorWAFPreview mode7 min
Learning objectives
  • Explain the path of an internet request through the external Application Load Balancer, and where a Cloud Armor security policy is evaluated.
  • Write Cloud Armor rules (IP allow and deny, geography, preconfigured WAF expressions) and test them in preview mode before enforcing them.
  • Attach a security policy to a backend service and read the logs that show which rule matched.

The short answer

Ingress (入口流量) is how external traffic enters your landing zone. For HTTP and HTTPS, the usual pattern is a global external Application Load Balancer (外部应用负载均衡器) with one public address, TLS certificates, URL maps and a Cloud Armor (Cloud Armor,网页应用防火墙) security policy attached to each backend service. Backends have no public address of their own.

What: the pieces on the request path

  • Forwarding rule and IP address. The global anycast address that clients connect to, for a given port and protocol.
  • Target proxy and certificates. The HTTPS proxy terminates TLS. Use Google-managed certificates or Certificate Manager so nobody copies key files.
  • URL map. Routes host names and paths to backend services.
  • Backend service. A group of backends (instance groups, network endpoint groups, serverless NEGs for Cloud Run) with health checks and a security policy.
  • Cloud Armor security policy. Ordered rules evaluated at the Google edge, before the request reaches a backend.
  • Logging. The load balancer logs each request and records which security policy rule matched.

Why: protect the entrance once, centrally

Every internet-facing application needs rate limiting, geography and IP controls, protection against common web attacks, and defence against volumetric traffic. Without a shared pattern each team builds a different version, or none. A landing zone provides a standard ingress project, a baseline policy and a way to roll out rules safely.

How the Cloud Armor policy works internally

  1. A rule has a priority (0 to 2147483646), a match (a basic IP range list or a Common Expression Language expression) and an action (allow, deny(403), deny(404), deny(502), redirect, throttle, rate_based_ban).
  2. Rules are evaluated from the lowest priority number up. The first rule that matches decides the result, and no later rule is evaluated.
  3. The default rule has priority 2147483647 and matches everything. Its action (allow or deny) is the policy's stance. A deny-by-default policy is stricter and needs explicit allow rules.
  4. A rule in preview mode is evaluated and logged, but its action is not enforced. The request continues down the list as if the rule had not matched, so the first enforced match still decides.
  5. Expressions can use origin.ip, origin.region_code, request headers and paths, and preconfigured WAF functions such as evaluatePreconfiguredWaf('xss-v33-stable'). Preconfigured rule names and versions change, so list them in the current documentation or with gcloud compute security-policies list-preconfigured-expression-sets.

When to use it

  • Any public web application or API behind an external Application Load Balancer.
  • Rate limiting login or search endpoints with throttle or rate_based_ban rules.
  • Blocking or allowing countries and IP ranges (for example only the corporate range for an admin path).
  • Adding a virtual patch for a known vulnerability while the application is fixed.

It is the wrong tool for private services that only on-premises users call. For those, use an internal Application Load Balancer and firewall policies.

What it is confused with

ControlLayer and scopeUsed for
VPC firewall rules and firewall policiesLayers 3 and 4, on VM network interfacesWhich sources may reach a VM or port
Cloud ArmorLayer 7 (and edge layer 3/4 defence) at the load balancerHTTP attacks, IP and geography, rate limits
Identity-Aware ProxyLayer 7 authentication in front of an applicationWho is allowed to use an internal web app
VPC Service ControlsAPI perimeter around Google servicesData exfiltration from Google APIs
Cloud NATEgress translationOutbound internet access for private VMs

Common misunderstandings

"We have Cloud Armor, so the VM is safe." A policy on the backend service protects the load balancer path only. A VM that still has an external IP and an open firewall rule can be reached directly. Remove the external address (Organization Policy constraints/compute.vmExternalIpAccess) and allow only Google front end and health check ranges.
"Preview mode is the same as enforcing." It is not. A rule in preview mode never blocks a request. A common mistake is to leave a rule in preview for months and believe it is protecting the site.
"Deny by default breaks everything." It is a valid design, but only with a complete allow list that you can test. Start with an allow-by-default policy plus targeted deny rules, and move to deny by default for admin paths first.
Internet user 203.0.113.50 Anycast IP + TLS forwarding rule · proxy Cloud Armor policy ordered rules · WAF URL map host and path routing Backend service health checks · no public IP Cloud Run (NEG) MIG (VMs) Storage bucket Evaluation happens at the Google edge, before the backend. Backends allow only Google front end and health check ranges. Logs: the load balancer records the matched rule and the policy name for every request.

Figure 1. Request path. The policy sits between the proxy and the backend service, so rejected requests never consume backend capacity.

1000 allow origin.ip in corporate range (admin path) 2000 deny(403) evaluatePreconfiguredWaf('sqli-v33-stable') 3000 deny(403) PREVIEW origin.region_code == 'XX' (logs only) 4000 throttle login path, 100 requests per minute per IP 2147483647 default allow Lowest number first; the first enforced match decides; the default rule is last.

Figure 2. A policy as an ordered list. Notice the preview rule at 3000: it is evaluated and logged, but the request continues to the next rule.

In Figure 1, follow the line from the user to the backend and notice that the security policy is a step on the path, not a separate network. In Figure 2, note the gaps between priorities: they leave room for new rules.

The animation shows one request: it arrives at the anycast address, is evaluated by the policy (a preview rule logs but does not block), is forwarded to a healthy backend, and writes a log entry with the policy name. The log lines are written in the style of the load balancer request log.

The commands below use the gcloud compute security-policies group and gcloud compute backend-services. Creating a policy is a metadata operation, but Cloud Armor is billed per policy and per rule and per request, and the load balancer itself is billed while it exists. Check the current Cloud Armor pricing page before you create a policy in a shared project. Check gcloud compute security-policies --help for the flags in your SDK version.

gcloud compute security-policies create (write, billed while the policy exists)

Purpose. Creates an empty policy with the default rule.

gcloud compute security-policies create pol-web \
  --description="Baseline policy for the public web tier" \
  --project=PROJECT_ID

Flags. The name is positional. --description is free text. Optional flags such as --type and --network exist for other policy types (for example edge or regional policies), so check --help.

Created [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/securityPolicies/pol-web].
NAME     DESCRIPTION
pol-web  Baseline policy for the public web tier

gcloud compute security-policies rules create (write)

Purpose. Adds a rule. Always add a new rule with --preview first.

gcloud compute security-policies rules create 1000 \
  --security-policy=pol-web \
  --description="Allow the corporate range to /admin" \
  --src-ip-ranges="198.51.100.0/24" \
  --action=allow \
  --project=PROJECT_ID

gcloud compute security-policies rules create 2000 \
  --security-policy=pol-web \
  --description="Block SQL injection signatures" \
  --expression="evaluatePreconfiguredWaf('sqli-v33-stable')" \
  --action=deny-403 \
  --preview \
  --project=PROJECT_ID

Flags. The priority is positional. --src-ip-ranges is the basic match. --expression is a CEL expression for advanced matching. --action is allow, deny-403, deny-404, deny-502, redirect, throttle or rate-based-ban. --preview logs without enforcing. The WAF rule name and version (sqli-v33-stable) must be one that the current documentation lists.

Created [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/securityPolicies/pol-web].

Common errors. Invalid value for field 'resource.rules[0].match.expr' means the expression is not valid CEL or the preconfigured name does not exist. Priority already exists means another rule uses that number. Use rules update to edit it.

gcloud compute security-policies rules update --no-preview (write)

Purpose. Enforces a rule that you have tested in preview.

gcloud compute security-policies rules update 2000 \
  --security-policy=pol-web \
  --no-preview \
  --project=PROJECT_ID

gcloud compute backend-services update --security-policy (write)

Purpose. Attaches the policy to a global backend service behind an external Application Load Balancer. Until you attach it, the policy does nothing.

gcloud compute backend-services update be-web \
  --security-policy=pol-web \
  --global \
  --project=PROJECT_ID
Updated [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/backendServices/be-web].

gcloud compute security-policies describe and list (read, free)

gcloud compute security-policies list --project=PROJECT_ID
gcloud compute security-policies describe pol-web --project=PROJECT_ID \
  --format="yaml(name,rules[].priority,rules[].action,rules[].preview)"
name: pol-web
rules:
- action: allow
  preview: false
  priority: 1000
- action: deny(403)
  preview: true
  priority: 2000
- action: allow
  preview: false
  priority: 2147483647

IDs and output layout are illustrative.

gcloud logging read for matched rules (read, free)

Purpose. See what the policy would have done. Preview results appear in the previewSecurityPolicy field of the request log.

gcloud logging read \
  'resource.type="http_load_balancer" AND jsonPayload.previewSecurityPolicy.outcome="DENY"' \
  --project=PROJECT_ID --limit=5 \
  --format="table(timestamp,httpRequest.requestUrl,jsonPayload.previewSecurityPolicy.name,jsonPayload.previewSecurityPolicy.priority)"

Field names in the log entry can differ by policy type and release, so first run the command with --format=json --limit=1 and read the actual structure.

Production use. Keep policies in Terraform, apply new rules in preview for at least a few days of normal traffic, review the log, and then enforce. Treat the rule list as code: every rule has a description that names the owner and the reason.

Lab: write and test a Cloud Armor policy (read-only if you have no load balancer)

Goal. Create a policy, add one allow rule and one preview rule, and verify the rule list. Attaching the policy to a live load balancer is an optional step that creates billable resources.

Prerequisites. A sandbox project with billing linked and a budget set. roles/compute.securityAdmin on the project. If you want the optional step, a sandbox load balancer with a global backend service (a Cloud Run service behind a serverless NEG is the cheapest). IDs in the expected output are illustrative.

  1. Enable the Compute API: gcloud services enable compute.googleapis.com --project=PROJECT_ID.
  2. Create the policy with the command from the previous tab.
  3. Add rule 1000 (allow your public IP range, for example the range of your office or lab; use a documentation range if you only want to test the syntax).
  4. Add rule 2000 in preview mode with an expression that is safe to test, for example --expression="request.path.matches('/admin.*')" and --action=deny-403.
  5. Verify. Run gcloud compute security-policies describe pol-web --format="yaml(rules)". Rule 2000 must show preview: true and the default rule must be last.
  6. Optional (billable). Attach the policy to a sandbox backend service with gcloud compute backend-services update ... --security-policy=pol-web --global. Send a request to /admin and read the preview result in Logs Explorer or with gcloud logging read. The request must still succeed because the rule is in preview.
  7. Enforce the rule with rules update 2000 --no-preview, repeat the request, and confirm that the response is 403. Then set the rule back to preview or delete it.

Expected result. A policy with a documented allow rule, a preview rule, and the default rule. With the optional step, a log entry that names pol-web and the rule priority, and a 403 after enforcement.

Cost. Creating and editing the policy is low (a policy and its rules are billed while they exist). A load balancer and backends are billed while they run. Budgets send alerts and do not cap spend.

Cleanup. Detach the policy first, then delete it.

gcloud compute backend-services update be-web --security-policy="" --global --project=PROJECT_ID
gcloud compute security-policies delete pol-web --project=PROJECT_ID --quiet

If you created a load balancer for the optional step, delete in this order: forwarding rule, target proxy, URL map, backend service, serverless NEG, certificate, reserved address.

Real cases

  • Login abuse. A retail application saw credential-stuffing on its login path. A throttle rule on the login path (per client IP) and a preview-only preconfigured rule for automation signatures reduced the load within an hour. The team kept the signature rule in preview until they confirmed that a partner integration did not match it.
  • Admin path exposed. An internal admin page was reachable from the internet because it shared a host name with the public site. A priority 1000 allow rule for the corporate range and a deny rule for /admin for everyone else moved the risk out of the application. A second step moved the page behind Identity-Aware Proxy.
  • Bypass through a VM address. After a Cloud Armor rollout, scans still reached a VM directly because a developer had added an external IP. An Organization Policy that denies external IPs (Hour 3) and firewall rules that allow only the Google front end ranges closed the gap.

Practices

  • One baseline policy per environment, owned by the platform team, plus a small, application-specific policy owned by the application team.
  • Number rules in steps of 1000 and write the owner, ticket and date in the description.
  • Roll out every new rule in preview mode first, read the logs, then enforce. Record the preview window in the change ticket.
  • Send load balancer logs to a log bucket with a retention period that meets your investigation needs, and alert on spikes of denied requests.
  • Use Google-managed certificates or Certificate Manager. Do not store private keys in repositories.
Security note. Rules that match on a country code or an IP range are not authentication. Attackers use proxies and VPNs. Combine Cloud Armor with application authentication, Identity-Aware Proxy for internal tools, and rate limits. Also remember that logging of request headers can capture personal data: apply your privacy rules to the log bucket.

Symptoms and first checks

SymptomLikely causeFirst check
Legitimate users get 403 after a rule changeA WAF signature or a deny rule enforced without previewRead the request log for the matched priority, then set the rule to preview
A rule never matchesLower-priority number rule matches first, rule left in preview, or a wrong expressionsecurity-policies describe and compare priorities and the preview flag
Policy is created but nothing is blockedNot attached to the backend servicegcloud compute backend-services describe be-web --global --format="value(securityPolicy)"
Attackers reach the VM directlyVM has an external IP or the firewall allows 0.0.0.0/0gcloud compute instances list --format="table(name,networkInterfaces[0].accessConfigs[0].natIP)"
Real client IP is wrong in rulesRules use the proxy address or X-Forwarded-For is misreadUse origin.ip in expressions and check the log's remoteIp
502 errors from the load balancerUnhealthy backends or health check blocked by firewallgcloud compute backend-services get-health be-web --global
Rule creation fails with an invalid expressionUnknown preconfigured rule name or a typo in CELList expression sets, then test the expression in the console editor

Triage order

  1. Is the request reaching the load balancer? Check the load balancer request logs.
  2. Which rule matched, and was it in preview? Read the log fields.
  3. Is the backend healthy? Check health and the firewall rules for Google ranges.
  4. Is there a direct path that bypasses the load balancer?
  5. Roll back the last rule change to preview mode before you investigate further.
or score ≥ 70% on the quiz

Module 7 · Lab: Cloud Router and BGP configuration

43–53 · Build a lab VPC and Cloud Router, read its status, change route advertisements, and optionally bring up HA VPN with BGP
LabCloud RouterBGPOptional HA VPN10 min
Learning objectives
  • Create a custom-mode VPC network, a subnet and a Cloud Router with a private ASN, and read the router's configuration and status.
  • Change the route advertisement mode and prove the effect with describe and get-status.
  • Optionally connect two lab VPC networks with HA VPN and BGP, verify the sessions, and clean everything up in the right order.

The short answer

This module is a lab, so the concepts tab is a short lab brief. You create a Cloud Router (云路由器) on a lab VPC, learn to read its status, and change what it advertises. The optional part adds HA VPN between two lab VPC networks, so that you can see a real BGP session reach Established. Module 2 explained the model, Module 3 the HA VPN design, and Module 8 uses the same commands for troubleshooting.

What you build

PartResourcesCost
A. RequiredCustom VPC vpc-lab, subnet sub-lab, Cloud Router rtr-lab (ASN 64514)Free for metadata-only resources (a Cloud Router has no hourly charge on its own)
B. RequiredAdvertisement mode change, get-status, route listFree (read and update of router configuration)
C. Optional, billableSecond VPC vpc-peer, two HA VPN gateways, up to four tunnels, two BGP sessions per directionBilled per tunnel per hour plus data transfer. Low for a one-hour lab, but not zero: delete everything before you leave

Why this lab

Most hybrid problems are BGP problems: a session that is not established, a prefix that is not advertised, or a route that is learned but not preferred. The commands you use in this lab are the same you use on a production incident. Doing them once on a quiet network makes the output familiar.

How BGP works in this lab

  1. Each Cloud Router has a private ASN. Both ends of a session use different ASNs, so it is external BGP (eBGP).
  2. Each tunnel has a Cloud Router interface with a link-local address in 169.254.0.0/16 (a /30 is typical) and a BGP peer that points at the address of the other end.
  3. When the IPsec tunnel is up, the routers exchange OPEN messages. The session goes through Idle, Connect, Active, OpenSent, OpenConfirm to Established.
  4. After Established, each router sends the prefixes it advertises. The other router installs them as dynamic routes with a priority derived from the MED and the base priority you set.

When to repeat this lab

  • When a new engineer joins the platform team.
  • When you change the advertisement design, for example a move from default to custom advertisements.
  • Before a change window for real HA VPN or Interconnect work, as a dry run of the commands.

Common misunderstandings

A Cloud Router is not a packet forwarder. It does not sit in the data path. If you delete it, the dynamic routes disappear and traffic that used them stops.
The BGP session needs a working tunnel or attachment. A router without an interface and a peer shows no bgpPeerStatus at all. That is normal in Part A.
The same ASN on both ends is a classic mistake. With external BGP, the peer ASN must differ from the local ASN, or the session is rejected.
vpc-lab · region REGION sub-lab 10.70.0.0/24 Cloud Router rtr-lab · AS 64514 HA VPN gateway gw-lab · if0, if1 vpc-peer · same region sub-peer 10.71.0.0/24 HA VPN gateway gw-peer · if0, if1 Cloud Router rtr-peer · AS 64515 tunnel 0 tunnel 1 BGP over link-local 169.254.x.x/30 inside each tunnel

Figure 1. Optional Part C. Two VPC networks in one project act as "Google Cloud" and "the other site". Parts A and B use only the left-hand side.

Idle Connect Active OpenSent OpenConfirm Established Stuck in Idle or Active: the tunnel is down, a firewall blocks TCP 179, or the peer address is wrong. Stuck in OpenSent or OpenConfirm: ASN or hold timer mismatch. Established with no routes: advertisement mode, a filter, or a peer that announces nothing. Module 8 turns these into a triage order.

Figure 2. The states you will see in get-status. The cause of a stuck session depends on which state it stops in.

In Figure 1 find the two Cloud Routers and the two lines between the gateways: those are the tunnels that carry the BGP sessions. In Figure 2 notice that most failures stop the session before Established.

The animation covers the router configuration and a session coming up: the objects are created, the peer sends OPEN, the session reaches Established, prefixes are exchanged, and a learned route is installed in the VPC network. The log lines match what get-status and the route list show.

These are the commands you will run in the lab, with their purpose, flags and a note on what can go wrong. Replace the uppercase placeholders. IDs in the expected output are illustrative. Check gcloud compute routers --help for the flags in your SDK version.

gcloud compute networks create and subnets create (write, free)

gcloud compute networks create vpc-lab \
  --subnet-mode=custom \
  --bgp-routing-mode=regional \
  --project=PROJECT_ID

gcloud compute networks subnets create sub-lab \
  --network=vpc-lab --region=REGION --range=10.70.0.0/24 \
  --project=PROJECT_ID

Flags. --subnet-mode=custom avoids the automatic subnets. --bgp-routing-mode is regional (learned routes only in the router's region) or global. --range must not overlap with any network you will connect later.

Created [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/vpc-lab].
NAME     SUBNET_MODE  BGP_ROUTING_MODE  IPV4_RANGE  GATEWAY_IPV4
vpc-lab  CUSTOM       REGIONAL

Created [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/subnetworks/sub-lab].
NAME     REGION  NETWORK  RANGE
sub-lab  REGION  vpc-lab  10.70.0.0/24

gcloud compute routers create (write, free)

Purpose. Creates the Cloud Router with a private ASN.

gcloud compute routers create rtr-lab \
  --network=vpc-lab \
  --region=REGION \
  --asn=64514 \
  --project=PROJECT_ID
Creating router [rtr-lab]...done.
NAME     REGION  NETWORK
rtr-lab  REGION  vpc-lab

Common errors. The resource 'projects/.../networks/vpc-lab' was not found means a typo in the network name or the wrong project. Invalid value for field 'resource.bgp.asn' means the ASN is outside the allowed ranges.

gcloud compute routers describe (read, free)

gcloud compute routers describe rtr-lab --region=REGION --project=PROJECT_ID \
  --format="yaml(name,network,bgp)"
bgp:
  advertiseMode: DEFAULT
  asn: 64514
  keepaliveInterval: 20
name: rtr-lab
network: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/vpc-lab

gcloud compute routers update (write, free): custom advertisements

Purpose. Switches to custom advertisement mode, so you choose exactly which prefixes the peer learns.

gcloud compute routers update rtr-lab \
  --region=REGION \
  --advertisement-mode=custom \
  --set-advertisement-groups=all_subnets \
  --set-advertisement-ranges=192.168.200.0/24=lab-summary \
  --project=PROJECT_ID

Flags. --advertisement-mode is default or custom. --set-advertisement-groups=all_subnets keeps advertising every subnet. --set-advertisement-ranges adds ranges (the text after = is a description). Use --add-advertisement-ranges or --remove-advertisement-ranges for incremental changes.

Updating router [rtr-lab]...done.

Common error. If you set custom mode with no groups and no ranges, the router advertises nothing, and a live session loses its routes. Plan the change window accordingly.

gcloud compute routers get-status (read, free)

gcloud compute routers get-status rtr-lab --region=REGION --project=PROJECT_ID \
  --format="yaml(result.bgpPeerStatus,result.bestRoutes)"
result:
  bgpPeerStatus:
  - advertisedRoutes:
    - destRange: 10.70.0.0/24
    ipAddress: 169.254.10.1
    name: bgp0
    peerIpAddress: 169.254.10.2
    state: Established
    status: UP
    uptime: 4 minutes, 12 seconds
  bestRoutes:
  - destRange: 10.71.0.0/24
    nextHopIp: 169.254.10.2

In Part A the router has no peers, so bgpPeerStatus is empty. The output above is what Part C shows when the session is up.

gcloud compute routes list (read, free)

gcloud compute routes list --project=PROJECT_ID \
  --filter="network:vpc-lab" \
  --format="table(name,destRange,priority,nextHopIp,nextHopVpnTunnel.basename())"

Optional Part C commands (write, billable)

gcloud compute vpn-gateways create gw-lab --network=vpc-lab --region=REGION --project=PROJECT_ID
gcloud compute vpn-gateways create gw-peer --network=vpc-peer --region=REGION --project=PROJECT_ID

gcloud compute vpn-tunnels create tun-lab-0 \
  --vpn-gateway=gw-lab --peer-gcp-gateway=gw-peer \
  --interface=0 --region=REGION --router=rtr-lab \
  --ike-version=2 --shared-secret="$VPN_SECRET" --project=PROJECT_ID

Flags. --vpn-gateway is the local HA VPN gateway and --peer-gcp-gateway is the other HA VPN gateway when both are in Google Cloud. --interface is 0 or 1. --shared-secret must be identical on both tunnels of a pair. Never type a secret into a command history: generate it in a shell variable (see the lab tab) and discard it after use.

Production use. These are the commands of the first five minutes of every hybrid incident: routers describe for intent, routers get-status for the live state, routes list for the effect.

Lab: Cloud Router and BGP (10 minutes for Parts A and B, 15 more for optional Part C)

Goal. Create a Cloud Router, read its configuration and status, change the advertisement mode, and (optionally) bring up two BGP sessions over HA VPN between two lab VPC networks.

Prerequisites. A sandbox project, billing linked, a budget set (Hour 1). Roles roles/compute.networkAdmin on the project. Cloud Shell or a shell with gcloud authenticated. No real secrets: the optional VPN secret is generated at run time. IDs in the expected output are illustrative. Use one REGION for everything.

Cost warning for Part C. HA VPN tunnels and the associated resources are billed while they exist, and data transfer is billed separately. A one-hour test is usually low, but a forgotten lab accumulates charges for every hour. Budgets send alerts and do not cap spend. Do Part C only in a sandbox, set a reminder, and run the cleanup at the end of this tab.

Part A: create the router

  1. Set variables: export PROJECT_ID=your-sandbox-project REGION=your-region, and run gcloud config set project $PROJECT_ID.
  2. Enable the Compute API: gcloud services enable compute.googleapis.com.
  3. Create the network and subnet (commands tab).
  4. Verify. gcloud compute networks subnets list --filter="network:vpc-lab" must show 10.70.0.0/24.
  5. Create the Cloud Router rtr-lab with ASN 64514.
  6. Verify. gcloud compute routers describe rtr-lab --region=$REGION --format="value(bgp.asn,bgp.advertiseMode)" must print 64514 and DEFAULT.

Part B: advertisements and status

  1. Run gcloud compute routers get-status rtr-lab --region=$REGION. Expected: no peers yet, so no bgpPeerStatus.
  2. Switch to custom advertisements with --advertisement-mode=custom --set-advertisement-groups=all_subnets --set-advertisement-ranges=192.168.200.0/24=lab-summary.
  3. Verify. gcloud compute routers describe rtr-lab --region=$REGION --format="yaml(bgp.advertiseMode,bgp.advertisedGroups,bgp.advertisedIpRanges)" shows CUSTOM, the group ALL_SUBNETS and the extra range.
  4. Write down one risk of custom mode in a sentence (for example: a missing group means that a live session stops advertising subnets).
  5. Switch back: gcloud compute routers update rtr-lab --region=$REGION --advertisement-mode=default.

Part C (optional, billable): HA VPN with BGP between two VPC networks

  1. Create the second side: vpc-peer, subnet sub-peer 10.71.0.0/24, router rtr-peer with ASN 64515.
  2. Create the gateways: gcloud compute vpn-gateways create gw-lab --network=vpc-lab --region=$REGION and the same for gw-peer on vpc-peer.
  3. Generate a secret in memory only: VPN_SECRET=$(openssl rand -base64 24). Do not print it or save it to a file.
  4. Create the tunnels for both interfaces, in both directions: tun-lab-0 (interface 0) and tun-lab-1 (interface 1) on gw-lab, and tun-peer-0 and tun-peer-1 on gw-peer, each with --peer-gcp-gateway pointing at the other gateway, --router set to the local router and --shared-secret="$VPN_SECRET". The pair tun-lab-0 and tun-peer-0 must use the same secret, and so must the pair on interface 1.
  5. Add a router interface and a BGP peer for each tunnel on both routers. For tun-lab-0:
    gcloud compute routers add-interface rtr-lab \
      --interface-name=if-lab-0 --vpn-tunnel=tun-lab-0 \
      --ip-address=169.254.10.1 --mask-length=30 --region=$REGION
    
    gcloud compute routers add-bgp-peer rtr-lab \
      --peer-name=bgp-lab-0 --interface=if-lab-0 \
      --peer-ip-address=169.254.10.2 --peer-asn=64515 --region=$REGION
    On the peer side use 169.254.10.2 for the interface and 169.254.10.1 for the peer. Use 169.254.11.0/30 for the second tunnel. Check gcloud compute routers add-bgp-peer --help for the flags in your SDK version.
  6. Verify the tunnels. gcloud compute vpn-tunnels list --filter="region:$REGION" --format="table(name,status,detailedStatus)". Expect ESTABLISHED (it can take two to three minutes).
  7. Verify BGP. gcloud compute routers get-status rtr-lab --region=$REGION --format="value(result.bgpPeerStatus[].state)" must show Established for both peers.
  8. Verify routes. gcloud compute routes list --filter="network:vpc-lab AND destRange:10.71.0.0/24" shows a dynamic route to 10.71.0.0/24.
  9. Unset the secret: unset VPN_SECRET.

Expected result. Parts A and B: a router with ASN 64514, advertisements that change as you command them, and an empty peer list. Part C: two ESTABLISHED tunnels, two Established BGP sessions and a learned dynamic route for the other VPC.

Cost. Parts A and B are free. Part C is low if it runs for under an hour and is billable for as long as the gateways and tunnels exist.

Cleanup (in this order, Part C first if you ran it).

for R in rtr-lab rtr-peer; do
  for P in $(gcloud compute routers describe $R --region=$REGION --format="value(bgpPeers[].name)" | tr ';' ' '); do
    gcloud compute routers remove-bgp-peer $R --peer-name=$P --region=$REGION --quiet
  done
done
gcloud compute vpn-tunnels delete tun-lab-0 tun-lab-1 tun-peer-0 tun-peer-1 --region=$REGION --quiet
gcloud compute vpn-gateways delete gw-lab gw-peer --region=$REGION --quiet
gcloud compute routers delete rtr-lab rtr-peer --region=$REGION --quiet
gcloud compute networks subnets delete sub-lab sub-peer --region=$REGION --quiet
gcloud compute networks delete vpc-lab vpc-peer --quiet

Router interfaces are removed when the router is deleted. Finally, confirm that nothing remains: gcloud compute vpn-tunnels list and gcloud compute routers list must be empty for the lab names.

Real cases

  • Advertisement change that removed access. An engineer switched a router to custom mode to add a summary range, and forgot the all_subnets group. The peer lost every subnet route and an on-premises batch job failed. The runbook now requires describe before and after every router change, and the change is applied in Terraform with a plan review.
  • Same ASN on both sides. A branch router was configured with the same private ASN as the Cloud Router. The session never reached Established, and the error was visible only as a repeating notification on the branch device. A table of ASNs per site, in the network design document, prevented the repeat.
  • Forgotten lab tunnels. A team left a VPN test running over a long weekend and the budget alert was the first signal. A label such as ttl=2026-12-01 on lab resources, plus a scheduled cleanup job in a sandbox folder, removes this class of cost surprise.

Practices

  • Keep an ASN and link-local address register, one row per router, tunnel and site, in the repository next to the Terraform code.
  • Always read routers describe and routers get-status before and after a router change, and save the output in the change ticket.
  • Use custom advertisements for production routers so that you advertise summaries, not every subnet. Review them like firewall rules.
  • Monitor BGP session state and tunnel state with alerting policies (Hour 6).
  • Generate VPN secrets with a secret manager or Terraform, rotate them on a schedule, and keep them out of command history and repositories.
Security note. The shared secret protects the IPsec tunnel. A secret typed in a command is stored in shell history and in logs of CI systems. Use a variable populated from Secret Manager, a short-lived shell, and mask the value in CI logs.

Symptoms and first checks

SymptomLikely causeFirst check
routers create fails with an ASN errorASN outside the private rangesUse 64512 to 65534 or 4200000000 to 4294967294
get-status shows no bgpPeerStatusNo peers configured (normal in Part A)routers describe and check bgpPeers
Tunnel status is FIRST_HANDSHAKE or NO_INCOMING_PACKETSThe other tunnel does not exist yet, or secrets differCreate both sides and confirm the same secret per pair
BGP state is Active or IdleTunnel not established, wrong peer address, or filtered TCP 179vpn-tunnels describe then compare link-local addresses on both ends
Session Established but no learned routesPeer advertises nothing, or custom mode on the peer without rangesrouters describe on the peer
Route learned but traffic failsFirewall rules deny ingress from the other rangeConnectivity Tests (Module 8)
Cleanup fails with "resource is already being used"A BGP peer, interface or tunnel still refers to the objectDelete from the most dependent: peers, tunnels, gateways, routers, subnets, network

Triage order

  1. Tunnel state: vpn-tunnels describe.
  2. BGP session state: routers get-status.
  3. Advertised and learned routes: get-status and routes list.
  4. Firewall and policy: allow the other range on both ends.

Use these search pages and the official guides. Check the date of a video before you copy flags from it.

Official reading: Cloud Router overview · Cloud VPN overview.

or score ≥ 70% on the quiz

Module 8 · Troubleshooting connectivity

53–60 · A layered triage for hybrid networks: tunnel, BGP, routes, firewall, asymmetry and MTU
TriageTunnelBGPRoutesMTU7 min
Learning objectives
  • Apply a layered triage order to a hybrid connectivity incident, from the physical or IPsec layer up to firewalls and the application.
  • Read tunnel state, BGP session state and route tables with gcloud, and map each symptom to its likely cause.
  • Use a Connectivity Test and logs to prove where a packet stops, and recognise asymmetric routing and MTU problems.

The short answer

Hybrid connectivity fails in layers (分层排障). The order that saves the most time is: 1) the transport (IPsec tunnel or Interconnect attachment), 2) the BGP session, 3) the routes on both sides, 4) firewalls and policies, 5) asymmetry and MTU, and 6) the application. Do not start at the application, and do not change two layers at once.

What: the layers and their evidence

LayerWhat can breakEvidence in Google Cloud
1. TransportPeer IP, shared secret, IKE version and proposals, peer firewall, VLAN or LACP (Interconnect)gcloud compute vpn-tunnels describe (status, detailedStatus), Interconnect attachment state, Cloud VPN logs
2. BGPPeer link-local address, ASN, MD5 or timers, TCP 179 blocked, peer not configuredgcloud compute routers get-status (bgpPeerStatus), Cloud Router logs
3. RoutesPrefix not advertised, custom advertisements wrong, regional vs global routing mode, route priorityrouters get-status (advertised and best routes), gcloud compute routes list
4. Firewall and policyIngress deny on the VPC, on-premises firewall, a hierarchical policy, VPC Service Controls (for APIs)Firewall rules logging, Connectivity Test, Policy Troubleshooter for IAM
5. Path behaviourAsymmetric routing, MTU, MSS, duplicate prefixes on two pathsPacket captures, Packet Mirroring, ping -M do -s tests, Connectivity Test
6. ApplicationDNS, certificates, listener on the wrong portApplication logs, curl -v, Cloud DNS logs

Why layers

Each layer depends on the one below. A BGP session cannot be established over a tunnel that is down, and a route that is learned is useless if a firewall blocks the packet. Checking in order means that the first failing layer is also the root cause, and every later symptom is a consequence.

How each classic problem looks

  • Tunnel down. The tunnel shows FIRST_HANDSHAKE, NO_INCOMING_PACKETS or WAITING_FOR_FULL_CONFIG. Typical causes: the peer gateway has the wrong Google IP, the shared secret differs, IKE versions differ, the peer firewall blocks UDP 500 and 4500 (or ESP), or only one of the two tunnels was created.
  • BGP idle or active. The tunnel is up but the session is not. Check that each side's interface IP is the other side's peer IP (a /30 from 169.254.0.0/16), that the ASNs match what each side expects, and that nothing filters TCP 179 or the link-local range at the peer.
  • Route not advertised. The session is Established, but the prefix is missing on the other end. On the Google side, check the advertisement mode (a custom mode without groups advertises nothing). On the peer, check export policy and prefix lists.
  • Asymmetric routing. Two tunnels or two Interconnects carry the same prefix with different priorities, or a firewall is in the path of only one direction. Requests come in on path A and replies leave on path B. A stateful firewall drops the reply.
  • MTU. Cloud VPN adds IPsec overhead. The VPC MTU is configurable per network, and the usable payload over a tunnel is smaller than on the internal network. Symptoms: SSH logs in but stalls on large output, TLS handshakes hang at the certificate, large file copies stop. Fix with a consistent MTU and TCP MSS clamping on the on-premises device, and by testing with the don't-fragment bit.

When to use which tool

QuestionTool
Is the tunnel up?vpn-tunnels describe, Cloud VPN logs
Is BGP established, and what is advertised and learned?routers get-status
Is there a route to the destination from the source network?routes list, Connectivity Test
Which firewall rule dropped it?Firewall rules logging, Connectivity Test, Firewall Insights
Where does a live flow go?VPC Flow Logs, Packet Mirroring

Common misunderstandings

"The tunnel is up, so the network is fine." An established tunnel proves only the IPsec layer. BGP, routes, firewalls and MTU can all still fail.
"BGP is Established, so the prefix is advertised." It proves the session. Whether a prefix is advertised depends on the advertisement mode and on the peer's export policy.
Change one thing at a time. Two simultaneous changes make the evidence useless. Record the state before each change.
Symptom: cannot reach 10.70.0.5 1. Tunnel ESTABLISHED? no: peer IP, secret, IKE 2. BGP Established? no: ASN, link-local, 179 3. Route present both ways? no: advertisements 4. Firewall allows both ways? no: rules, policies 5. Same path back? MTU OK? no: asymmetry, MSS Stop at the first "no". Fix it, re-run the check, then go on.

Figure 1. The triage ladder. Each rung has one command that gives the answer.

On-premises 172.16.1.20 Tunnel A through the stateful firewall Tunnel B no firewall in the path VM in vpc-lab 10.70.0.5 request reply The firewall sees the request but never the reply.

Figure 2. Asymmetric routing. Make the return path match the forward path with consistent route priorities (MED) on both tunnels, or put the firewall on both paths.

In Figure 1 the red boxes on the right are the cause for each failing rung. In Figure 2, trace the request and the reply separately: they use different tunnels.

The animation shows a healthy flow from an on-premises host to a VM: the layers you check, in order, are the same steps the packet takes. When a real incident happens, the first step that does not look like its log line is where you start.

All the commands below are read-only and free unless marked. Replace the uppercase placeholders. IDs and field layouts in the expected output are illustrative. Check gcloud compute vpn-tunnels --help and gcloud network-management --help for the flags in your SDK version.

gcloud compute vpn-tunnels describe (read, free)

Purpose. Layer 1: shows the IPsec state and the detailed reason.

gcloud compute vpn-tunnels describe tun-hq-0 --region=REGION --project=PROJECT_ID \
  --format="yaml(name,status,detailedStatus,peerIp,ikeVersion,router)"
detailedStatus: Handshake with peer is not yet complete. Retrying.
ikeVersion: 2
name: tun-hq-0
peerIp: 198.51.100.10
router: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/routers/rtr-hq
status: FIRST_HANDSHAKE

Common errors. FIRST_HANDSHAKE or NO_INCOMING_PACKETS: wrong peer IP, wrong secret or no reply from the peer. REJECTED or NEGOTIATION_FAILURE style states: mismatching IKE proposals. WAITING_FOR_FULL_CONFIG: the tunnel lacks a router, peer or secret. The exact states are in the current Cloud VPN documentation.

gcloud compute routers get-status (read, free)

Purpose. Layers 2 and 3: BGP state, advertised routes, learned routes.

gcloud compute routers get-status rtr-hq --region=REGION --project=PROJECT_ID \
  --format="yaml(result.bgpPeerStatus,result.bestRoutes)"
result:
  bgpPeerStatus:
  - name: bgp-hq-0
    ipAddress: 169.254.10.1
    peerIpAddress: 169.254.10.2
    state: Active
    status: DOWN
    uptime: ''

Reading it. state: Active with status: DOWN means the session is not up. If Established but advertisedRoutes is empty, go to the advertisement mode. If bestRoutes is empty, the peer is announcing nothing or filtering.

gcloud compute routers describe (read, free)

Purpose. Compare what you intended with what is live: ASN, advertisement mode, groups, ranges, peer settings.

gcloud compute routers describe rtr-hq --region=REGION --project=PROJECT_ID \
  --format="yaml(bgp,bgpPeers,interfaces)"

gcloud compute routes list (read, free)

gcloud compute routes list --project=PROJECT_ID \
  --filter="network:vpc-lab AND destRange:172.16.0.0/16" \
  --format="table(name,destRange,priority,nextHopVpnTunnel.basename(),nextHopHub)"

Common errors. No row: the route is not learned. Two rows to the same prefix with different priorities: the lowest value is used, and asymmetry is possible if the peer chooses the other tunnel. A field name may differ in your SDK version, so use --format=yaml if the table fails.

gcloud network-management connectivity-tests create and describe (write, low cost)

Purpose. Layers 3 and 4: asks Google to analyse the configured path between a source and a destination and report where it stops. Tests are a metadata resource and each run is billed per test at a low rate; check the current Network Intelligence Center pricing.

gcloud network-management connectivity-tests create test-onprem-to-vm \
  --source-ip-address=172.16.1.20 \
  --source-network=projects/PROJECT_ID/global/networks/vpc-lab \
  --destination-instance=projects/PROJECT_ID/zones/ZONE/instances/vm-lab \
  --destination-port=443 --protocol=TCP \
  --project=PROJECT_ID

gcloud network-management connectivity-tests describe test-onprem-to-vm \
  --project=PROJECT_ID \
  --format="yaml(reachabilityDetails.result,reachabilityDetails.traces)"

Flags. Source and destination can be an IP address, an instance, or an endpoint. Which source flags are available depends on whether the source is inside Google Cloud, on-premises or the internet, so run gcloud network-management connectivity-tests create --help.

reachabilityDetails:
  result: UNREACHABLE
  traces:
  - endpointInfo: {}
    steps:
    - description: 'Config checking state: verify firewall rule.'
      state: DROP
      causesDrop: FIREWALL_RULE
      firewall:
        displayName: deny-all-ingress
        priority: 65534

Common errors. SERVICE_DISABLED: enable networkmanagement.googleapis.com. A result of AMBIGUOUS or UNDETERMINED means that the analysis lacked data, for example because the source is outside Google Cloud, so add more specific inputs.

gcloud logging read for firewall and VPN logs (read, free)

gcloud logging read \
  'resource.type="gce_subnetwork" AND jsonPayload.disposition="DENIED" AND jsonPayload.connection.src_ip="172.16.1.20"' \
  --project=PROJECT_ID --limit=5 --format=json

This needs Firewall Rules Logging enabled on the rule. Without it there is no entry, so enable logging only on the rules you debug, because logs are billed by volume.

MTU and path tests from a VM (read, free)

ping -M do -s 1372 -c 3 172.16.1.20
ping -M do -s 1472 -c 3 172.16.1.20

The first request tests a smaller payload; the second tests a larger one. A path that succeeds at the small size and fails at the large size has a smaller path MTU than the large packet. Add 28 bytes of IP and ICMP headers when you compare with the MTU. Use tracepath to discover the path MTU where it is available.

Production use. Put the three evidence commands (vpn-tunnels describe, routers get-status, routes list) at the top of the incident runbook, and keep a Connectivity Test for each critical flow (on-premises to database, on-premises to DNS). Run them after every change and keep the result in the change ticket.

Lab: triage a broken hybrid setup (a paper and read-only exercise, 15 minutes)

Goal. Practise the order of checks on a set of captured outputs. If you built Part C of Module 7 and it is still running, run the same commands on the live resources. Otherwise use the outputs below.

Prerequisites. Module 7 is complete. gcloud authenticated for the optional live checks. The captured outputs are illustrative and contain no real secrets.

  1. Case 1. vpn-tunnels describe shows status: FIRST_HANDSHAKE for tun-hq-0. The peer device is configured with the right ASN but the Google gateway IP from the other interface. Write the first check and the fix (use the IP of interface 0 for tunnel 0).
  2. Case 2. Both tunnels are ESTABLISHED. get-status shows state: Active, peerIpAddress: 169.254.10.2. The on-premises device has interface address 169.254.10.5. Write the cause (the addresses do not match: both ends must use the same /30) and the fix.
  3. Case 3. BGP is Established, advertisedRoutes is empty and routers describe shows advertiseMode: CUSTOM with no groups. Write the cause and the one-line fix (--set-advertisement-groups=all_subnets).
  4. Case 4. On-premises can ping a VM, but SSH stalls after login. Pings with -M do -s 1472 fail. Write the likely cause (MTU over the tunnel) and a mitigation (MSS clamping on the on-premises device, consistent MTU).
  5. Case 5. Two tunnels exist with different advertised priorities and the on-premises firewall is only in one path. Pings fail intermittently. Write the cause (asymmetric routing) and a fix (make route priorities consistent on both sides, or inspect both paths).
  6. Optional live check. Run a Connectivity Test from a source IP to a VM in your lab VPC. Read reachabilityDetails.result. If it is REACHABLE, note the trace; if not, note the causesDrop field.

Expected result. A short written table: case, first command, cause, fix. Check your answers against the troubleshooting tab.

Verification. For the live check, gcloud network-management connectivity-tests describe TEST --format="value(reachabilityDetails.result)" returns a result value. Compare it with what you predicted.

Cost. Free for the paper cases. A Connectivity Test is low cost per run. Budgets send alerts and do not cap spend.

Cleanup. gcloud network-management connectivity-tests delete test-onprem-to-vm --quiet, and complete the Module 7 cleanup if you left Part C running.

Real cases

  • Maintenance that looked like an outage. The on-premises team replaced a VPN device and kept the configuration but not the firmware profile. IKE proposals no longer matched and both tunnels dropped. The Google side showed the tunnels in a handshake state and no BGP at all. The runbook now starts with vpn-tunnels describe and a comparison of the proposals on both sides.
  • One tunnel preferred. Both tunnels were up but one carried all the traffic, because the on-premises router preferred one BGP peer by local preference. When that device was patched, traffic failed over, a stateful firewall in the second path dropped the replies, and users saw random resets. The fix was symmetric preferences and the firewall in both paths.
  • Large uploads failing. Small API calls worked over the VPN, but uploads of several megabytes stalled. The cause was an MTU of 1500 on the on-premises device with the don't-fragment bit set and an ICMP block on the path. Setting the MSS clamp and allowing ICMP "fragmentation needed" fixed it.

Practices

  • Run a Connectivity Test for the ten most important flows after each network change, and keep the saved results.
  • Monitor tunnel state, BGP session state and the count of learned prefixes. Alert when the learned count changes suddenly.
  • Test failover on a schedule: take one tunnel down in a maintenance window, confirm that traffic survives, then restore it.
  • Write the expected MTU and MSS values in the design document, and test with the don't-fragment bit after each change.
  • Enable Firewall Rules Logging and VPC Flow Logs with a sampling rate you can afford on the critical subnets only.
Security note. Do not open a firewall to "any" to test connectivity, and do not leave debug logging or packet mirroring on. Use narrow source ranges and a timer, and remove the temporary rule in the same change ticket. Packet captures can contain credentials and personal data: store them encrypted and delete them after the incident.

Symptoms and first checks

SymptomLikely causeFirst check
Tunnel FIRST_HANDSHAKE or NO_INCOMING_PACKETSWrong peer or Google IP, secret mismatch, IKE version mismatch, peer firewallvpn-tunnels describe, then the peer's logs for IKE errors
Tunnel ESTABLISHED, BGP Idle or ActiveWrong link-local addresses or ASN, TCP 179 blocked, peer BGP not configuredrouters get-status and compare the /30 on both ends
BGP Established, prefix missing on the peerCustom advertisements without groups or ranges, or the peer's import filterrouters describe (advertiseMode, groups, ranges)
Prefix learned but not in the VPC routesRegional dynamic routing mode, a more specific local route, or a route policynetworks describe (routing mode) and routes list
Requests arrive, replies do notAsymmetric routing with a stateful firewallCompare priorities on both tunnels and trace the return path
Small packets work, large transfers stallMTU or MSS, ICMP blockedping -M do -s SIZE with growing sizes
Traffic blocked only from on-premises rangesVPC firewall ingress rule missing for the on-premises CIDRConnectivity Test and Firewall Rules Logging
Intermittent failures after adding a second linkDuplicate prefixes with equal priority (ECMP) over unequal pathsSet explicit priorities (MED) and test each path alone

Triage order

  1. Tunnel or attachment state (transport).
  2. BGP session state.
  3. Advertised and learned routes on both ends.
  4. Firewall rules and policies in both directions.
  5. Path behaviour: asymmetry and MTU.
  6. Application: DNS, certificates, ports.

Use these search pages and the official documentation. Always check the date of a video and compare commands with the current reference.

Official reading: Cloud VPN troubleshooting · Connectivity Tests overview.

or score ≥ 70% on the quiz

Command cheat sheet

Hybrid connectivity: Cloud VPN, Interconnect and hub-and-spoke
Hour 5

Command cheat sheet for Hour 5. Replace uppercase placeholders (PROJECT_ID, REGION, ZONE). Commands marked write change configuration; those marked billable create resources that cost money while they exist. Budgets send alerts and do not cap spend. Check gcloud <group> --help for the flags in your SDK version.

Cloud Router and BGP

CommandPurposeKey flagsGotcha
gcloud compute routers create ROUTER (write, free)Create a Cloud Router in a VPC network and region--network, --region, --asn, --advertisement-modeThe ASN must be private (64512 to 65534 or 4200000000 to 4294967294) unless you own a public one. The router is regional.
gcloud compute routers describe ROUTER (read)Show the configured intent: ASN, advertisement mode, peers, interfaces--region, --format="yaml(bgp,bgpPeers,interfaces)"Shows configuration only. A session that is configured can still be down.
gcloud compute routers get-status ROUTER (read)Show live BGP state, advertised routes and best (learned) routes--region, --format="yaml(result.bgpPeerStatus,result.bestRoutes)"Established proves the session only. Check advertisedRoutes and bestRoutes too.
gcloud compute routers update ROUTER (write)Change advertisement mode, groups and custom ranges--advertisement-mode=custom, --set-advertisement-groups=all_subnets, --set-advertisement-ranges=CIDR=description, --add-advertisement-ranges, --remove-advertisement-rangesCustom mode with no groups and no ranges advertises nothing. Describe before and after.
gcloud compute routers add-interface ROUTER (write)Attach a link-local interface to a VPN tunnel or VLAN attachment--interface-name, --vpn-tunnel, --ip-address, --mask-length=30, --regionInterface addresses come from 169.254.0.0/16. Both ends of a tunnel must use the same /30.
gcloud compute routers add-bgp-peer ROUTER (write)Define the neighbour for a router interface--peer-name, --interface, --peer-ip-address, --peer-asn, --regionThe peer ASN must differ from the router ASN for external BGP. Check --help for advertisement and priority flags.
gcloud compute routers remove-bgp-peer ROUTER (write)Remove a BGP peer before deleting the tunnel--peer-name, --regionRemoving the peer drops the session and its routes at once.
gcloud compute routers delete ROUTER (write)Delete a Cloud Router--region, --quietAll dynamic routes learned through it disappear. Delete tunnels first or you get a dependency error.

HA VPN

CommandPurposeKey flagsGotcha
gcloud compute vpn-gateways create GW (write, billable with tunnels)Create an HA VPN gateway with two interfaces--network, --regionEach interface gets its own external IP. Give both to the peer team.
gcloud compute external-vpn-gateways create PEER (write)Describe the on-premises gateway to Google--interfaces=0=PEER_IP_0,1=PEER_IP_1 (check --help for the redundancy flag)The redundancy type must match the real number of peer interfaces, or tunnels do not form as expected.
gcloud compute vpn-tunnels create TUN (write, billable)Create one IPsec tunnel on one HA VPN interface--vpn-gateway, --interface, --peer-gcp-gateway or --peer-external-gateway with --peer-external-gateway-interface, --router, --ike-version=2, --shared-secret, --regionCreate a tunnel on each interface for the SLA. Never type a real secret in a command: use a variable from Secret Manager.
gcloud compute vpn-tunnels describe TUN (read)Show the IPsec state and the detailed reason--region, --format="yaml(status,detailedStatus,peerIp)"FIRST_HANDSHAKE and NO_INCOMING_PACKETS point at the peer side.
gcloud compute vpn-tunnels list (read)List tunnels and their states--filter, --format="table(name,status,detailedStatus)"Filter by region to avoid noise from other regions.
gcloud compute vpn-tunnels delete TUN (write)Stop billing and remove the tunnel--region, --quietRemove the BGP peer and interface first.
gcloud compute vpn-gateways delete GW (write)Delete the gateway--regionFails while a tunnel uses it.

Interconnect (read-only checks)

CommandPurposeKey flagsGotcha
gcloud compute interconnects list (read)List Dedicated Interconnect connections--formatEmpty for Partner Interconnect: those appear as attachments only.
gcloud compute interconnects attachments list (read)List VLAN attachments with state and router--filter, --formatCompare operationalStatus and the pairing key with the provider portal.
gcloud compute interconnects attachments describe ATTACHMENT (read)Show VLAN ID, Cloud Router IP and customer router IP--regionCheck --help for the fields in your SDK version. Never confuse the two link-local addresses.

Network Connectivity Center

CommandPurposeKey flagsGotcha
gcloud network-connectivity hubs create HUB (write)Create a hub in the network project--description, --projectEnable networkconnectivity.googleapis.com first.
gcloud network-connectivity spokes linked-vpc-network create SPOKE (write)Attach a VPC network to the hub--hub, --vpc-network, --globalOverlapping subnets are not accepted. Plan the IP ranges first.
gcloud network-connectivity spokes linked-vpn-tunnels create SPOKE (write)Attach HA VPN tunnels as a hybrid spoke--hub, --vpn-tunnels, --region, --site-to-site-data-transferInclude both tunnels of the pair. The data-transfer flag opens site-to-site routing.
gcloud network-connectivity hubs describe HUB (read)Show hub state and unique ID--project, --formatThe state must be ACTIVE before you rely on it.
gcloud network-connectivity spokes list --hub=HUB (read)List attached spokes with state and type--hub, --projectAn inactive spoke removes routes silently.
gcloud network-connectivity spokes delete SPOKE (write)Detach a network--global or --region, --quietRoutes disappear from every other spoke at once. Treat it as an outage risk.

Cloud Armor and load balancer

CommandPurposeKey flagsGotcha
gcloud compute security-policies create POLICY (write, billed while it exists)Create a Cloud Armor policy--description, --projectThe policy does nothing until it is attached to a backend service.
gcloud compute security-policies rules create PRIORITY (write)Add an allow, deny, throttle or WAF rule--security-policy, --src-ip-ranges, --expression, --action, --previewStart in --preview. Lower priority numbers are evaluated first.
gcloud compute security-policies rules update PRIORITY (write)Enforce or change a rule--security-policy, --no-preview, --actionSwitching --no-preview goes live at once.
gcloud compute backend-services update BACKEND (write)Attach the policy to a backend service--security-policy=POLICY, --globalUse an empty value to detach before deleting the policy.
gcloud compute security-policies describe POLICY (read)Read rules, priorities and preview flags--format="yaml(rules)"Check the preview flag: a rule left in preview protects nothing.
gcloud compute backend-services get-health BACKEND (read)Check backend health behind the load balancer--global502 errors often come from health checks blocked by a firewall.

Diagnostics

CommandPurposeKey flagsGotcha
gcloud compute routes list (read)See static, subnet and dynamic routes in a VPC network--filter="network:NAME", --formatTwo routes to one prefix: the lowest priority value wins, and asymmetry is possible.
gcloud network-management connectivity-tests create TEST (write, low cost)Analyse the path between a source and a destination--source-*, --destination-*, --destination-port, --protocolRequires networkmanagement.googleapis.com. The flags depend on the endpoint types.
gcloud network-management connectivity-tests describe TEST (read)Read the result and the step where a packet drops--format="yaml(reachabilityDetails)"UNDETERMINED means that the analysis lacked data.
gcloud logging read FILTER (read)Read Cloud VPN, router, firewall and load balancer logs--limit, --format=json, --freshnessFirewall Rules Logging must be enabled on the rule, and it is billed by volume.
Triage order. Tunnel state, then BGP state, then routes on both ends, then firewalls, then asymmetry and MTU, then the application.
Cost. VPN gateways and tunnels, Interconnect, load balancers and Cloud Armor policies are billed while they exist. Delete lab resources in dependency order and rely on cleanup, not on budgets.

Capstone lab and final quiz

Hybrid connectivity: Cloud VPN, Interconnect and hub-and-spoke
Hour 5

Capstone lab: a hybrid hub with a Cloud Router, BGP and a protected entrance

Goal. Build a small, safe hybrid-network foundation in a sandbox project: a hub-and-spoke topology in Network Connectivity Center with two VPC spokes, a Cloud Router with controlled advertisements, an optional HA VPN pair with two BGP sessions, and a Cloud Armor policy rolled out in preview mode. Then verify each part, break one thing on purpose, fix it with the triage order, and clean everything up.

Prerequisites

  • A sandbox project (or a folder of sandbox projects) with billing linked and a budget with alert thresholds set in Hour 1. Budgets send alerts and do not cap spend.
  • gcloud CLI (current release channel), authenticated in Cloud Shell or a local shell. Roles on the project: roles/compute.networkAdmin, roles/compute.securityAdmin, roles/networkconnectivity.hubAdmin, roles/serviceusage.serviceUsageAdmin.
  • A single REGION for all resources, and non-overlapping ranges: 10.80.0.0/24 and 10.81.0.0/24.
  • No real secrets. The VPN secret is generated in memory and never printed.

IDs in the expected output are illustrative. Check gcloud <group> --help for the flags in your SDK version.

Cost. Steps 1 to 4 and 8 are metadata operations and are free. Step 5 (HA VPN) creates gateways and tunnels that are billed while they exist, plus data transfer; it is low for under an hour, but a forgotten lab accumulates charges. Step 7 (Cloud Armor policy) is billed while the policy exists. A budget does not cap spend: do the cleanup at the end, before you close the terminal.

Steps

  1. Set up the shell and APIs.
    export PROJECT_ID=YOUR_SANDBOX_PROJECT
    export REGION=YOUR_REGION
    gcloud config set project $PROJECT_ID
    gcloud services enable compute.googleapis.com networkconnectivity.googleapis.com networkmanagement.googleapis.com
    Verify: gcloud services list --enabled --filter="name:compute OR name:networkconnectivity" --format="value(name)" lists both APIs.
  2. Create two custom VPC networks and subnets.
    gcloud compute networks create vpc-cap-a --subnet-mode=custom
    gcloud compute networks create vpc-cap-b --subnet-mode=custom
    gcloud compute networks subnets create sub-cap-a --network=vpc-cap-a --region=$REGION --range=10.80.0.0/24
    gcloud compute networks subnets create sub-cap-b --network=vpc-cap-b --region=$REGION --range=10.81.0.0/24
    Verify: gcloud compute networks subnets list --filter="name~sub-cap" --format="table(name,region.basename(),ipCidrRange)" shows both ranges and no overlap.
    NAME        REGION   IP_CIDR_RANGE
    sub-cap-a   REGION   10.80.0.0/24
    sub-cap-b   REGION   10.81.0.0/24
  3. Create the hub and attach both networks as VPC spokes.
    gcloud network-connectivity hubs create hub-cap --description="Capstone hub"
    gcloud network-connectivity spokes linked-vpc-network create spoke-cap-a --hub=hub-cap --vpc-network=projects/$PROJECT_ID/global/networks/vpc-cap-a --global
    gcloud network-connectivity spokes linked-vpc-network create spoke-cap-b --hub=hub-cap --vpc-network=projects/$PROJECT_ID/global/networks/vpc-cap-b --global
    Verify: gcloud network-connectivity spokes list --hub=hub-cap shows two spokes in the ACTIVE state. Then gcloud compute routes list --filter="network:vpc-cap-a AND destRange:10.81.0.0/24" shows the route to the other network (it can take a minute).
  4. Create a Cloud Router with controlled advertisements.
    gcloud compute routers create rtr-cap-a --network=vpc-cap-a --region=$REGION --asn=64520
    gcloud compute routers update rtr-cap-a --region=$REGION --advertisement-mode=custom --set-advertisement-groups=all_subnets --set-advertisement-ranges=192.168.210.0/24=cap-summary
    Verify: gcloud compute routers describe rtr-cap-a --region=$REGION --format="yaml(bgp.asn,bgp.advertiseMode,bgp.advertisedGroups,bgp.advertisedIpRanges)".
    bgp:
      advertiseMode: CUSTOM
      advertisedGroups:
      - ALL_SUBNETS
      advertisedIpRanges:
      - description: cap-summary
        range: 192.168.210.0/24
      asn: 64520
  5. (Optional, billable) Bring up HA VPN with BGP between the two networks. Skip this step if you only want free resources and go to step 7. Create a second router rtr-cap-b (ASN 64521) on vpc-cap-b, one HA VPN gateway on each network (gw-cap-a, gw-cap-b), generate VPN_SECRET=$(openssl rand -base64 24), and create four tunnels (interface 0 and 1 on each gateway) with --peer-gcp-gateway, --router, --ike-version=2 and --shared-secret="$VPN_SECRET". Add a router interface and a BGP peer for each tunnel, using a different /30 from 169.254.0.0/16 for each tunnel (for example 169.254.20.0/30 and 169.254.21.0/30), as in Module 7. Then unset VPN_SECRET. Verify the tunnels: gcloud compute vpn-tunnels list --filter="region:$REGION" --format="table(name,status)" shows four tunnels in ESTABLISHED state (wait two to three minutes). Verify BGP: gcloud compute routers get-status rtr-cap-a --region=$REGION --format="value(result.bgpPeerStatus[].state)" prints Established for both peers. gcloud compute routes list --filter="network:vpc-cap-a AND destRange:10.81.0.0/24" shows a dynamic route. Note that the hub and the VPN both carry this prefix: the hub for VPC spokes, the VPN for dynamic routing. In production you would use one or the other for a given pair.
  6. Break one thing on purpose and fix it. Run gcloud compute routers update rtr-cap-a --region=$REGION --advertisement-mode=custom --set-advertisement-groups="" --clear-advertisement-ranges (check --help for the exact flag names in your SDK version). Run get-status and write down which layer shows the symptom (the session stays up, the advertised list is empty). Restore with --set-advertisement-groups=all_subnets. Verify: advertisedRoutes again contains 10.80.0.0/24.
  7. Create a Cloud Armor policy in preview mode.
    gcloud compute security-policies create pol-cap --description="Capstone policy"
    gcloud compute security-policies rules create 1000 --security-policy=pol-cap --description="Preview deny of /admin" --expression="request.path.matches('/admin.*')" --action=deny-403 --preview
    Verify: gcloud compute security-policies describe pol-cap --format="yaml(rules[].priority,rules[].preview)" shows rule 1000 with preview: true and the default rule last. Attaching the policy to a live load balancer is outside this capstone, because it needs a billable load balancer.
  8. Run a Connectivity Test (low cost).
    gcloud network-management connectivity-tests create cap-test \
      --source-network=projects/$PROJECT_ID/global/networks/vpc-cap-a --source-ip-address=10.80.0.10 \
      --destination-network=projects/$PROJECT_ID/global/networks/vpc-cap-b --destination-ip-address=10.81.0.10 \
      --destination-port=443 --protocol=TCP
    Verify: gcloud network-management connectivity-tests describe cap-test --format="value(reachabilityDetails.result)" prints a result. With no VM and no firewall rule you will probably see a drop. Write down which step drops the packet and why (for example, no allowing ingress firewall rule).

Expected result

  • Two active VPC spokes on one hub and routes in both directions.
  • A Cloud Router with ASN 64520 and custom advertisements that you changed, broke and restored.
  • (Optional) four established tunnels and two established BGP sessions per router.
  • A Cloud Armor policy with one preview rule.
  • A written note for each failure you provoked: first command, evidence, cause, fix.

Cleanup (in this order, do not skip)

gcloud network-management connectivity-tests delete cap-test --quiet
gcloud compute security-policies delete pol-cap --quiet

# Only if you ran step 5:
for R in rtr-cap-a rtr-cap-b; do
  for P in $(gcloud compute routers describe $R --region=$REGION --format="value(bgpPeers[].name)" | tr ';' ' '); do
    gcloud compute routers remove-bgp-peer $R --peer-name=$P --region=$REGION --quiet
  done
done
gcloud compute vpn-tunnels list --filter="region:$REGION" --format="value(name)" | xargs -r gcloud compute vpn-tunnels delete --region=$REGION --quiet
gcloud compute vpn-gateways delete gw-cap-a gw-cap-b --region=$REGION --quiet

gcloud network-connectivity spokes delete spoke-cap-a --global --quiet
gcloud network-connectivity spokes delete spoke-cap-b --global --quiet
gcloud network-connectivity hubs delete hub-cap --quiet
gcloud compute routers delete rtr-cap-a rtr-cap-b --region=$REGION --quiet
gcloud compute networks subnets delete sub-cap-a sub-cap-b --region=$REGION --quiet
gcloud compute networks delete vpc-cap-a vpc-cap-b --quiet

Errors for resources that you did not create (for example rtr-cap-b when you skipped step 5) are expected and harmless.

Final check. gcloud compute networks list --filter="name~vpc-cap", gcloud compute routers list, gcloud compute vpn-tunnels list and gcloud network-connectivity hubs list must show nothing for the capstone names. Check the billing report the next day for unexpected charges.

Self-assessment

  • Can you explain why a hub, and not a mesh of peerings, was used for the two VPC networks?
  • Can you say which layer each of your three checks (vpn-tunnels describe, routers get-status, routes list) covers?
  • Can you explain why a Cloud Armor rule in preview mode does not protect anything yet?

Now take the final quiz.

Knowledge check

Sources and versions

Hybrid connectivity: Cloud VPN, Interconnect and hub-and-spoke
Hour 5

Reference documentation for Hour 5

These are the official pages that this hour is based on. Documentation pages are reorganised from time to time, so if a link no longer opens, search the title on cloud.google.com.

Tools and versions used in this hour

ToolVersion usedNote
Google Cloud CLI (gcloud)Current release channel (GA commands)Run gcloud version and gcloud components update. The network-connectivity, network-management and security-policies groups gain flags between releases.
Terraform (referenced only)1.x with the Google providerPin the major version in required_providers. The Terraform modules above are examples, not prerequisites for the labs.
Cloud ShellManaged by GoogleIncludes gcloud, openssl and ping. It is the simplest environment for the labs.

Before you use this in production

Check flags and quotas against the current documentation. Commands in this hour were written to use stable, documented forms. Flags, spoke types, supported topologies, preconfigured Cloud Armor rule names and resource states change between releases, and some features are in preview. Run gcloud <group> --help and read the current reference before you run a command in a production project.
  • Do not copy ASNs, IP ranges, resource names or output from this course into production. All values are examples. IDs in expected output are illustrative.
  • Check the current pricing pages for Cloud VPN, Cloud Interconnect, Cloud Router, Network Connectivity Center, Cloud Armor, load balancing and Connectivity Tests. This course does not state prices.
  • Confirm the availability SLA conditions for HA VPN and Cloud Interconnect in the current service level agreement before you promise an availability target.
  • Review every network change in a pull request, test it in a sandbox first, and keep the rollback command ready.
  • Budgets send alerts and do not cap spend. Delete billable lab resources when you finish.