Hour 4: Network hub: Shared VPC, firewall policies, egress and DNS

VPC networks and subnets, Shared VPC host and service projects, hierarchical firewall policies, Cloud NAT, Private Google Access and Cloud DNS.
Hour 4Shared VPCFirewall policiesCloud DNS

Network hub: Shared VPC, firewall policies, egress and DNS

Hours 1 to 3 gave you an organization, an identity model and guardrails. This hour builds the part every workload touches: the network. You will build the hub of the landing zone, a host project that owns one global VPC network, and you will learn how other projects use it without owning it.

The hour follows the order in which a platform team makes decisions. First the building blocks of a Google Cloud VPC network (global network, regional subnets, routes, custom mode). Then Shared VPC, which separates the network team from the application teams. Then the IP address plan, the one decision that is hard to change later. Then hierarchical firewall policies, which let you set security rules once for a whole folder.

The second half covers how traffic leaves and how names are found: Cloud NAT and Private Google Access for egress without external IP addresses, and Cloud DNS for private zones inside the VPC. Module 7 puts all of it together in one lab with verification after each step, and Module 8 collects the symptoms you will see in real networks and the order in which to check them.

Every module has ten tabs: concepts, diagrams, an animation, commands, a lab, production cases, troubleshooting, videos, plus a quiz and audio narration. The hour ends with a command cheat sheet, a capstone lab and a final quiz.

What you will be able to do

  • Explain the Google Cloud network model (global VPC, regional subnets, routes, firewall) and create a custom-mode network with gcloud.
  • Design a host project and service project layout, enable Shared VPC and grant subnet-level roles/compute.networkUser.
  • Write an IP address plan without overlaps, including secondary ranges for GKE and reserved ranges for managed services.
  • Create hierarchical firewall policies with correct priorities and the actions allow, deny and goto_next, and associate them with folders.
  • Provide egress with Cloud Router and Cloud NAT, and private access to Google APIs.
  • Create private Cloud DNS zones and record sets for a VPC network.
  • Diagnose the common failures: no egress, DNS not resolving, shared subnet not visible, firewall priority conflicts, CIDR overlap.

Schedule (60 minutes)

#ModuleMinutesMain commands
1VPC fundamentals6gcloud compute networks create, subnets create, routes list
2Shared VPC8gcloud compute shared-vpc enable, associated-projects add
3IP address plan7subnets create --secondary-range, expand-ip-range
4Hierarchical firewall policies8gcloud compute firewall-policies create, rules create, associations create
5Egress and private access7gcloud compute routers create, routers nats create
6Cloud DNS7gcloud dns managed-zones create, record-sets create
7Lab: host project, shared VPC, subnet, NAT, firewall policy10All of the above, with verification
8Troubleshooting networks7get-effective-firewalls, routes list, nat get-status
Total60

The times are the study time for reading and running the commands inside the hour. A first-time learner will need more time for the labs; the ten tabs are meant to be used as a reference later.

What you need

  • A Google Cloud identity, a billing account with a budget, and the gcloud CLI or Cloud Shell. See the Setup page for the checks.
  • Two sandbox projects (a host and a service project), and a lab folder under an organization for Modules 2, 4 and 7. If you have no organization, the labs give a fallback that uses a single project and VPC firewall rules; Shared VPC and hierarchical policies cannot be run without an organization.
  • The foundations from Hours 1 to 3: the hierarchy, billing links, a group-based IAM approach, and the Organization Policy basics.

What the labs create and what they cost

ResourceCreated inCost
VPC networks, subnets, routes, firewall rules, firewall policies and associationsModules 1, 3, 4, 7Free (metadata only)
Shared VPC host enablement and service project attachmentModules 2, 7Free
Cloud DNS private zone and a few record setsModules 6, 7Low (usually well under a few USD per day for this lab)
Cloud Router and Cloud NAT gatewayModules 5, 7Low while it exists, metered by the hour and by data processed. Delete it in the cleanup the same day.
One small test VM (optional, for proof of egress and shared subnet use)Modules 2, 7Low (usually well under a few USD per day). Delete it when the test is done.
Cost warning. Budgets send alerts; they do not cap spend. Set a budget with alert thresholds before you start (see Setup), use the smallest machine type, and run every cleanup step, in the order given, when you finish. Cloud NAT and VMs are the two items that keep billing if you forget them.
How to study. Read the concepts tab, run the commands tab against a lab project, then do the lab with its verification commands. Use the quiz at the end of each module as a check before you move on.

Setup

Network hub: Shared VPC, firewall policies, egress and DNS
Hour 4

Environment for Hour 4

This hour needs two sandbox projects, one lab folder, a few roles, the networking APIs and a budget. Everything here is safe to create and delete. IDs in expected output are illustrative; replace ORG_ID, FOLDER_ID, BILLING_ACCOUNT_ID, HOST_PROJECT_ID, SERVICE_PROJECT_ID, REGION and ZONE with your own values.

1. Tools: gcloud CLI or Cloud Shell

The simplest start is Cloud Shell (the terminal button in the Google Cloud console). It has the gcloud CLI, Terraform and an authenticated session. To use your own machine, install the gcloud CLI (current release channel) and sign in.

gcloud version
gcloud auth login
gcloud auth list
gcloud config list
Google Cloud SDK 5xx.x.x
...
Credentialed Accounts
ACTIVE  ACCOUNT
*       you@example.com
[core]
account = you@example.com

Update the CLI if commands in this hour are not recognized: gcloud components update (not available when gcloud was installed through a package manager; use that manager instead). Where a flag is not shown in your SDK version, check gcloud … --help.

2. Organization, lab folder and projects

Shared VPC (Modules 2 and 7) and hierarchical firewall policies (Module 4) need an organization. Check that you have one:

gcloud organizations list
DISPLAY_NAME  ID            DIRECTORY_CUSTOMER_ID
example.com   123456789012  C01abc2de

Create a lab folder and two projects under it. These steps are free; link a billing account to the projects (you need roles/billing.user on it):

gcloud resource-manager folders create --display-name="lz-net-lab" --organization=ORG_ID
gcloud projects create HOST_PROJECT_ID --folder=FOLDER_ID --name="lab net host" --labels=env=lab,owner=platform
gcloud projects create SERVICE_PROJECT_ID --folder=FOLDER_ID --name="lab net service" --labels=env=lab,owner=platform
gcloud billing projects link HOST_PROJECT_ID --billing-account=BILLING_ACCOUNT_ID
gcloud billing projects link SERVICE_PROJECT_ID --billing-account=BILLING_ACCOUNT_ID

Project IDs are global, 6 to 30 characters, and cannot be changed. Use a suffix of your own, such as lz-net-host-xyz123. Verify:

gcloud projects list --filter="parent.id=FOLDER_ID" --format="table(projectId,name,labels)"
gcloud billing projects describe HOST_PROJECT_ID --format="value(billingEnabled)"
PROJECT_ID           NAME             LABELS
lz-net-host-xyz123   lab net host     env=lab,owner=platform
lz-net-svc-xyz123    lab net service  env=lab,owner=platform
True

3. Roles you need

RoleOnNeeded for
roles/compute.xpnAdmin (Shared VPC Admin)Lab folder or organizationEnable the host project and attach service projects (Modules 2 and 7)
roles/compute.networkAdminHost projectCreate networks, subnets, Cloud Router, Cloud NAT
roles/compute.securityAdminHost projectVPC firewall rules (also in the no-organization fallback)
roles/compute.orgFirewallPolicyAdmin and roles/compute.orgFirewallPolicyUserOrganizationCreate and associate hierarchical firewall policies (Module 4)
roles/dns.adminHost projectCloud DNS zones and record sets (Module 6)
roles/serviceusage.serviceUsageAdminBoth projectsEnable APIs
roles/billing.userBilling accountLink projects to billing

In a lab it is acceptable to use roles/owner on the two lab projects and the folder administration roles on the lab folder, but do not use broad roles on the organization for lab work. Grant roles to a group (GROUP_EMAIL), not to individual users:

gcloud resource-manager folders add-iam-policy-binding FOLDER_ID --member="group:GROUP_EMAIL" --role="roles/compute.xpnAdmin"
gcloud projects add-iam-policy-binding HOST_PROJECT_ID --member="group:GROUP_EMAIL" --role="roles/compute.networkAdmin"

Organization-level roles (roles/compute.orgFirewallPolicyAdmin) are granted with gcloud organizations add-iam-policy-binding ORG_ID ... by an organization administrator. Roles can take a minute to take effect.

4. Enable the networking APIs (free)

gcloud services enable compute.googleapis.com dns.googleapis.com --project=HOST_PROJECT_ID
gcloud services enable compute.googleapis.com --project=SERVICE_PROJECT_ID
gcloud services list --enabled --project=HOST_PROJECT_ID --filter="name:(compute.googleapis.com OR dns.googleapis.com)" --format="value(name)"
compute.googleapis.com
dns.googleapis.com

Enabling the Compute Engine API in a new project creates a default network unless the constraint compute.skipDefaultNetworkCreation is enforced. Module 1 shows how to delete it. Check whether it exists now:

gcloud compute networks list --project=HOST_PROJECT_ID

5. Set a budget before you create anything that bills

Budgets send alerts at thresholds; they do not stop spending. Create a small budget on the billing account for the lab projects (see Hour 1, Module 3 for the full explanation). The command form is below; check gcloud billing budgets create --help for the flags in your SDK version.

gcloud billing budgets create \
  --billing-account=BILLING_ACCOUNT_ID \
  --display-name="lz-net-lab-budget" \
  --budget-amount=20USD \
  --threshold-rule=percent=0.5 \
  --threshold-rule=percent=0.9 \
  --filter-projects=projects/HOST_PROJECT_ID,projects/SERVICE_PROJECT_ID

Use an amount that fits your sandbox. Also set up an email recipient for billing alerts in the console so someone sees them. The costs in this hour are low, but a forgotten Cloud NAT gateway or VM keeps billing every hour.

6. Default settings for the commands

gcloud config set project HOST_PROJECT_ID
gcloud config set compute/region REGION
gcloud config set compute/zone ZONE
gcloud config list

Use a region close to you that is allowed by your policies (for example one that gcp.resourceLocations permits; Hour 3). A lab region and zone are the same in every module of this hour.

What to do without an organization

No organization. A personal account without a verified domain has no organization, so there are no folders, no organization-level IAM and no hierarchical firewall policies, and Shared VPC cannot be enabled.
  • Use one sandbox project with a billing account and a budget. Skip the folder and the service project.
  • Do Modules 1, 3, 5 and 6 as written: they work in a single project (VPC, subnets, secondary ranges, Cloud NAT, private DNS zones).
  • For Module 2 read the concepts and diagrams, and run gcloud compute shared-vpc list-associated-resources HOST_PROJECT_ID only to see the error message.
  • For Module 4 use the fallback in its lab: VPC firewall rules with the same priorities and the same IAP and deny pattern.
  • For Module 7 follow the single-project path given in the lab, and treat Shared VPC steps as a walkthrough.
  • Free option for an organization: Cloud Identity Free with a domain you own gives you an organization at no licence cost. Use a domain you control, and do not use a company domain for personal experiments.

Checklist before you start

  • gcloud auth list shows the identity you expect.
  • gcloud organizations list shows an organization (or you have chosen the single-project path).
  • Two lab projects exist, are linked to billing, and have the Compute Engine API enabled.
  • A budget with alerts exists for the billing account or the projects.
  • gcloud compute networks list --project=HOST_PROJECT_ID works (the output may be empty).
  • You know the cleanup order: VMs, NAT and routers, firewall policy associations, Shared VPC attachments, subnets, networks. Each module lab lists it.

Module 1 · VPC fundamentals

00–06 · Global VPC networks, regional subnets, routes, custom mode, and why the default network is avoided
VPCSubnetsRoutesCustom mode6 min
Learning objectives
  • Explain that a Google Cloud VPC network is a global resource with regional subnets, and describe what routes and implied firewall rules do.
  • Create a custom-mode VPC network and a subnet with gcloud, and verify them with describe commands.
  • Describe why the default network and auto mode networks are avoided in a landing zone, and how to prevent them.

The short answer

A VPC network (虚拟私有云网络) is the private network of a project. In Google Cloud it is a global resource: the same network covers every region. The IP address space is not in the network itself but in subnets (子网), and a subnet belongs to exactly one region. A VM in europe-west1 and a VM in asia-east1 that sit in the same VPC network can reach each other by internal IP address, with no VPN or peering between them, as long as a firewall rule allows the traffic.

What: the pieces of a VPC network

PieceScopeWhat it does
VPC networkGlobal, inside one projectContainer for subnets, routes and firewall rules. Has a routing mode (regional or global dynamic routing) and an MTU setting.
SubnetRegionalA primary IPv4 range and optional secondary ranges. Can enable Private Google Access and flow logs.
RouteGlobal (applies to the whole network)Destination range, next hop and priority. Subnet routes are created for you, other routes are static or dynamic (from Cloud Router).
Firewall rule or policyGlobal, regional, or hierarchicalAllow or deny traffic by direction, priority, source or destination, protocol and port, and target.
Network interfacePer VMThe attachment of a VM to one subnet. A VM has one internal IP per interface and optionally an external IP.

Why: global network, regional subnets

In some other clouds a virtual network is a regional object, and you need peering or transit constructs to join regions. In Google Cloud the network is already global, so one VPC network and a few subnets can serve a worldwide platform. This is the reason a landing zone usually has few, large networks (for example one hub network per environment) instead of one network per application.

How it works internally

  1. Subnet route. When you create a subnet, the network installs a subnet route for its primary range (and each secondary range). You cannot delete it while the subnet exists. These routes are why every VM in the VPC can reach every subnet.
  2. Default route. A new network also has a system generated route 0.0.0.0/0 to the default-internet-gateway at priority 1000. It only helps a VM that has an external IP address (or that uses Cloud NAT, Module 5). If you delete it, and add no replacement, internet egress stops.
  3. Route selection. The most specific destination (longest prefix) wins. Among equal prefixes the lowest priority number wins. Dynamic routes from Cloud Router (Hour 5) take part in the same selection.
  4. Implied firewall rules. Two hidden rules at priority 65535: allow all egress and deny all ingress. A firewall rule or policy with a lower number (higher priority) wins over them.
  5. Reserved addresses. In each primary IPv4 range Google reserves the first address (network), the second (default gateway), the second to last and the last (broadcast). A /24 therefore gives 252 usable addresses, not 256. The smallest primary IPv4 range you can create is /29.

Auto mode, custom mode, and the default network

ItemAuto mode networkCustom mode network
SubnetsOne subnet per region, created automatically, each a /20 inside 10.128.0.0/9; new regions add subnets laterNone until you create them
IP controlFixed block, cannot overlap with other auto mode networksYou choose every range
Hybrid and peeringRanges can collide with on-premises or other networks; cannot be used with VPN or peering of the same rangeDesigned to be planned with the rest of the estate
Landing zone useAvoidUse

The default network that appears in a new project is an auto mode network with four convenience firewall rules: default-allow-internal (all internal traffic in 10.128.0.0/9), default-allow-ssh, default-allow-rdp and default-allow-icmp from 0.0.0.0/0. That is wide open for SSH and RDP from the internet, and no landing zone wants it in production. You can switch an auto mode network to custom mode with gcloud compute networks update NETWORK --switch-to-custom-subnet-mode; the change is one-way.

When to use what

  • Custom mode, global routing, a few large networks for a landing zone. Subnets per region, per tier or per team, as needed.
  • Several VPC networks when you need a hard boundary (production versus non-production, a regulated workload, an untrusted partner). Join them with Network Connectivity Center or peering (Hour 5).
  • A sandbox default network only in a disposable personal project, never in the organization's production path.

What it is confused with

Often confused withDifference
AWS VPC or Azure VNetThose are regional objects. A Google Cloud VPC network is global, subnets are regional, and routes and firewall rules apply across the global network.
Subnet = availability zoneA subnet is regional. A VM in any zone of the region can use it. There is no subnet per zone.
VPC network vs projectA project can hold several networks. A network lives in one project (or is shared from a host project, Module 2).
Firewall rule vs routeA route decides where a packet goes. A firewall rule decides whether it may pass. You need both to be right.

Common misunderstandings

"A subnet in another region cannot be reached." It can. Subnet routes apply to the whole VPC network. The usual reason for failure is a missing firewall rule, since ingress is denied by default.
"Deleting the default network is risky." Deleting it removes the network and its firewall rules. If you have no resources attached it is safe, and it is the normal first step in a new project. To keep it from returning, enforce compute.skipDefaultNetworkCreation at the organization or folder.
"Private IP means private from Google." Internal addresses are only reachable inside the VPC and its hybrid links. Reaching Google APIs privately is a separate setting (Private Google Access, Module 5).
VPC network vpc-hub (global) · custom mode · project prj-net-hub Subnet snet-app-ew1 europe-west1 10.16.0.0/20 VMs in zones b, c, d Subnet snet-app-ue1 us-east1 10.17.0.0/20 VMs in zones b, c, d Subnet snet-app-ae1 asia-east1 10.18.0.0/20 VMs in zones a, b, c Routes: subnet routes (automatic) + 0.0.0.0/0 to default-internet-gateway Global routing table: longest prefix wins, then lowest priority number Firewall: your rules and policies, then implied deny-ingress / allow-egress (priority 65535) Applies across all regions of the network One network, three regions, no peering between regions. Subnet traffic between regions rides Google's backbone. Cross-region traffic is subject to inter-region network egress charges; check current network pricing.

Figure 1. One global VPC network with regional subnets. The routing table and the firewall are properties of the whole network, not of a region.

Look at the three layers inside the dashed zone: subnets hold the address space, routes decide the next hop, and firewall rules decide whether a packet passes. When a connection fails, test them in that order.

New project Compute Engine API enabled skipDefaultNetworkCreation? Organization Policy at folder Yes: no default network Create custom VPC or use Shared VPC No: default network appears auto mode + open SSH/RDP rules delete it networks delete default

Figure 2. The default network is created at the moment the Compute Engine API is enabled. Prevent it with the constraint, or delete it right after.

The animation shows what happens behind two gcloud commands. The first call creates only an empty global network. The second call creates a regional subnet, and the routing table gets the subnet route. The default route to the internet gateway comes with the network.

These commands work in any project where the Compute Engine API is enabled. Replace PROJECT_ID and REGION with your values (for example a lab project and europe-west1). Enabling an API is free; networks, subnets, routes and firewall rules are metadata and are free to create.

gcloud services enable compute.googleapis.com (free)

Purpose. Enables the Compute Engine API in the project. A VPC network cannot be created until the API is on. If the organization does not skip default network creation, this command also creates the default network.

gcloud services enable compute.googleapis.com --project=PROJECT_ID
Operation "operations/acat.p2-123456789012-aaaa1111-bbbb-2222-cccc-333344445555" finished successfully.

Flags. --project selects the project explicitly, so the command does not depend on the active configuration. Common errors. PERMISSION_DENIED ... serviceusage.services.enable means you need roles/serviceusage.serviceUsageAdmin or an equivalent role. Production use. Enabling APIs is done by the project factory (Hour 7), not by hand.

gcloud compute networks list (free, read only)

Purpose. Shows the networks in a project, with the subnet mode. Run it first in every new project to see whether a default network exists.

gcloud compute networks list --project=PROJECT_ID
NAME     SUBNET_MODE  BGP_ROUTING_MODE  IPV4_RANGE  GATEWAY_IPV4
default  AUTO         REGIONAL

Flags. --format="value(name)" prints only names, which is handy in scripts. Common errors. Compute Engine API has not been used in project ... before means the API is not enabled yet.

gcloud compute networks delete default (free, destructive)

Purpose. Removes the default network. Delete the four default firewall rules first, or the command fails because they still reference the network.

gcloud compute firewall-rules delete default-allow-icmp default-allow-internal default-allow-rdp default-allow-ssh --project=PROJECT_ID --quiet
gcloud compute networks delete default --project=PROJECT_ID --quiet
Deleted [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls/default-allow-icmp].
Deleted [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls/default-allow-internal].
Deleted [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls/default-allow-rdp].
Deleted [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls/default-allow-ssh].
Deleted [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/default].

Flags. --quiet skips the confirmation prompt; use it only in scripts you have reviewed. Common errors. The network resource ... is already being used by ... means a VM, a route or a rule still uses it. List them with gcloud compute instances list and gcloud compute firewall-rules list --filter="network:default".

gcloud compute networks create (free)

Purpose. Creates a custom-mode VPC network with global dynamic routing, so Cloud Router (Hour 5) can advertise routes across regions.

gcloud compute networks create vpc-lab \
  --project=PROJECT_ID \
  --subnet-mode=custom \
  --bgp-routing-mode=global \
  --mtu=1460
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       GLOBAL

Flags. --subnet-mode=custom means no subnets are created for you. --bgp-routing-mode chooses whether dynamic routes apply to the region of the Cloud Router (regional, the default) or to all regions (global). --mtu sets the maximum transmission unit (1460 is the default; 1500 and 8896 are supported values, check the help for your SDK). Common errors. Invalid value for field 'resource.name' means the name must start with a lowercase letter and use only lowercase letters, digits and hyphens. Production use. Network names are chosen once (for example vpc-hub-prod) and created by Terraform.

gcloud compute networks subnets create (free)

Purpose. Creates a regional subnet with a primary range. Turn on Private Google Access here, so VMs without external IPs can reach Google APIs.

gcloud compute networks subnets create snet-lab-REGION \
  --project=PROJECT_ID \
  --network=vpc-lab \
  --region=REGION \
  --range=10.16.0.0/24 \
  --enable-private-ip-google-access
Created [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/subnetworks/snet-lab-REGION].
NAME              REGION    NETWORK  RANGE          STACK_TYPE  IPV6_ACCESS_TYPE  INTERNAL_IPV6_PREFIX  EXTERNAL_IPV6_PREFIX
snet-lab-REGION   REGION    vpc-lab  10.16.0.0/24   IPV4_ONLY

Flags. --range is the primary IPv4 range in CIDR form. --enable-private-ip-google-access allows Google API access without an external IP. --enable-flow-logs turns on VPC Flow Logs for this subnet; this produces log data that is billed as Cloud Logging ingestion, so use it deliberately. Common errors. Invalid IPv4 range ... overlaps with existing subnet or Requested subnet range conflicts with ... means another subnet in the same VPC (or a peered VPC) already covers part of this range.

gcloud compute networks subnets describe (free, read only)

Purpose. Verifies the range, the gateway and the Private Google Access flag of a subnet.

gcloud compute networks subnets describe snet-lab-REGION --region=REGION --project=PROJECT_ID \
  --format="yaml(name,ipCidrRange,gatewayAddress,privateIpGoogleAccess,network)"
gatewayAddress: 10.16.0.1
ipCidrRange: 10.16.0.0/24
name: snet-lab-REGION
network: https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/networks/vpc-lab
privateIpGoogleAccess: true

gcloud compute routes list (free, read only)

Purpose. Shows the routing table of one network. You should see one subnet route per range, and the default route to the internet gateway.

gcloud compute routes list --project=PROJECT_ID --filter="network:vpc-lab" \
  --format="table(name,destRange,nextHopGateway.basename(),nextHopNetwork.basename(),priority)"
NAME                            DEST_RANGE    NEXT_HOP_GATEWAY         PRIORITY
default-route-aaaa1111bbbb2222  0.0.0.0/0     default-internet-gateway 1000
default-route-cccc3333dddd4444  10.16.0.0/24                           0
Production use. Keep these read commands in a runbook. When a team says "the network is broken", list networks, subnets, routes and firewall rules in that order before you touch anything. Check gcloud compute networks --help for the flags in your SDK version.

Lab 1: a custom network from scratch (about 10 minutes, free)

Goal. Create a custom-mode VPC network with one subnet, prove the routing table, and remove the default network in a lab project.

Prerequisites. A sandbox project (see Setup) linked to a billing account with a budget, roles/compute.networkAdmin or roles/owner on that project, and gcloud authenticated. IDs in the expected output are illustrative.

Cost. Free. Networks, subnets, routes and firewall rules are metadata. No VM is created in this lab.

  1. Set the project and region once:
    gcloud config set project PROJECT_ID
    gcloud config set compute/region REGION
  2. Enable the API and look at what Google created:
    gcloud services enable compute.googleapis.com
    gcloud compute networks list
    Verification. If the list shows default AUTO, the organization does not skip default networks. Note the result.
  3. Remove the default network and its four rules (commands in the previous tab). Verification. gcloud compute networks list now prints Listed 0 items.
  4. Create the custom network vpc-lab with --subnet-mode=custom --bgp-routing-mode=global. Verification. gcloud compute networks describe vpc-lab --format="value(autoCreateSubnetworks,routingConfig.routingMode)" prints an empty first value (false) and GLOBAL.
  5. Create snet-lab-REGION with range 10.16.0.0/24 and Private Google Access. Verification. Run the subnets describe command; the gateway is 10.16.0.1.
  6. Read the routes:
    gcloud compute routes list --filter="network:vpc-lab"
    Expected result. Two routes: the default route at priority 1000 and a subnet route for 10.16.0.0/24 at priority 0.
  7. Try an overlap on purpose:
    gcloud compute networks subnets create snet-overlap --network=vpc-lab --region=REGION --range=10.16.0.128/25
    Expected result. An error that the range overlaps with the existing subnet. This is the check that protects your IP plan inside one network.
  8. Try the implied firewall: you have no VM, so read the rules instead.
    gcloud compute firewall-rules list --filter="network:vpc-lab"
    Expected result. Listed 0 items. The only rules are the implied ones, which do not appear in the list.

Cleanup. Delete in reverse order:

gcloud compute networks subnets delete snet-lab-REGION --region=REGION --quiet
gcloud compute networks delete vpc-lab --quiet
Verify with gcloud compute networks list (empty). If you want to keep the project for Module 2, keep vpc-lab.

Lab 2 (optional): prevent the default network

If you have an organization and a lab folder, set constraints/compute.skipDefaultNetworkCreation to enforced on the folder, create a new project under it, enable the Compute Engine API, and run gcloud compute networks list. The list must be empty. Hour 3 covers the commands for setting a constraint.

Real cases

  • Auto mode that blocked a VPN. A team built production in the default network. When the company connected the project to on-premises over a VPN, the on-premises address plan used part of 10.128.0.0/9. Auto mode ranges cannot be changed, so the workloads had to be rebuilt in a new custom network. A custom network planned from the start avoids this migration.
  • One network per application. A group created a VPC network for each of forty applications. Every connection to on-premises needed its own routing and every shared service needed peering, which hit quotas and made changes slow. They moved to a small number of Shared VPC networks (Module 2) with subnets per application and firewall policy at the folder level.
  • Open SSH from the internet. A security review found default-allow-ssh and default-allow-rdp rules from 0.0.0.0/0 in dozens of projects. The fix was a two-part change: enforce compute.skipDefaultNetworkCreation and a hierarchical firewall policy (Module 4) that denies tcp:22 and tcp:3389 except from the Identity-Aware Proxy range.

Practices

  • Create networks only in custom mode. Name them by role and environment (vpc-hub-prod), and subnets by workload and region (snet-app-ew1).
  • Use global dynamic routing when you have hybrid connectivity, so that routes learned in one region are used in all regions.
  • Turn on Private Google Access on every subnet that has VMs without external IPs.
  • Turn on flow logs where you need them (for example a sampling rate of a few percent on hub subnets), not everywhere, since the log volume is billed.
  • Remove or block the default network before the first workload lands in a project.
  • Manage networks with Terraform so that a change is reviewed, and a console edit shows up as drift (Hour 7).
Security note. Do not use broad ingress allow rules from 0.0.0.0/0 for administration. Use the Identity-Aware Proxy range 35.235.240.0/20 with tcp:22 and tcp:3389 and require OS Login. Remember that creating a route to default-internet-gateway does not expose a VM unless it has an external IP or a NAT; the combination of route, external address and firewall rule is what makes it reachable.

Symptoms and first checks

SymptomLikely causeFirst check
VM in another region cannot be reached by internal IPIngress denied by default; no allow rulegcloud compute firewall-rules list --filter="network:NETWORK", then run a Connectivity Test
Invalid IPv4 range / range conflicts on subnet createOverlap with another subnet, peered VPC or reserved rangegcloud compute networks subnets list --network=NETWORK
The network resource ... is already being used on deleteInstances, routes, forwarding rules or firewall rules still use itgcloud compute instances list; gcloud compute routes list --filter="network:NETWORK"
New project already has a default networkConstraint compute.skipDefaultNetworkCreation not enforcedgcloud org-policies describe compute.skipDefaultNetworkCreation --project=PROJECT_ID --effective
VM has no internet although a default route existsNo external IP and no Cloud NATgcloud compute instances describe VM --format="value(networkInterfaces[0].accessConfigs)"
Compute Engine API has not been used in projectAPI not enabled yetgcloud services list --enabled --filter="name:compute.googleapis.com"
Dynamic routes are not used in another regionNetwork is in regional routing modegcloud compute networks describe NETWORK --format="value(routingConfig.routingMode)"

Triage order

  1. Confirm the project and network: gcloud config list project, gcloud compute networks list.
  2. Confirm the subnet and its range: subnets describe. Check the IP is inside the range and not one of the four reserved addresses.
  3. Check routes for the destination and the next hop.
  4. Check firewall rules and policies (direction, priority, target, source or destination).
  5. Use the Connectivity Tests tool in the console (Network Intelligence Center) to trace the path, and read VPC Flow Logs or firewall logs if enabled.

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

Official reading: VPC networks · Routes · Firewall rules overview · Subnets.

or score ≥ 70% on the quiz

Module 2 · Shared VPC

06–14 · One host project owns the network, service projects use its subnets, and IAM is granted per subnet
Shared VPCHost projectService projectsnetworkUser8 min
Learning objectives
  • Describe the roles of a host project and service projects, and which team owns what in a Shared VPC design.
  • Enable a host project, attach a service project, and grant subnet-level roles/compute.networkUser with gcloud.
  • Verify the attachment with list-associated-resources and diagnose why a shared subnet is not visible to a service project.

The short answer

Shared VPC (共享 VPC) lets an organization connect several projects to one common VPC network. The network lives in a host project (宿主项目). Other projects, called service projects (服务项目), are attached to the host. Their VMs and other resources can then use the host's subnets and get internal IP addresses from them. The network team controls routes, subnets and firewall; each application team still owns its own project, quotas, billing and workload IAM.

Why it is needed

  • Separation of duties. Network administrators manage the network once; developers manage applications. Neither role needs the other's permissions.
  • One address plan, one place for firewall and hybrid links. One VPN or Interconnect attachment and one Cloud NAT serve every service project, instead of one per project.
  • Internal connectivity without peering. Resources in different service projects that use the same Shared VPC network reach each other by internal IP, subject to firewall rules.
  • Billing stays with the workload. VM cost is charged to the service project. Network costs (for example egress traffic) are charged to the project that holds the resource that generates them, so check the network pricing page for which project is billed in each case.

What: the roles and who holds them

Role or personGranted onWhat they can do
Shared VPC Admin (roles/compute.xpnAdmin)Organization or folderEnable a host project, attach and detach service projects. Also needs roles/resourcemanager.projectIamAdmin if they must delegate subnet access.
Network Admin (roles/compute.networkAdmin)Host projectCreate networks, subnets, routes, Cloud Router. Cannot edit firewall rules or SSL certificates.
Security Admin (roles/compute.securityAdmin)Host projectCreate and edit firewall rules and policies, SSL certificates.
Service Project Admin (roles/compute.networkUser)One subnet, or the whole host projectUse shared subnets from the service project: create VMs, instance templates, GKE clusters, internal load balancers in them.
Application teamService projectCompute, storage and application roles in their own project. No rights over the host project.

How it works internally

  1. Enable the host. An administrator with roles/compute.xpnAdmin runs gcloud compute shared-vpc enable HOST_PROJECT_ID. The project is marked as a Shared VPC host. The project must be in the same organization as the service projects.
  2. Attach service projects. gcloud compute shared-vpc associated-projects add SERVICE_PROJECT_ID --host-project=HOST_PROJECT_ID links the service project. Each service project can have only one host.
  3. Grant subnet access. The administrator grants roles/compute.networkUser on specific subnets (the common, least-privilege choice) or on the whole host project to groups and service accounts that work in the service project.
  4. Create resources. In the service project, a user creates a VM and passes the subnet by its full path: projects/HOST_PROJECT_ID/regions/REGION/subnetworks/SUBNET. Compute Engine checks compute.subnetworks.use on that subnet before the VM is created.
  5. Service accounts used by services. For some products the account that needs networkUser is not a human. It is a service agent: for managed instance groups and instance templates it is the Google APIs service account PROJECT_NUMBER@cloudservices.gserviceaccount.com; for GKE it also includes the GKE service agent, which needs roles/container.hostServiceAgentUser on the host project. Check the product documentation for the exact agents.

When to use Shared VPC and when not to

SituationChoice
Many teams, one organization, central network team, hybrid connectivityShared VPC (a host project per environment, such as prod and non-prod)
Two organizations, or a partner project in another organizationVPC Network Peering or Private Service Connect, since Shared VPC works only inside one organization
A single small team and one projectA normal VPC network in that project is fine
Need a very hard isolation between workloadsSeparate VPC networks (maybe separate host projects) and a controlled path between them

What it is confused with

Often confused withDifference
VPC Network PeeringPeering connects two separate networks, each owned by its own project; control stays split. Shared VPC puts all resources in one network under one owner. Peering is not transitive; Shared VPC has one network.
Resource sharing in AWS RAMRAM shares subnets with other AWS accounts in a similar way, but in Google Cloud the sharing is a first-class feature with host and service roles and subnet-level IAM.
Cross-project IAM onlyIAM alone cannot place a VM from project A on a network of project B. Shared VPC is what enables that.

Common misunderstandings

"Shared VPC works without an organization." It does not. The host and service projects must be in the same organization. In a personal project with no organization you can only read about it; use a normal VPC (Module 1) for hands-on work.
"networkUser on the host project is the safe default." It gives access to every subnet in the host project, including subnets of other teams. Prefer the per-subnet grant, and use groups, not individual accounts.
"The firewall lives in the service project." Firewall rules and policies that apply to the shared network are created in the host project (or at the folder or organization). A service project owner cannot open a port for their own VMs unless you delegate the right, which weakens central control.
Host project prj-net-hub-prod VPC network vpc-hub-prod (custom mode) snet-app-ew1 10.16.0.0/20 snet-data-ew1 10.16.16.0/20 Firewall policy · routes · Cloud NAT · Cloud Router Owned by the network team Service project prj-app-a-prod VMs, instance groups, GKE Uses subnet snet-app-ew1 only Group: grp-app-a gets networkUser Own billing, quotas, workload IAM Service project prj-app-b-prod VMs, Cloud SQL private IP Uses subnet snet-data-ew1 only Group: grp-app-b gets networkUser Own billing, quotas, workload IAM attached service project attached service project Arrows: service-project resources take their internal IP from the host subnet they are allowed to use.

Figure 1. One host project, one network, two service projects. Each service project sees only the subnets on which its principals hold roles/compute.networkUser.

Notice who owns what: the host box holds the network objects and the shared controls, and the service boxes hold only workloads. Subnet-level grants are what stop team A from placing VMs in team B's subnet.

Organization Folder: network xpnAdmin held by the network group Folder: production app teams, networkUser per subnet prj-net-hub-prod (host) prj-app-a-prod (service) associated-projects add

Figure 2. The host project and the service projects sit in different folders. The attachment is an association, not a parent-child relationship.

The animation follows a Shared VPC administrator enabling the host and attaching a service project, then a developer creating a VM in the service project. The key interaction is the IAM check on the subnet: the VM is created only if the caller has compute.subnetworks.use on that subnet.

These commands need an organization. Run them with an identity that holds roles/compute.xpnAdmin on the organization or a folder. Enabling Shared VPC, attaching projects and IAM bindings are metadata operations and are free.

gcloud compute shared-vpc enable (free)

Purpose. Turns a project into a Shared VPC host project. The Compute Engine API must already be enabled in the host project.

gcloud compute shared-vpc enable HOST_PROJECT_ID
Updated [https://www.googleapis.com/compute/v1/projects/HOST_PROJECT_ID].

Common errors. Required 'compute.organizations.enableXpnHost' permission means you lack roles/compute.xpnAdmin (granted on the organization or a folder). Project ... is not in an organization means Shared VPC cannot be used there. Production use. The platform pipeline enables hosts once, in code; people do not run it by hand.

gcloud compute shared-vpc associated-projects add (free)

Purpose. Attaches a service project to the host project.

gcloud compute shared-vpc associated-projects add SERVICE_PROJECT_ID --host-project=HOST_PROJECT_ID
Updated [https://www.googleapis.com/compute/v1/projects/HOST_PROJECT_ID].

Flags. --host-project is required and names the host. Common errors. Project ... is already a host project (a host cannot be a service project), or Cannot attach: project is already associated with another host. Detach first, with associated-projects remove, after you remove all resources that use the shared network.

gcloud compute shared-vpc list-associated-resources (free, read only)

Purpose. Lists the service projects attached to a host. Run it after every change as proof.

gcloud compute shared-vpc list-associated-resources HOST_PROJECT_ID
RESOURCE_ID           RESOURCE_TYPE
SERVICE_PROJECT_ID    PROJECT

gcloud compute shared-vpc get-host-project (free, read only)

Purpose. Run from the service side: shows which host a service project is attached to. An empty result means it is not attached.

gcloud compute shared-vpc get-host-project SERVICE_PROJECT_ID
kind: compute#project
name: HOST_PROJECT_ID
xpnProjectStatus: HOST

gcloud compute networks subnets add-iam-policy-binding (free)

Purpose. Grants roles/compute.networkUser on one subnet to a group. This is the least-privilege way to share a subnet.

gcloud compute networks subnets add-iam-policy-binding snet-app-REGION \
  --project=HOST_PROJECT_ID \
  --region=REGION \
  --member="group:GROUP_EMAIL" \
  --role="roles/compute.networkUser"
Updated IAM policy for subnetwork [snet-app-REGION].
bindings:
- members:
  - group:GROUP_EMAIL
  role: roles/compute.networkUser
etag: BwYabc123XYZ=
version: 1

Flags. --member has the form group:, user:, or serviceAccount:. Common errors. Policy update access denied means you need compute.subnetworks.setIamPolicy (for example via roles/compute.networkAdmin or roles/owner on the host project). Note. If the group is not a user of the service project's service accounts, VM creation still fails for the service accounts; grant the role to those accounts as the product requires.

gcloud compute networks subnets get-iam-policy and list-usable (free, read only)

Purpose. get-iam-policy shows who can use a subnet. list-usable, run against the host project by a service project user, lists the subnets that the caller may use.

gcloud compute networks subnets get-iam-policy snet-app-REGION --project=HOST_PROJECT_ID --region=REGION
gcloud compute networks subnets list-usable --project=HOST_PROJECT_ID
PROJECT          REGION  NETWORK    SUBNET          RANGE
HOST_PROJECT_ID  REGION  vpc-hub    snet-app-REGION 10.16.0.0/20

gcloud compute instances create with a shared subnet (write, metered)

Purpose. Creates a VM in the service project on a shared subnet. A VM costs money while it exists. This is the check that everything above works; do it only in a lab, with the smallest machine type, and delete the VM right afterwards.

gcloud compute instances create vm-shared-test \
  --project=SERVICE_PROJECT_ID \
  --zone=ZONE \
  --machine-type=e2-micro \
  --subnet=projects/HOST_PROJECT_ID/regions/REGION/subnetworks/snet-app-REGION \
  --no-address
Created [https://www.googleapis.com/compute/v1/projects/SERVICE_PROJECT_ID/zones/ZONE/instances/vm-shared-test].
NAME            ZONE  MACHINE_TYPE  PREEMPTIBLE  INTERNAL_IP  EXTERNAL_IP  STATUS
vm-shared-test  ZONE  e2-micro                   10.16.0.2                 RUNNING

Flags. --subnet must be the full path when the subnet is in another project; --no-address skips the external IP. Common errors. Required 'compute.subnetworks.use' permission for 'projects/HOST/regions/REGION/subnetworks/SUBNET' means the caller lacks networkUser on that subnet. Cost is low (usually well under a few USD per day for one small VM), but budgets only alert, they do not cap spend.

Production use. Use list-associated-resources in a nightly check: it must match the project factory's list. A service project attached outside the pipeline is a finding. Check gcloud compute shared-vpc --help for the flags in your SDK version.

Lab 2: host project, service project, subnet-level access (about 15 minutes, free to low cost)

Goal. Enable a host project, attach a service project, grant subnet access to a group, and verify that the service project can see the subnet.

Prerequisites. An organization, a lab folder, two lab projects under it (HOST_PROJECT_ID and SERVICE_PROJECT_ID) linked to a billing account with a budget, the Compute Engine API enabled in both, and an identity with roles/compute.xpnAdmin on the folder or organization and roles/compute.networkAdmin on the host project. A lab group GROUP_EMAIL exists. IDs in the expected output are illustrative.

Without an organization. You cannot enable Shared VPC. Do steps 1, 2 and 4 on one project (create the network and subnet, read the IAM policy of the subnet), and read the rest as a walkthrough. Do not try a trial organization with real data.

Cost. Free for the steps below. Step 7 creates one small VM and is optional; it is low cost and is deleted in the cleanup.

  1. Create the network in the host project:
    gcloud compute networks create vpc-hub --project=HOST_PROJECT_ID --subnet-mode=custom --bgp-routing-mode=global
    gcloud compute networks subnets create snet-app-REGION --project=HOST_PROJECT_ID --network=vpc-hub --region=REGION --range=10.16.0.0/20 --enable-private-ip-google-access
    Verification. gcloud compute networks subnets describe snet-app-REGION --project=HOST_PROJECT_ID --region=REGION --format="value(ipCidrRange)" prints 10.16.0.0/20.
  2. Enable the host: gcloud compute shared-vpc enable HOST_PROJECT_ID. Verification. Run gcloud compute projects describe HOST_PROJECT_ID --format="value(xpnProjectStatus)", which prints HOST.
  3. Attach the service project: gcloud compute shared-vpc associated-projects add SERVICE_PROJECT_ID --host-project=HOST_PROJECT_ID. Verification. gcloud compute shared-vpc list-associated-resources HOST_PROJECT_ID lists SERVICE_PROJECT_ID.
  4. Before any grant, look at what the service project can use:
    gcloud compute networks subnets list-usable --project=HOST_PROJECT_ID
    Expected result. Empty for a principal that has no networkUser (a project owner of the service project does not see host subnets automatically).
  5. Grant the subnet role to the group with subnets add-iam-policy-binding as in the command tab. Verification. gcloud compute networks subnets get-iam-policy snet-app-REGION --project=HOST_PROJECT_ID --region=REGION shows roles/compute.networkUser for GROUP_EMAIL.
  6. As a member of the group (or with impersonation of a lab service account that has the role), run list-usable again. Expected result. The subnet snet-app-REGION is listed.
  7. Optional. Create vm-shared-test in the service project on the shared subnet (command tab). Verification. gcloud compute instances describe vm-shared-test --project=SERVICE_PROJECT_ID --zone=ZONE --format="value(networkInterfaces[0].network,networkInterfaces[0].networkIP)" shows the host network URL and an address from 10.16.0.0/20.
  8. Negative test: remove the binding (remove-iam-policy-binding) and try to create a second VM. Expected result. The error Required 'compute.subnetworks.use' permission. Restore the binding.

Cleanup, in this order.

gcloud compute instances delete vm-shared-test --project=SERVICE_PROJECT_ID --zone=ZONE --quiet
gcloud compute shared-vpc associated-projects remove SERVICE_PROJECT_ID --host-project=HOST_PROJECT_ID
gcloud compute shared-vpc disable HOST_PROJECT_ID
gcloud compute networks subnets delete snet-app-REGION --project=HOST_PROJECT_ID --region=REGION --quiet
gcloud compute networks delete vpc-hub --project=HOST_PROJECT_ID --quiet

Verification. gcloud compute shared-vpc list-associated-resources HOST_PROJECT_ID returns nothing before you disable the host. If associated-projects remove fails, a resource in the service project still uses the shared network; delete it first.

Real cases

  • Prod and non-prod host projects. A typical enterprise creates two or more hosts, for example one for production and one for non-production, each with its own network, firewall policy and hybrid links. Service projects of the same environment attach to the matching host. This limits the blast radius of a network mistake, and gives non-production a place to test firewall and routing changes first.
  • Subnet per team, not per project. A retail platform gave each business unit a subnet in each region and granted networkUser to the unit's group only on those subnets. When one unit grew, the network team added a subnet and a binding through Terraform; no other team was affected.
  • GKE on Shared VPC. A platform team ran GKE clusters in service projects. They created secondary ranges for pods and services in the host subnet (Module 3), granted the GKE service agent the right roles on the host, and kept cluster admin separate from network admin. Missing roles/container.hostServiceAgentUser was the first problem they hit.

Practices

  • Put host projects in a network folder. Give roles/compute.xpnAdmin to a small group at that folder, not at the organization, if you can.
  • Use the Organization Policy constraints constraints/compute.restrictSharedVpcHostProjects and constraints/compute.restrictSharedVpcSubnetworks to say which hosts and subnets projects may use. This stops a team from attaching to an unauthorized host.
  • Grant networkUser per subnet, to groups. Review the bindings in the same pull request that creates a subnet.
  • Do not put workloads in the host project, apart from network objects. A VM there is outside the separation of duties.
  • Track every attachment in code, and compare list-associated-resources to the project factory list regularly.
Security note. Anyone with roles/compute.xpnAdmin or roles/compute.networkAdmin on the host can change the network for every service project. Keep these roles in a small reviewed group, audit with Cloud Audit Logs (Hour 6), and require approval for changes made by a pipeline identity.

Symptoms and first checks

SymptomLikely causeFirst check
Shared subnet not listed in the service projectNo roles/compute.networkUser on the subnet for the caller; or the project is not attachedgcloud compute networks subnets get-iam-policy SUBNET --region=REGION --project=HOST_PROJECT_ID; list-associated-resources
Required 'compute.subnetworks.use' permissionCaller (user or service account) lacks networkUser on that subnetIdentify the caller in the error or the audit log, then compare with the subnet policy
Managed instance group or GKE fails to create nodesThe service agent (Google APIs service account, GKE service agent) lacks networkUser or hostServiceAgentUser in the hostRead the operation error; list the host project IAM policy for PROJECT_NUMBER@cloudservices.gserviceaccount.com
shared-vpc enable fails with a permission errorNo compute.organizations.enableXpnHost (missing roles/compute.xpnAdmin)gcloud organizations get-iam-policy ORG_ID or the folder policy, filtered to your identity
associated-projects add failsProject already a host, already attached elsewhere, or an Organization Policy blocks the hostgcloud compute shared-vpc get-host-project SERVICE_PROJECT_ID; gcloud org-policies describe compute.restrictSharedVpcHostProjects --project=SERVICE_PROJECT_ID --effective
associated-projects remove or disable failsResources in service projects still use the shared networkList instances and forwarding rules in service projects that reference the host network
VM created but cannot reach other VMsFirewall in the host project (ingress denied)gcloud compute firewall-rules list --project=HOST_PROJECT_ID --filter="network:vpc-hub"

Triage order

  1. Is the service project attached? get-host-project from the service side.
  2. Which identity made the call? Read the error text and the audit log; a service agent is a different principal from the person.
  3. Is networkUser granted on the correct subnet (and region)? Use get-iam-policy.
  4. Do Organization Policy constraints restrict hosts or subnets? Use org-policies describe --effective.
  5. Only then look at routes and firewall in the host project.

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

Official reading: Shared VPC overview · Provision Shared VPC · VPC Network Peering.

or score ≥ 70% on the quiz

Module 3 · IP address plan

14–21 · CIDR planning without overlaps across VPCs and on-premises, secondary ranges for GKE, and reserved ranges
CIDRNo overlapsSecondary rangesIPAM7 min
Learning objectives
  • Plan non-overlapping RFC 1918 ranges for environments, regions, GKE pods and services, and on-premises, and record the plan as a table.
  • Create subnets with primary and secondary ranges using gcloud, and read the ranges back.
  • Explain what overlap breaks (peering, VPN, Interconnect, NAT) and how to detect it before it happens.

The short answer

An IP address plan is a table that says which part of the private address space belongs to which environment, region, network, subnet and purpose. You decide it once, before the first subnet is created, because an IP range of a subnet is hard to change when VMs, load balancers and hybrid links depend on it. The two failure modes are overlap (two networks use the same addresses, so they cannot be connected) and exhaustion (a subnet is too small for growth, for example a GKE cluster that needs more pods).

Why it is needed

  • Connectivity. VPC Network Peering, Network Connectivity Center, Cloud VPN and Cloud Interconnect can only connect address spaces that do not overlap.
  • Policy. Firewall rules, routes, and on-premises firewall rules often match on ranges. A clean plan lets you write one rule for "all production" instead of many rules.
  • Cost of change. Deleting and rebuilding a subnet means moving the workloads in it. A plan with room to grow avoids that.
  • Mergers. Companies join, and both sides often used 10.0.0.0/8 in a hurry. A plan that keeps clear blocks free lets you absorb the next network.

What: the private address space

BlockSizeNotes for Google Cloud
10.0.0.0/8about 16.7 million addressesThe usual choice for the landing zone. Avoid 10.128.0.0/9 if any auto mode network may exist, because auto mode uses it.
172.16.0.0/12about 1 million addressesGood for smaller estates. Careful with Docker, which uses 172.17.0.0/16 on a host by default.
192.168.0.0/1665,536 addressesOften used in offices and home labs, and so likely to overlap with remote users' networks. Keep out of the cloud plan if you can.
100.64.0.0/10 (RFC 6598)about 4 million addressesShared address space, sometimes used for GKE pod ranges when the RFC 1918 space is full. Check the current VPC documentation for valid subnet ranges before you rely on it.

How it works: sizes and reserved addresses

PrefixAddressesUsable (4 reserved)Typical use
/1665,53665,532Large region block, GKE pods for a cluster
/204,0964,092An application tier in a region
/221,0241,020GKE nodes, or GKE Services range
/24256252Small tier, proxy-only subnet, management
/281612Small utility ranges. The smallest primary range is /29 (8 addresses, 4 usable).

A /n block holds 2(32 − n) addresses. Every primary IPv4 range loses four: the network address, the default gateway (the first usable address, for example 10.16.0.1), the second-to-last, and the broadcast address.

How it works: secondary ranges and GKE

A VPC-native GKE cluster (the default and recommended mode) takes three kinds of addresses:

  • Nodes from the subnet's primary range, one address per node.
  • Pods from a secondary range. By default GKE gives each node a block of pod addresses (a /24 in the standard maximum of 110 pods per node), so the pod range must be sized for the maximum number of nodes times that block. Pod range exhaustion is a common reason clusters cannot scale.
  • Services (ClusterIP) from a second secondary range. A /20 gives about 4,000 Services, and a /22 about 1,000. The Services range cannot be changed in an existing cluster.

You define secondary ranges when you create the subnet (--secondary-range=pods=10.64.0.0/16,services=10.68.0.0/22) or add them later with gcloud compute networks subnets update --add-secondary-ranges. Check gcloud compute networks subnets update --help for the flags in your SDK version. Name the ranges per cluster, for example pods-prod-a, so ranges are not shared by accident.

An example plan

BlockOwner / purposeNotes
10.0.0.0/12On-premises and branch officesReserved. Never used in the cloud.
10.16.0.0/12Google Cloud productionSplit into /16 per region: 10.16.0.0/16 europe-west1, 10.17.0.0/16 us-east1, ...
10.32.0.0/12Google Cloud non-productionSame layout as production for easy review.
10.48.0.0/12Shared services, hub, managementProxy-only subnets, private services access ranges, test.
10.64.0.0/10GKE pods and Services (secondary ranges)Never routed on-premises, so it can be reused only when clusters use route-limited designs. Document that choice.
10.128.0.0/9Unused. Reserved to avoid the auto mode blockKeep free.
Rule of thumb. Allocate on bit boundaries so that a region, an environment or a purpose is one prefix. Then one firewall rule or one route advertisement covers it, and you can summarize on the on-premises router.

Private services access and other reserved ranges

Managed services such as Cloud SQL private IP and Memorystore use private services access: you reserve an internal range in the VPC network with gcloud compute addresses create --global --purpose=VPC_PEERING --prefix-length=16, and then create a peering connection to the service producer. That range must be outside all subnets and on-premises ranges. Other products, such as internal Application Load Balancers, need a proxy-only subnet (a /23 or larger is common guidance, check the documentation) in each region. Plan them in the same table.

When to use what

  • Large, regular blocks if you expect hybrid connectivity and many networks.
  • Smaller blocks and NAT between networks only when merging with a partner you do not control; it is an exception, not a design.
  • IPv6 (dual-stack subnets) when workloads or clients need it. Plan it in the same table; Google Cloud allocates the IPv6 ranges for you.

What it is confused with

Often confused withDifference
Subnet = networkThe VPC network has no range. Subnets do. Plan at subnet level.
Public IP planningExternal addresses are assigned by Google (ephemeral or reserved). You plan private ranges.
Using NAT to hide overlapPossible with special designs, but it is a workaround. Standard Cloud NAT is for egress to the internet, not for translating between private networks.

Common misunderstandings

"Separate VPCs can use the same ranges, since they are isolated." True only while they never connect. The day you add peering, a hub or a VPN, the overlap blocks you.
"I can add address space later if I need to." You can expand a primary range with expand-ip-range only if the adjacent space is free, and you cannot shrink it. The Services range of a GKE cluster is fixed. Leave room around every block.
"On-premises will tell me what it uses." Ask for the full list of on-premises, VPN user, partner and cloud ranges first, and check them against the plan. Remote-user VPN pools are often forgotten.
10.0.0.0/8 · one private block, divided by bit boundaries 10.0.0.0/12 On-premises never in cloud 10.16.0.0/12 GCP production /16 per region 10.32.0.0/12 GCP non-production /16 per region 10.48.0.0/12 Shared and hub proxy-only, PSA 10.64.0.0/10 GKE pods, Services secondary ranges Production 10.16.0.0/12 split by region 10.16.0.0/16 europe-west1 · 10.17.0.0/16 us-east1 · 10.18.0.0/16 asia-east1 each /16 holds /20 subnets per tier: 10.16.0.0/20, 10.16.16.0/20, ... Subnet snet-gke-prod primary 10.16.32.0/22 (nodes) pods 10.64.0.0/16 · services 10.68.0.0/22 Check before every allocation: no overlap with other VPCs, peerings, on-premises, VPN pools, private services access ranges, and the 10.128.0.0/9 auto mode block. Keep spare blocks free.

Figure 1. An example address plan. Blocks follow bit boundaries, so each environment, region or purpose is a single prefix.

Read the picture from top to bottom: one supernet, a block per owner, then a regional split and finally a subnet with secondary ranges. Every arrow is a decision recorded in the plan table.

Subnet snet-gke-prod · region europe-west1 Primary range 10.16.32.0/22 GKE nodes, internal load balancer IPs 1,020 usable Secondary range pods 10.64.0.0/16 One /24 per node (110 pods per node default) about 256 nodes Secondary range services 10.68.0.0/22 ClusterIP Services fixed at cluster creation about 1,000 Services

Figure 2. One subnet, three ranges. The pod range must be sized for the maximum number of nodes; the Services range cannot grow in an existing cluster.

The animation shows a request for address space going through the plan before any command runs. The gcloud call then asks the network to create the subnet, and the network validates the new ranges against everything it already knows about. The last step records the allocation in the plan, which is the step teams forget.

All commands in this tab only create or read network metadata, so they are free. Use a lab project in which you created vpc-lab (Module 1). Replace PROJECT_ID and REGION. The plan itself is a table in a repository, not a command; a tool such as a spreadsheet, a Terraform variables file or an IPAM product can hold it.

gcloud compute networks subnets list (free, read only)

Purpose. The inventory of ranges in a project. Compare it with your plan table.

gcloud compute networks subnets list --project=PROJECT_ID \
  --format="table(name,region.basename(),network.basename(),ipCidrRange,secondaryIpRanges[].ipCidrRange.list())" \
  --sort-by=ipCidrRange
NAME              REGION    NETWORK  IP_CIDR_RANGE   SECONDARY_IP_RANGES
snet-app-REGION   REGION    vpc-lab  10.16.0.0/20
snet-gke-REGION   REGION    vpc-lab  10.16.32.0/22   10.64.0.0/16,10.68.0.0/22

Flags. --format with table(...) chooses columns; --sort-by sorts on a field, which makes gaps and overlaps easy to see. Production use. Export this output nightly from every host project into the IPAM table, and alert if it differs.

gcloud compute networks subnets create with secondary ranges (free)

Purpose. Creates a subnet with primary and two secondary ranges for GKE.

gcloud compute networks subnets create snet-gke-REGION \
  --project=PROJECT_ID \
  --network=vpc-lab \
  --region=REGION \
  --range=10.16.32.0/22 \
  --secondary-range=pods=10.64.0.0/16,services=10.68.0.0/22 \
  --enable-private-ip-google-access
Created [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/subnetworks/snet-gke-REGION].
NAME             REGION   NETWORK  RANGE          STACK_TYPE  IPV6_ACCESS_TYPE  INTERNAL_IPV6_PREFIX  EXTERNAL_IPV6_PREFIX
snet-gke-REGION  REGION   vpc-lab  10.16.32.0/22  IPV4_ONLY

Flags. --secondary-range takes NAME=RANGE pairs separated by commas. The names are what you pass to GKE as the pod and Services ranges. Common errors. Invalid IPv4 range ... overlaps if any range (primary or secondary) overlaps another range in the same VPC, in a peered VPC, or in a reserved private services range.

gcloud compute networks subnets describe (free, read only)

Purpose. Shows the secondary ranges of one subnet.

gcloud compute networks subnets describe snet-gke-REGION --project=PROJECT_ID --region=REGION \
  --format="yaml(ipCidrRange,secondaryIpRanges)"
ipCidrRange: 10.16.32.0/22
secondaryIpRanges:
- ipCidrRange: 10.64.0.0/16
  rangeName: pods
- ipCidrRange: 10.68.0.0/22
  rangeName: services

gcloud compute networks subnets expand-ip-range (free, one-way)

Purpose. Grows the primary range of a subnet in place when it is almost full. The change cannot be undone, so confirm that the neighbouring space is free in the plan first.

gcloud compute networks subnets expand-ip-range snet-app-REGION --project=PROJECT_ID --region=REGION --prefix-length=20
You are about to expand the IP range of subnetwork [snet-app-REGION] to [/20]. This operation is not reversible.
Do you want to continue (Y/n)?  Y
Updated [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/subnetworks/snet-app-REGION].

Flags. --prefix-length is the new, shorter prefix. Common errors. An error that the new range conflicts with another subnet or route means the neighbouring block is not free.

gcloud compute addresses create --purpose=VPC_PEERING (free to reserve)

Purpose. Reserves an internal range for private services access (Cloud SQL and similar managed services). The reservation itself is a metadata change; the services that later use it are billed.

gcloud compute addresses create psa-range-lab \
  --project=PROJECT_ID \
  --global \
  --purpose=VPC_PEERING \
  --prefix-length=24 \
  --network=vpc-lab \
  --addresses=10.48.0.0
Created [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/addresses/psa-range-lab].

Flags. --addresses pins the start address so that the range follows your plan; without it Google picks a free block. Check gcloud compute addresses create --help for the flags in your SDK version.

Production use. Put the CIDR table in a repository, review changes by pull request, and have the pipeline fail when a new range overlaps an existing one. Python's ipaddress module, or Terraform's cidrsubnet() and cidrhost() functions, can check and compute ranges.

Lab 3: plan, create and prove an overlap (about 15 minutes, free)

Goal. Write a small address plan, create subnets with secondary ranges from it, and prove that the network rejects an overlapping range.

Prerequisites. The lab project and the custom network vpc-lab from Module 1 (create it again if you cleaned up). IDs in the expected output are illustrative.

Cost. Free. Only subnets and an address reservation are created. No VM or cluster is created.

  1. Write the plan as a text table (a file or a note) with these rows: 10.16.0.0/20 app tier europe-west1, 10.16.64.0/20 data tier europe-west1 (not created in this lab), 10.16.32.0/22 GKE nodes with pods 10.64.0.0/16 and services 10.68.0.0/22, and 10.48.0.0/24 reserved for private services access. Check on paper that none of the five ranges overlap.
  2. Create the app subnet if it does not exist (Module 1). Then create the GKE subnet with the secondary ranges using the command in the previous tab. Verification. gcloud compute networks subnets describe snet-gke-REGION --region=REGION --format="yaml(ipCidrRange,secondaryIpRanges)" shows the three ranges from your plan.
  3. Make a deliberate error: try to create snet-clash with --range=10.64.0.0/20, which is inside the pods range of snet-gke-REGION. Expected result. The command fails with an overlap error. Secondary ranges are part of the overlap check.
  4. Reserve the private services access range:
    gcloud compute addresses create psa-range-lab --global --purpose=VPC_PEERING --prefix-length=24 --network=vpc-lab --addresses=10.48.0.0
    Verification. gcloud compute addresses list --global --filter="name=psa-range-lab" --format="table(name,address,prefixLength,purpose)" shows 10.48.0.0, 24, VPC_PEERING.
  5. Try to create a subnet inside the reserved range: gcloud compute networks subnets create snet-psa-clash --network=vpc-lab --region=REGION --range=10.48.0.0/25. Expected result. The command fails, because the range is reserved for peering.
  6. Expand a range: gcloud compute networks subnets expand-ip-range snet-app-REGION --region=REGION --prefix-length=19, after you confirm that 10.16.0.0/19 is free in your plan (in this lab no data subnet exists yet, so it is). Verification. subnets describe now shows 10.16.0.0/19. Lesson. Expansion works only into free space, and it cannot be undone. If you had created the data tier at 10.16.16.0/20 first, the command would fail with a conflict. In your plan, leave a sibling block free for growth.
  7. List all ranges sorted, and compare them with the plan: gcloud compute networks subnets list --network=vpc-lab --sort-by=ipCidrRange.

Expected result. Two created subnets, one reserved range, three refused operations that prove the checks, and a plan table that matches the output.

Cleanup.

gcloud compute addresses delete psa-range-lab --global --quiet
gcloud compute networks subnets delete snet-gke-REGION --region=REGION --quiet
gcloud compute networks subnets delete snet-app-REGION --region=REGION --quiet

Verification. gcloud compute networks subnets list --network=vpc-lab returns Listed 0 items. Keep vpc-lab if the next module's lab needs it, or delete it as in Module 1.

Real cases

  • Overlap found at VPN time. A company planned a hub VPN to its main data centre and found that two Google Cloud projects used 10.10.0.0/16, which the data centre also used. The team needed a migration to new ranges, with weeks of work. After this they created a central address plan, with a review step in the project factory.
  • GKE out of pod addresses. A cluster was created with a /20 pod range. With the default of a /24 per node, it could hold only 16 nodes, and autoscaling stopped at that number. New clusters now use a planned /16 or larger pod range per cluster and a lower maximum pods per node for small workloads, which reduces the block size per node.
  • Peering that conflicted with a managed service. A team reserved a private services access range that overlapped with a planned subnet in a different region. Cloud SQL private IP failed to create. The plan table now has a dedicated row for private services access ranges and proxy-only subnets, in each environment.

Practices

  • Keep the plan in version control. One owner (the network team) approves every range. Every range has an owner, a purpose and a date.
  • Leave 30 to 50 percent of each block unallocated, and never allocate the last part of a block to a different purpose.
  • Do not use auto mode networks. Do not use 10.128.0.0/9 for anything.
  • Give GKE its own pod and Services ranges per cluster, sized for the maximum node count, and name them for the cluster.
  • Include the remote-access VPN pool, partner ranges and other clouds in the plan, not only Google Cloud and the data centre.
  • Automate checks: a pipeline step that lists subnets in every host project and compares with the plan.
Security note. Clean ranges also make firewall policy simple and safe. A rule such as "deny ingress from 10.0.0.0/12 (on-premises) except to tcp:443" only works when the block really contains all on-premises addresses and nothing else. An untidy plan leads to broad allow rules, which are a security weakness.

Symptoms and first checks

SymptomLikely causeFirst check
Subnet create fails with an overlap errorRange overlaps a primary or secondary range, a peered VPC, or a reserved rangegcloud compute networks subnets list --sort-by=ipCidrRange; gcloud compute addresses list --global --filter="purpose=VPC_PEERING"
Peering or VPN route is not accepted or is silently missingOverlap between the networksgcloud compute networks peerings list and compare ranges on both sides
GKE cluster creation fails: not enough IP addresses in the rangePod or Services range too smallCompare cluster node count and maxPodsPerNode to the pod range size
Cannot add VMs: IP_SPACE_EXHAUSTED or similarSubnet full (remember 4 reserved)subnets describe, then expand-ip-range if the neighbour is free
Cloud SQL private IP fails to createPrivate services access range missing, exhausted, or overlappinggcloud services vpc-peerings list --network=NETWORK and gcloud compute addresses list --global
On-premises hosts cannot reach a subnet that is reachable from the cloudRoute not advertised, or an on-premises range is more specificCloud Router advertisements (Hour 5), on-premises route table
Internal load balancer creation failsNo proxy-only subnet in the regiongcloud compute networks subnets list --filter="purpose=REGIONAL_MANAGED_PROXY"

Triage order

  1. Name the two ranges that collide, with owners. Use the plan table first, the live list second.
  2. Decide which side can change. A new subnet is easy; a subnet with VMs, load balancers or a cluster is not.
  3. If a change is needed, create the new subnet with a correct range, move workloads, then delete the old one. Do not rely on NAT between private networks unless you must.
  4. Update the plan table and add a pipeline check so the same overlap cannot return.

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

Official reading: Subnets · GKE VPC-native clusters and alias IPs · Private services access · Best practices and reference architectures for VPC design.

or score ≥ 70% on the quiz

Module 4 · Hierarchical firewall policies

21–29 · Organization and folder firewall policies, priorities, allow, deny and goto_next, and associations to folders
Firewall policyPrioritygoto_nextAssociations8 min
Learning objectives
  • Explain how hierarchical firewall policies are evaluated before VPC firewall rules, and what allow, deny and goto_next do.
  • Create an organization firewall policy, add rules with priorities, and associate the policy with a folder using gcloud.
  • Choose between hierarchical policies and VPC-level rules, and design a safe guardrail rule set (SSH, RDP, health checks, IAP).

The short answer

A firewall policy (防火墙策略) is a named list of firewall rules. A hierarchical firewall policy is attached to the organization or to a folder, and it is evaluated before any firewall rule that a project owner creates in a VPC network. A central team can use it to enforce non-negotiable rules for every project below a node: block SSH and RDP from the internet, allow the load balancer health check ranges, allow the IAP range, and let the rest be decided at the VPC level.

Why it is needed

  • Guardrails that project owners cannot remove. A VPC firewall rule can be edited by anyone with roles/compute.securityAdmin on the project. A hierarchical rule can only be edited by someone with rights on the policy, which lives at the organization or in a security project.
  • One change, thousands of networks. Associating a policy with a folder applies it to every network in every project below.
  • Consistent baselines. Production, non-production and sandbox folders can have different policies, for example denying egress to the internet in production except through a proxy range.

What: the pieces

PieceMeaning
PolicyA container created in the organization (or in a folder). Has a short name, an ID and a list of rules. Created with gcloud compute firewall-policies create.
RulePriority, direction (INGRESS or EGRESS), match (source or destination ranges, layer 4 protocols and ports), action, targets, logging flag.
Actionallow, deny, goto_next. A fourth action, applying a security profile group for firewall inspection, belongs to the Cloud NGFW product and is outside this course.
TargetWhich VMs the rule applies to. Hierarchical rules can target all instances, VMs using specific service accounts (--target-service-accounts), or specific networks (--target-resources). Network tags are not used in hierarchical rules.
AssociationThe link between the policy and the node (organization or folder) where it applies.

How it works internally: evaluation order

  1. Traffic reaches a VM's network interface. Google Cloud evaluates the organization firewall policy first.
  2. Next the folder policies, from the topmost folder down to the folder that is the direct parent of the project. Each node can have one associated policy.
  3. Then the VPC-level rules and policies: VPC firewall rules and global network firewall policies (in a default order that you can change per network), then regional network firewall policies.
  4. If nothing matched, the implied rules apply: allow egress, deny ingress.

Inside a policy, rules are checked from the lowest priority number to the highest. The first matching rule decides: allow and deny end the evaluation, while goto_next continues with the next level. A rule that does not match is skipped. Priorities are integers (lower is stronger) and must be unique in a policy, so leave gaps (100, 200, 300, ...) so you can insert rules later.

What the actions mean in practice

ActionEffectTypical use
denyDrop the packet; nothing lower can allow itBlock SSH and RDP from the internet for every project; block known bad ranges
allowPass the packet; the VPC rules are not evaluatedAllow health check ranges and IAP so that nobody can break them by a mistake
goto_nextDelegate to the next levelSay "projects decide this port", or exclude a trusted range from a broad deny rule
Pattern: deny with exceptions. Put the exceptions at lower numbers than the deny. For example priority 100: allow tcp:22 from 35.235.240.0/20 (IAP). Priority 200: deny tcp:22 and tcp:3389 from 0.0.0.0/0. A packet from IAP matches rule 100 first and passes; anything else matches 200 and is dropped.

Hierarchical policy or VPC firewall rule?

NeedUse
A rule that every project must have and no project can overrideHierarchical policy at the organization or folder
A rule that depends on the application, such as "app tier talks to database tier on tcp:5432"VPC-level rule or network firewall policy in the host project, usually with service accounts or secure tags as targets
Different baseline for production and sandboxDifferent policies on different folders
Rule for one network onlyNetwork firewall policy, or a hierarchical rule with --target-resources naming the network

What it is confused with

Often confused withDifference
VPC firewall rules (gcloud compute firewall-rules)VPC rules belong to one network in one project. They can use network tags. They are evaluated after hierarchical policies.
Network firewall policiesAttach to a VPC network (global) or a region, not to the hierarchy. They give you the same rule model at the network level, with secure tags and FQDN or geolocation matches.
Organization Policy constraintsConstraints control API actions (who may create what). Firewall policies control packets at runtime. Both belong to guardrails but they are different systems.
Cloud ArmorCloud Armor filters web traffic at the edge of a load balancer. Firewall policies filter traffic to VM network interfaces inside the VPC.

Common misunderstandings

"An allow in the organization policy opens the port." It makes the packet pass the policy; the VM still needs to listen on the port. It also skips the VPC rules, so a broad allow can bypass a team's careful deny. Use goto_next when you want the project rules to decide.
"I can deny a port in a VPC rule and the organization allow will not matter." The organization policy is evaluated first, so an organization-level allow wins and the VPC deny is never reached.
"An association applies to one project." It applies to every project below the node, including projects created later. Test in a lab folder first, and use dry-run style review (read the rules and the logs) before associating a deny rule with a production folder.
"Rules in the policy apply instantly everywhere, so a mistake is easy to fix." Policies take effect within seconds, which is also the speed at which a bad deny can cut off access. Keep a break-glass path (the IAP allow) at a low number.
1. Organization policy fw-org-baseline 2. Folder policy fw-prod (folder production) 3. VPC-level rules firewall rules, network policies 4. Implied rules deny ingress · allow egress goto_next or no match goto_next or no match no match Organization policy fw-org-baseline (rules by priority) 100 INGRESS allow tcp:22,3389 from 35.235.240.0/20 (IAP) 110 INGRESS allow tcp from 130.211.0.0/22, 35.191.0.0/16 (health checks) 200 INGRESS deny tcp:22,3389 from 0.0.0.0/0 300 INGRESS deny all from known bad ranges 2147483645 INGRESS goto_next all (explicit hand-off, optional) Folder policy fw-prod (associated with folder production) 100 EGRESS deny all to 0.0.0.0/0 except the proxy range 200 INGRESS goto_next tcp:443,3306 from 10.0.0.0/8 First matching rule decides. Allow and deny stop evaluation; goto_next passes the packet to the next level. Association: one policy per node. Policy applies to all projects below it.

Figure 1. Evaluation order and an example rule set. Hierarchical policies come first; the VPC rules of a project only see what is delegated or not matched.

Follow the left column from top to bottom to see the levels, and the right column for the rules. The IAP allow at priority 100 sits above the deny at 200 on purpose: the exception must have a lower number than the broad deny.

Organization association: fw-org-baseline Folder: production association: fw-prod Folder: sandbox no own policy (org policy only) prj-app-a-prod prj-lab-1 prod projects: org policy, then fw-prod, then VPC rules sandbox projects: org policy, then VPC rules A node has at most one associated hierarchical policy.

Figure 2. Associations in the hierarchy. A project sees the policies of all its ancestors, from the organization down.

The animation traces three packets through the levels. The first is allowed by an exception rule that has a lower priority number than the broad deny. The second is handed on with goto_next and decided by a VPC rule. The third matches nothing and falls to the implied deny.

Hierarchical firewall policies need an organization. The identity needs roles/compute.orgFirewallPolicyAdmin to create and edit policies, and roles/compute.orgFirewallPolicyUser to associate or view them. Creating policies, rules and associations is a metadata operation and is free. Firewall rule logging is billed as Cloud Logging ingestion, so it is low cost for a lab but can grow in production. Check gcloud compute firewall-policies --help for the flags in your SDK version; the command group and its flags have changed over releases.

gcloud compute firewall-policies create (free)

Purpose. Creates a policy at the organization level (or in a folder with --folder).

gcloud compute firewall-policies create \
  --organization=ORG_ID \
  --short-name=fw-org-baseline \
  --description="Organization baseline: SSH and RDP guardrails"
Waiting for operation [operation-1700000000000-aaaa1111bbbb2222-cccc3333-dddd4444] to complete...done.
Created [https://www.googleapis.com/compute/v1/locations/global/firewallPolicies/1234567890123456789].

Flags. --organization (or --folder) is the parent where the policy is stored. --short-name is the name you use later with --organization to find it; the long numeric ID is the permanent identifier. Common errors. Required 'compute.firewallPolicies.create' permission means you lack roles/compute.orgFirewallPolicyAdmin on the organization.

gcloud compute firewall-policies list (free, read only)

Purpose. Finds the policy ID that later commands need.

gcloud compute firewall-policies list --organization=ORG_ID
ID                   SHORT_NAME        DESCRIPTION
1234567890123456789  fw-org-baseline   Organization baseline: SSH and RDP guardrails

gcloud compute firewall-policies rules create (free)

Purpose. Adds a rule to the policy. The first positional argument is the priority. Create the exception (allow IAP) before the deny.

gcloud compute firewall-policies rules create 100 \
  --firewall-policy=fw-org-baseline \
  --organization=ORG_ID \
  --direction=INGRESS \
  --action=allow \
  --layer4-configs=tcp:22,tcp:3389 \
  --src-ip-ranges=35.235.240.0/20 \
  --description="Allow IAP TCP forwarding" \
  --enable-logging

gcloud compute firewall-policies rules create 200 \
  --firewall-policy=fw-org-baseline \
  --organization=ORG_ID \
  --direction=INGRESS \
  --action=deny \
  --layer4-configs=tcp:22,tcp:3389 \
  --src-ip-ranges=0.0.0.0/0 \
  --description="Deny SSH and RDP from the internet"
Waiting for operation [operation-1700000000001-aaaa1111bbbb2222-cccc3333-dddd5555] to complete...done.
Waiting for operation [operation-1700000000002-aaaa1111bbbb2222-cccc3333-dddd6666] to complete...done.

Flags. --direction is INGRESS or EGRESS. --action is allow, deny or goto_next. --layer4-configs lists protocol:port items, or all. --src-ip-ranges for ingress and --dest-ip-ranges for egress. --target-service-accounts and --target-resources narrow the rule. --enable-logging logs matches (billed). Common errors. Priority ... already exists means that priority is taken, so pick another number. Using a rule that mixes IPv4 and IPv6 ranges is not allowed in one rule.

gcloud compute firewall-policies rules list and describe (free, read only)

Purpose. Reads the rules back in priority order.

gcloud compute firewall-policies rules list --firewall-policy=fw-org-baseline --organization=ORG_ID
PRIORITY  ACTION  DIRECTION  MATCH
100       allow   INGRESS    src_ip_ranges: 35.235.240.0/20; layer4: tcp:22,tcp:3389
200       deny    INGRESS    src_ip_ranges: 0.0.0.0/0; layer4: tcp:22,tcp:3389

The column layout depends on the SDK version; use --format=yaml if you need the full detail.

gcloud compute firewall-policies associations create (free, takes effect at once)

Purpose. Attaches the policy to a folder (or to the organization). From this moment the rules apply to all projects below it. Do this on a lab folder first.

gcloud compute firewall-policies associations create \
  --firewall-policy=fw-org-baseline \
  --organization=ORG_ID \
  --folder=FOLDER_ID \
  --name=assoc-lab-folder
Waiting for operation [operation-1700000000003-aaaa1111bbbb2222-cccc3333-dddd7777] to complete...done.

Flags. --folder is the node to attach to; use --organization alone as the target if you want to attach it to the organization (check the help for the exact form in your SDK). --name names the association. Common errors. An error that the target already has a policy means a node can hold only one; replace the old association first with associations delete.

gcloud compute firewall-policies associations list (free, read only)

Purpose. Shows what is attached to a folder or the organization.

gcloud compute firewall-policies associations list --folder=FOLDER_ID
NAME              FIREWALL_POLICY_ID   ATTACHMENT_TARGET
assoc-lab-folder  1234567890123456789  folders/FOLDER_ID

Seeing what applies to a VM (free, read only)

Purpose. gcloud compute instances network-interfaces get-effective-firewalls shows the effective rules for a VM interface, including inherited hierarchical rules. Check --help for the exact flags (instance name, zone, network interface) in your SDK version.

gcloud compute instances network-interfaces get-effective-firewalls VM_NAME --zone=ZONE --project=PROJECT_ID
Production use. Define policies in Terraform (resources google_compute_firewall_policy, google_compute_firewall_policy_rule, google_compute_firewall_policy_association), review rules by pull request, and apply them first to a non-production folder. Keep a runbook for removing an association in an emergency.

Lab 4: a guardrail policy on a lab folder (about 15 minutes, free)

Goal. Create an organization firewall policy with an IAP exception and an SSH and RDP deny, attach it to a lab folder, and read back the rules and the association.

Prerequisites. An organization, a lab folder FOLDER_ID with one lab project, an identity with roles/compute.orgFirewallPolicyAdmin and roles/compute.orgFirewallPolicyUser on the organization, and a budget set on the billing account. IDs in the expected output are illustrative. Do not associate the policy with the organization or with a production folder.

Without an organization. Hierarchical policies are not available. Do the same logic with VPC rules in your lab project: gcloud compute firewall-rules create allow-iap-ssh --network=vpc-lab --direction=INGRESS --action=allow --rules=tcp:22 --source-ranges=35.235.240.0/20 --priority=100 and a deny rule at priority 200 with --action=deny --source-ranges=0.0.0.0/0. Then use gcloud compute firewall-rules list --filter="network:vpc-lab" --sort-by=priority to check the order.

Cost. Free for the policy, rules and association. With --enable-logging on the IAP rule, matched packets produce log entries; in a lab with no traffic this is nil.

  1. Create the policy as in the command tab. Verification. gcloud compute firewall-policies list --organization=ORG_ID shows fw-org-baseline.
  2. Add rule 100 (allow IAP) and rule 200 (deny SSH and RDP from 0.0.0.0/0). Verification. gcloud compute firewall-policies rules list --firewall-policy=fw-org-baseline --organization=ORG_ID shows 100 before 200.
  3. Add a third rule that proves goto_next:
    gcloud compute firewall-policies rules create 300 \
      --firewall-policy=fw-org-baseline --organization=ORG_ID \
      --direction=INGRESS --action=goto_next \
      --layer4-configs=tcp:443 --src-ip-ranges=0.0.0.0/0 \
      --description="Let projects decide HTTPS"
    Verification. The rule list shows three rules, action goto_next for 300.
  4. Try to reuse a priority: run the rule 200 command again with a different description. Expected result. An error that the priority already exists. This confirms priorities are unique.
  5. Associate the policy with the lab folder: associations create as in the command tab. Verification. gcloud compute firewall-policies associations list --folder=FOLDER_ID shows the association.
  6. Inspect the effect without a VM: in the lab project create a VPC rule that tries to allow SSH from anywhere, then read the effective result.
    gcloud compute firewall-rules create lab-allow-ssh-any --project=PROJECT_ID --network=vpc-lab --direction=INGRESS --action=allow --rules=tcp:22 --source-ranges=0.0.0.0/0 --priority=1000
    The VPC rule is created (policies do not block rule creation), but the organization deny at 200 is evaluated first, so the rule has no effect from the internet. Verification. If you have a test VM, get-effective-firewalls lists the inherited policy rules before the VPC rule. A VM costs money while it runs, so use the smallest type and delete it in the cleanup.
  7. Roll back the risky step: delete the association with gcloud compute firewall-policies associations delete assoc-lab-folder --firewall-policy=fw-org-baseline --organization=ORG_ID. Verification. associations list --folder=FOLDER_ID is empty.

Expected result. A policy with three ordered rules, a rejected duplicate priority, an association created and removed, and an understanding of why the VPC allow in step 6 is not enough.

Cleanup, in this order.

gcloud compute firewall-rules delete lab-allow-ssh-any --project=PROJECT_ID --quiet
gcloud compute firewall-policies rules delete 300 --firewall-policy=fw-org-baseline --organization=ORG_ID
gcloud compute firewall-policies rules delete 200 --firewall-policy=fw-org-baseline --organization=ORG_ID
gcloud compute firewall-policies rules delete 100 --firewall-policy=fw-org-baseline --organization=ORG_ID
gcloud compute firewall-policies delete fw-org-baseline --organization=ORG_ID

Verification. gcloud compute firewall-policies list --organization=ORG_ID no longer lists the policy. A policy with an association cannot be deleted, so remove the association first.

Real cases

  • SSH from the internet removed everywhere. A security team found open SSH rules created by developers in dozens of projects. They created an organization policy: allow IAP (35.235.240.0/20) at 100, deny tcp:22 and tcp:3389 from 0.0.0.0/0 at 200. After a week in a sandbox folder, they associated it with each environment folder in turn. Teams moved to IAP TCP forwarding and OS Login, and the finding disappeared from Security Command Center.
  • Health checks broken by a deny. A team created a broad deny for a "lock-down" project. Load balancer health checks use 130.211.0.0/22 and 35.191.0.0/16, so every backend became unhealthy and the service went down. The fix was an allow at a lower number for those ranges in the same policy, and a review checklist that lists the Google ranges every policy must keep.
  • Egress control in production. A regulated workload needed all internet egress to go through an inspection proxy. A folder policy with an egress allow to the proxy range at 100 and an egress deny to 0.0.0.0/0 at 200 gave a rule that individual teams could not remove, and VPC rules handled the application-level flows.

Practices

  • Keep the organization policy short: a handful of rules that must never be broken. Put application-specific rules in the host project.
  • Number rules in steps of 100 or 1000, put exceptions before denies, and write a description with a ticket or reason in each rule.
  • Always list the Google service ranges that must stay open (health checks, IAP, metadata server is link-local and not affected) before you write a deny.
  • Roll out per folder: sandbox, non-production, production. Review firewall logs before the next step.
  • Use goto_next for ports that teams manage, and allow only when you accept that the VPC rules will be skipped.
  • Use service account or secure tag targets, not network tags, when you need targeting: tags can be set by anyone who can edit the VM, service accounts and secure tags are IAM-controlled.
  • Manage everything with Terraform. A console change to a policy is drift (Hour 7).
Security note. The roles roles/compute.orgFirewallPolicyAdmin and association rights can open or close the network for the whole organization. Give them to a small security-network group, require code review, and send Admin Activity logs for firewall policy changes to an alert (Hour 6). A deny at the organization level without an IAP or break-glass exception can lock out your own administrators.

Symptoms and first checks

SymptomLikely causeFirst check
VPC allow rule is created but traffic is still blockedA hierarchical deny matches firstgcloud compute instances network-interfaces get-effective-firewalls VM_NAME --zone=ZONE; firewall-policies associations list --folder=FOLDER_ID
Load balancer backends unhealthy after a new policyHealth check ranges deniedRules list: is there an allow for 130.211.0.0/22 and 35.191.0.0/16 with a lower number than the deny?
rules create fails: priority already existsDuplicate priority in the policyfirewall-policies rules list; choose a free number
Association fails: target already has a policyA node holds one policy onlyassociations list --folder=FOLDER_ID; delete the old association or add rules to the existing policy
Required 'compute.firewallPolicies.use' permission (or similar) on associationMissing roles/compute.orgFirewallPolicyUserCheck the IAM policy of the organization and the policy for your identity
Rule has no effect on some VMsTarget service account or target resource does not match, or the rule direction is wrongrules describe, then compare with the VM's service account and network
IAP SSH stops working after a deny ruleIAP range 35.235.240.0/20 not allowed before the denyRule order: allow IAP at a lower number than the deny; test with gcloud compute ssh VM_NAME --tunnel-through-iap

Triage order

  1. Identify the packet: source, destination, protocol, port, direction.
  2. List the associations for the project's folders and the organization, so you know every policy in the path.
  3. Walk the policies in order (organization, folders down), reading rules by priority until one matches.
  4. If the result was goto_next or no match, read the VPC firewall rules and network policies, then the implied rules.
  5. Confirm with firewall logs or a Connectivity Test before and after any change; make the smallest change (a rule at the right number) rather than removing the association.

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

Official reading: Hierarchical firewall policies · Use hierarchical firewall policies and rules · VPC firewall rules · IAP TCP forwarding.

or score ≥ 70% on the quiz

Module 5 · Egress and private access

29–36 · Cloud NAT with Cloud Router, Private Google Access and Private Service Connect for workloads without external IPs
Cloud NATCloud RouterPrivate Google AccessPrivate Service Connect7 min
Learning objectives
  • Configure Cloud NAT on a Cloud Router so that VMs without external IP addresses can reach the internet for outbound traffic only.
  • Distinguish Cloud NAT, Private Google Access and Private Service Connect, and choose the right one for each destination.
  • Verify egress paths with NAT mapping information, NAT logging and the subnet setting for Private Google Access.

The short answer

In a landing zone, most VMs and managed workloads have no external IP address. That is a security decision: nothing on the internet can start a connection to them. But the same workloads still need to go out: operating system updates, container images, partner APIs, and Google APIs such as Cloud Storage and Artifact Registry. Egress (出站流量) design answers one question: for each destination, which controlled path does the traffic take?

What: three tools for three destinations

DestinationToolAddress the workload usesWhere it is configured
Public internet (package mirrors, partner APIs)Cloud NAT (云 NAT)Private source IP, translated to an external NAT IPNAT gateway on a Cloud Router, per region
Google APIs and services (*.googleapis.com)Private Google AccessPrivate source IP; destination is a public Google IP, reached without NATSubnet setting, per subnet
Google APIs or a producer service on a private IP of your choicePrivate Service Connect (PSC)Private IP of an endpoint in your VPCEndpoint (forwarding rule) plus DNS
On-premisesCloud VPN or Cloud Interconnect (Hour 5)Private IP, over a private routeCloud Router and tunnels

Why: no public address does not mean no outbound

  • Smaller attack surface. An address that is not routable from the internet cannot be scanned or attacked directly. The Organization Policy constraint constraints/compute.vmExternalIpAccess (Hour 3) makes this the default.
  • One visible exit. A NAT gateway gives a small, known set of external IPs. Partners can allow-list them and logs show who used them.
  • Google APIs without the public internet path. Traffic to Google APIs from a VM with Private Google Access stays on Google's network and never needs an external IP on the VM.

How Cloud NAT works internally

Cloud NAT is software-defined. It is not a VM and it is not a device in the path. The Andromeda network virtualization layer applies the translation on the host where the VM runs. A Cloud Router is used only as the place where the NAT gateway configuration lives, so a NAT gateway is always created on a Cloud Router, in one region, for one VPC network.

  1. The VM sends a packet to an internet address. The default route (0.0.0.0/0, next hop default-internet-gateway) matches.
  2. Because the VM has no external IP, the packet would be dropped. If a NAT gateway covers the subnet range of the VM, the packet is translated instead.
  3. The source IP becomes a NAT external IP, and the source port becomes a port from the block that was allocated to that VM.
  4. The reply comes back to the NAT IP and port, and the reverse translation delivers it to the VM. Connections that start on the internet side are not accepted.

Ports are the scarce resource. Each VM gets a minimum number of ports per NAT IP (the default is 64 for static allocation, and dynamic port allocation can raise it). Each port can serve one connection per destination IP, port and protocol. If a VM opens thousands of connections to the same destination, it can run out of ports and see OUT_OF_RESOURCES in NAT logs. Fixes are more NAT IPs, dynamic port allocation, or fewer short-lived connections.

NAT IP allocation and subnet scope

SettingOptionsUse when
NAT IP allocationAutomatic (--auto-allocate-nat-external-ips): Google adds addresses as needed. Manual (--nat-external-ip-pool): you reserve static addresses.Automatic for general egress. Manual when a partner must allow-list the source addresses.
Subnet scopeAll primary and secondary ranges of all subnets (--nat-all-subnet-ip-ranges), only primary ranges (--nat-primary-subnet-ip-ranges), or custom (--nat-custom-subnet-ip-ranges)All for simple networks. Custom to give one workload its own NAT IPs or to keep another off the internet.
LoggingOff, errors only, translations only, or allErrors only in production at first; all while diagnosing.

Private Google Access in practice

Private Google Access (PGA) is turned on per subnet. When it is on, VMs with only internal IPs can reach the external IPs of Google APIs. There are three ways to name those IPs, and the choice is a security decision:

  • *.googleapis.com default. Resolves to public Google addresses. Works with PGA. Traffic still leaves the VM toward a public address range of Google.
  • private.googleapis.com (199.36.153.8/30). A VIP range reachable only from Google Cloud for all Google APIs. Used with a private DNS zone that overrides googleapis.com.
  • restricted.googleapis.com (199.36.153.4/30). Only the APIs that VPC Service Controls supports. Used with a perimeter so that data cannot be sent to unsupported services. This is the usual landing-zone choice together with Module 6 (private DNS) and Hour 3 (perimeters).

The routes to these ranges must exist: the default route to default-internet-gateway covers them, and many hardened networks keep a specific route to the VIP range and remove the general internet route for workloads that must never reach the internet.

Private Service Connect in one paragraph

Private Service Connect (专用服务连接) has two uses that you will see in a landing zone. First, an endpoint for Google APIs: a global internal IP address that you reserve in your VPC, with a forwarding rule that targets an API bundle (all-apis or vpc-sc). Workloads resolve googleapis.com to this IP, so API calls use an address from your own plan. Second, an endpoint for a published service: a producer (another team, or a partner) publishes a service attachment, and a consumer creates an endpoint with a private IP. No VPC peering, no overlapping range problem, and the producer sees only the endpoint, not the whole consumer network.

What it is confused with

Often confusedDifference
Cloud NAT vs Private Google AccessNAT reaches any internet destination by translating the source address. PGA reaches only Google APIs and services, and needs no translation. A subnet can have both. Google API traffic with PGA does not use NAT.
Cloud NAT vs an external IP on the VMAn external IP allows inbound connections (subject to firewall rules). NAT never does. NAT also shares addresses across many VMs.
Cloud Router vs Cloud NATCloud Router is a control plane for dynamic routing (BGP) and a host for NAT configuration. Cloud NAT is the translation. They are separate resources that you create in this order.
Private Google Access vs Private Service Connect for Google APIsPGA uses Google's public API IP ranges, reached privately. PSC gives you an internal IP in your own range, with its own forwarding rule that you can monitor and control.
Cloud NAT vs a firewallNAT translates addresses. Firewall policies decide whether traffic is allowed. Both apply: a NAT gateway does not bypass a deny-egress rule.

Common misunderstandings

NAT is not inbound access. Cloud NAT does not publish a service. To serve internet clients you use a load balancer (Hour 5), not a NAT gateway or a VM external IP.
Private Google Access is not on by default for custom subnets. Subnets in the default network and in auto mode networks are created with it off as well. You must enable it per subnet, in every region that is used.
A NAT gateway is regional and per VPC network. A VM in europe-west1 is not served by a gateway in us-central1. In a Shared VPC, create the Cloud Router and NAT in the host project. They then serve the VMs of every service project that uses those subnets.

When to use what

  • Workload only talks to Google APIs: Private Google Access, and no NAT. Add Private Service Connect or restricted VIP when a perimeter exists.
  • Workload needs the internet for updates and a few partners: Cloud NAT with automatic IPs and error logging.
  • Workload must never reach the internet: no NAT coverage for its subnet, no default internet route, and a firewall policy with an egress deny at the folder level.
  • Outbound traffic must be inspected: route it to a next-generation firewall appliance in a hub project, or use Cloud NGFW features. This is a design decision for the network team and is outside this hour.
VPC network vpc-hub · region europe-west1 · host project Subnet snet-app 10.10.0.0/24 · VMs, no external IP Private Google Access: on Cloud Router rtr-euw1 hosts the NAT gateway config control plane only Cloud NAT nat-egress source IP to NAT external IP Firewall policy egress allow or deny still applies Internet partners · package mirrors Google APIs storage · artifact registry private or restricted VIP outbound Private Google Access path, no NAT

Figure 1. Two exits from one subnet. Internet traffic is translated by Cloud NAT (configured on a Cloud Router). Google API traffic uses Private Google Access directly and never touches the NAT gateway.

Where does the workload connect? Google APIs only Private Google Access or PSC endpoint Internet destinations Cloud NAT on a Cloud Router manual IPs for allow-lists Another producer service PSC endpoint to a service attachment, private IP Always: firewall policy egress rules, VM external IP blocked by org policy, logs on. Never: a public IP on a VM just to install packages.

Figure 2. Choose the path by destination, not by habit. The bottom band applies to every path.

Look at where the Cloud Router sits in Figure 1: it is attached to the NAT box but the data arrow goes from the subnet to NAT and on to the internet. The router holds configuration only. Also see that the Private Google Access line bypasses NAT completely.

The animation follows one outbound TCP connection from a VM without an external IP through the Cloud NAT gateway to an internet host, and shows the log line that Cloud NAT writes. Watch the source address change and then return to the original on the reply path.

Replace PROJECT_ID, REGION and the network names with your own. In a Shared VPC, run these against the host project. IDs and addresses in the expected output are illustrative.

gcloud compute routers create (write, free)

Purpose. Creates the Cloud Router that will hold the NAT gateway. The router itself is free to create; Cloud Router has no hourly charge when it is used only for NAT.

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

Flags. --network is the VPC network the router serves. --region must match the subnets you want to NAT. For NAT-only use you do not need an --asn; add one when the same router will also run BGP (Hour 5).

Common errors. The resource 'projects/.../networks/vpc-hub' was not found: wrong project (a Shared VPC network lives in the host project). Required 'compute.routers.create' permission: you need roles/compute.networkAdmin in the host project.

gcloud compute routers nats create (write, metered)

Purpose. Creates a NAT gateway on the router. This is the command that gives private VMs outbound internet access.

gcloud compute routers nats create nat-egress \
  --project=PROJECT_ID \
  --router=rtr-euw1 \
  --region=REGION \
  --auto-allocate-nat-external-ips \
  --nat-all-subnet-ip-ranges \
  --enable-logging \
  --log-filter=ERRORS_ONLY
Creating NAT [nat-egress] in router [rtr-euw1]...done.

Flags. --auto-allocate-nat-external-ips lets Google add NAT IPs as needed; for a fixed set, use --nat-external-ip-pool=ADDRESS_NAME with reserved static addresses. --nat-all-subnet-ip-ranges covers every subnet range in the region; use --nat-custom-subnet-ip-ranges=SUBNET_NAME to be selective. --enable-logging with --log-filter (ERRORS_ONLY, TRANSLATIONS_ONLY, ALL) controls logging. Check gcloud compute routers nats create --help for the flags in your SDK version (for example the dynamic port allocation options).

Cost. Low (usually well under a few USD per day for a lab). Cloud NAT is metered by gateway time and by data processed, plus the external IP address if you reserve static addresses that are not in use. Budgets send alerts and do not cap spend.

Common errors. Router ... already has a NAT with that name: names are unique per router. NAT_IPS_EXHAUSTED appears later in logs when automatic allocation hits a quota; raise the quota or add addresses.

gcloud compute routers nats describe (read, free)

Purpose. Reads the gateway back so you can verify scope, IP allocation and logging.

gcloud compute routers nats describe nat-egress \
  --router=rtr-euw1 --region=REGION --project=PROJECT_ID
autoAllocatedNatIps: []
enableEndpointIndependentMapping: false
logConfig:
  enable: true
  filter: ERRORS_ONLY
name: nat-egress
natIpAllocateOption: AUTO_ONLY
sourceSubnetworkIpRangesToNat: ALL_SUBNETWORKS_ALL_IP_RANGES
minPortsPerVm: 64

Production use. Run this in a scheduled check and compare to the Terraform state. An empty autoAllocatedNatIps before traffic is normal; the address appears on first use.

gcloud compute routers get-nat-mapping-info (read, free)

Purpose. Shows which NAT IP and port range each VM uses. It is the quickest answer to "which external address does this VM use?" and to port exhaustion.

gcloud compute routers get-nat-mapping-info rtr-euw1 \
  --region=REGION --project=PROJECT_ID
---
instanceName: vm-app-1
interfaceNatMappings:
- natIpPortRanges:
  - 198.51.100.7:1024-1087
  numTotalNatPorts: 64
  sourceAliasIpRange: ''
  sourceVirtualIp: 10.10.0.5

gcloud compute networks subnets update --enable-private-ip-google-access (write, free)

Purpose. Turns on Private Google Access for one subnet. It is a metadata change; it costs nothing.

gcloud compute networks subnets update snet-app \
  --project=PROJECT_ID \
  --region=REGION \
  --enable-private-ip-google-access
Updated [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/regions/europe-west1/subnetworks/snet-app].

Verify with:

gcloud compute networks subnets describe snet-app \
  --project=PROJECT_ID --region=REGION \
  --format="get(privateIpGoogleAccess)"
True

Common error. Value False or empty: the flag was applied to the wrong region or subnet. The setting is per subnet.

Private Service Connect endpoint for Google APIs (write, low)

Purpose. Reserves an internal global address and points a forwarding rule at the Google APIs bundle. This is a concept to recognise; run it only in a sandbox.

gcloud compute addresses create psc-google-apis \
  --project=PROJECT_ID \
  --global \
  --purpose=PRIVATE_SERVICE_CONNECT \
  --addresses=10.255.255.10 \
  --network=vpc-hub

gcloud compute forwarding-rules create pscgoogleapis \
  --project=PROJECT_ID \
  --global \
  --network=vpc-hub \
  --address=psc-google-apis \
  --target-google-apis-bundle=all-apis

Check gcloud compute forwarding-rules create --help for the flags in your SDK version; the endpoint name rules (lowercase letters and digits only for Google API endpoints) and the bundle values (all-apis, vpc-sc) are in the Private Service Connect documentation. The address must come from a range that is part of your IP plan, outside any subnet range.

Production use. Create NAT and Private Google Access in the same Terraform module as the subnet, so no subnet exists without a decision about its egress. Keep NAT logging at ERRORS_ONLY and use a log-based metric to alert on OUT_OF_RESOURCES.

Lab 5: private VM, NAT and Private Google Access (about 15 minutes, low cost)

Goal. Show the difference between a subnet with no egress, a subnet with Private Google Access and a subnet with Cloud NAT, using one small VM without an external IP.

Prerequisites. A sandbox project with billing linked and a budget set, the Compute Engine API enabled, a custom-mode VPC with one subnet in REGION, and roles/compute.admin (or roles/compute.networkAdmin plus roles/compute.instanceAdmin.v1). For SSH, a firewall rule that allows TCP 22 from 35.235.240.0/20 (the range used by Identity-Aware Proxy). Module 7 builds the full lab with a Shared VPC; here you can use a single project. IDs in the expected output are illustrative.

  1. Set the project: gcloud config set project PROJECT_ID.
  2. Create a VM without an external IP:
    gcloud compute instances create vm-egress-test \
      --zone=ZONE \
      --machine-type=e2-micro \
      --subnet=snet-app \
      --no-address \
      --image-family=debian-12 --image-project=debian-cloud
  3. Connect with IAP: gcloud compute ssh vm-egress-test --zone=ZONE --tunnel-through-iap. If this asks to enable the IAP API, accept it.
  4. On the VM, try the internet with a short timeout. This must fail because there is no NAT yet:
    curl -s -o /dev/null -m 8 -w "%{http_code}\n" https://example.com
    000
  5. Try Google APIs. Private Google Access is still off, so this also fails. From your workstation, turn it on for the subnet (previous tab), then repeat on the VM:
    curl -s -o /dev/null -m 8 -w "%{http_code}\n" https://storage.googleapis.com/
    400
    A 400 response from the storage endpoint without a bucket path is the proof that the API was reached, so the code is fine. A 000 means the connection failed.
  6. Create the Cloud Router and the NAT gateway with the commands from the previous tab.
  7. Repeat the internet test on the VM. It must now succeed:
    200
  8. Find the external address that the VM used: gcloud compute routers get-nat-mapping-info rtr-euw1 --region=REGION. Compare it with curl -s https://ifconfig.me run on the VM (a third-party echo service; do not rely on it in production).

Verification summary. Step 4 returns 000, step 5 returns 400 after Private Google Access is enabled, step 7 returns 200 after NAT exists, and the mapping info lists the VM with a NAT IP.

Cost. Low (usually well under a few USD per day for this lab): one e2-micro VM, one NAT gateway, small data transfer. Budgets send alerts and do not cap spend.

Cleanup. Delete in this order so that nothing is left billing:

gcloud compute instances delete vm-egress-test --zone=ZONE --quiet
gcloud compute routers nats delete nat-egress --router=rtr-euw1 --region=REGION --quiet
gcloud compute routers delete rtr-euw1 --region=REGION --quiet

If you reserved static NAT addresses, release them with gcloud compute addresses delete ADDRESS_NAME --region=REGION.

Real cases (typical patterns)

  • One NAT per region, shared by the hub. A platform team ran a Cloud Router and a NAT gateway for every region in the host project of a Shared VPC. Application teams in service projects never created NAT themselves. The set of external IPs was small, stable and documented, and partners allow-listed it. When a team asked for its own addresses, the team added a second gateway scoped with --nat-custom-subnet-ip-ranges to that team's subnets.
  • Port exhaustion during a batch job. A nightly job opened thousands of short connections to one SaaS API and failed with timeouts. Logs showed dropped connections with OUT_OF_RESOURCES, and get-nat-mapping-info showed the VMs at their port limit. Dynamic port allocation, more NAT IPs and connection reuse in the job solved it, with no change to the application's code path beyond a keep-alive setting.
  • Restricted Google APIs with a perimeter. A regulated workload used VPC Service Controls. The network team enabled Private Google Access, created a private DNS zone for googleapis.com that mapped to restricted.googleapis.com, and removed the general internet route from that folder's networks. Calls to unsupported services and to public sites failed by design, and the failures were found in testing, not in production.

Practices

  • Enable Private Google Access on every subnet at creation time. It is free and removes a large class of "cannot reach Cloud Storage" tickets.
  • Use the Organization Policy constraints/compute.vmExternalIpAccess (deny all, Hour 3) so that teams cannot bypass NAT by attaching external IPs.
  • Use manual NAT addresses for production egress that is allow-listed by third parties. Reserve them as named static addresses in the host project with labels that name the owner.
  • Alert on NAT errors with a log-based metric on nat_allocation_status and on the drop reason. Do not log ALL permanently: the volume is high and Cloud Logging ingestion is billed.
  • Test egress from the real subnet, not from Cloud Shell. Cloud Shell is not in your VPC network.
Security note. NAT makes outbound access easy, and that is also the way data leaves. Combine it with a deny-by-default egress rule in the hierarchical firewall policy (Module 4), allow only the required destinations (FQDN or address groups), and log the denies. An open NAT plus an allow-all egress rule gives an attacker a free exfiltration path.

Symptoms and first checks

SymptomLikely causeFirst check
VM cannot reach any internet address, DNS worksNo NAT gateway for this subnet range or regiongcloud compute routers nats describe NAT --router=ROUTER --region=REGION; look at sourceSubnetworkIpRangesToNat
Cannot reach storage.googleapis.com, internet works through NATResolution points to a restricted VIP but the route or firewall blocks it, or DNS override is wrongnslookup storage.googleapis.com on the VM; check the private zone and the route to 199.36.153.4/30
Cannot reach Google APIs, no NATPrivate Google Access is off on this subnetgcloud compute networks subnets describe SUBNET --region=REGION --format="get(privateIpGoogleAccess)"
Intermittent timeouts to one destination under loadNAT port exhaustion for that destinationLogs filter jsonPayload.allocation_status="DROPPED"; get-nat-mapping-info
Partner still blocks the old addressAutomatic allocation changed the NAT IP, or the VM is on another gatewayget-nat-mapping-info; switch to manual static addresses
NAT works in one region onlyNAT is regional; the other region has no router or NATgcloud compute routers list --filter="network:vpc-hub"
Egress blocked although NAT is fineAn egress deny in a firewall policy or a VPC ruleNetwork Intelligence Center Connectivity Tests, or gcloud compute firewall-policies listing (Module 4)
Shared VPC service project VM has no internetNAT was created in the service project, or in a different networkNAT must be in the host project on a router of the shared network

Triage order

  1. Does the VM have an external IP? If yes, NAT is not used for that VM.
  2. Is the destination Google or the internet? Pick PGA or NAT accordingly.
  3. Does DNS resolve to the address you expect (nslookup or dig)?
  4. Does a route exist for the destination, and is the next hop correct (gcloud compute routes list --filter="network:vpc-hub")?
  5. Is egress allowed by the firewall policies and VPC firewall rules (policies are evaluated top-down, Module 4)?
  6. Read NAT logs and get-nat-mapping-info for allocation problems.

Video content changes often, so the links below are search pages and official documentation rather than pinned videos. Check the date of a video against the current Cloud NAT documentation.

Official reading: Cloud NAT overview · Private Google Access · Private Service Connect · Cloud Router overview.

or score ≥ 70% on the quiz

Module 6 · Cloud DNS

36–43 · Public and private managed zones, record sets, forwarding and peering, and DNS for Shared VPC and Google APIs
Cloud DNSPrivate zonesForwardingPeering7 min
Learning objectives
  • Create a private managed zone attached to a VPC network and add record sets, and explain how it differs from a public zone.
  • Describe the order in which the Cloud DNS resolver in a VPC network chooses between private zones, forwarding zones, peering zones and public DNS.
  • Design DNS for a Shared VPC: where zones live, which networks they are attached to, and how Google APIs and on-premises names are resolved.

The short answer

Cloud DNS (云 DNS) is Google Cloud's managed domain name service. It has two jobs that are easy to mix up. First, it is an authoritative server for the zones you create: public zones answer the internet, private zones answer only selected VPC networks. Second, every VPC network has a built-in resolver (reached from a VM at 169.254.169.254) that decides, for each query, where to look. A landing zone uses both: private zones for internal names, forwarding to reach on-premises, peering to share names, and one private zone that pins Google APIs to a private address range.

What: the building blocks

ObjectWhat it isTypical landing-zone use
Public managed zoneAuthoritative zone served on the internet. You delegate your domain to its name servers.Public sites and APIs. Usually in a separate project owned by the web or DNS team.
Private managed zone (专用区域)Authoritative zone visible only to the VPC networks you listInternal service names, corp.example.internal, Google APIs override.
Forwarding zoneSends queries for a name to the DNS servers you list (internal IPs, over VPN or Interconnect)Resolve on-premises names from the cloud.
Peering zoneSends queries for a name to another VPC network's DNS contextHub network holds the zones; spoke networks peer to it.
DNS policyNetwork-level settings: inbound forwarding (on-premises can query cloud), alternative name servers, loggingLet on-premises DNS resolve cloud private zones; turn on query logging.
Response policyOverrides specific names or patterns with a set answer or a local data rule, ahead of other zonesBlock known-bad domains, override a few names without a full zone.
Record setA name, a type (A, AAAA, CNAME, TXT, SRV and so on), a TTL, and dataThe content of a zone.

How the resolver decides (the order matters)

When a VM sends a query to the metadata-server resolver, Cloud DNS looks at the network's configuration in a fixed order. The exact steps are in the documentation under "name resolution order"; in short:

  1. Response policy rules for the network, if any. A matching rule answers immediately.
  2. Zones attached to the network, chosen by the longest matching suffix: a forwarding zone, a peering zone or a private zone whose DNS name is the best match for the query name. For a VM the "internal DNS" names (INSTANCE.ZONE.c.PROJECT_ID.internal) are also part of this decision.
  3. If no zone matches, the query goes to public DNS through Google Public DNS resolution (unless you configured alternative name servers in a DNS policy).

Longest suffix wins. If you have a private zone for example.com. and a forwarding zone for corp.example.com., a query for app.corp.example.com goes to the forwarding zone. A name such as www.example.com that is not in the private zone returns NXDOMAIN. It does not fall through to the public zone. This is the number one surprise when an internal zone shadows a public domain.

Why: names, not addresses

  • Stability. IP addresses change when a VM is replaced. Names survive.
  • Policy. A private zone for googleapis.com is how a landing zone steers all Google API calls through the restricted VIP and VPC Service Controls (Module 5).
  • Hybrid. Without forwarding, cloud workloads cannot find on-premises systems by name, and on-premises systems cannot find cloud services. Hard-coded addresses are the usual workaround and the usual outage.
  • Reduced exposure. A name in a private zone is not published. Attackers who scan public DNS do not see it.

DNS in a Shared VPC

DNS follows the network, and the network lives in the host project. The common design is:

  • Create the private zones in the host project (or in a dedicated DNS project) and attach them to the host project's network. VMs in every service project that use the shared subnets resolve those zones automatically.
  • Service projects that need their own names get a zone in their own project, and the platform team adds the shared network to the zone's visibility. This needs a permission on the network (dns.networks.bindPrivateDNSZone, part of roles/dns.peer) for the project owner. Without that role the zone creation is refused.
  • For several VPC networks (for example a hub and a number of spokes), keep one set of zones in the hub and use peering zones in the spokes. A spoke does not need its own copies.

Google APIs: the override zone

To keep every API call on a private path, create a private zone for googleapis.com. attached to the network and add two records: a CNAME from *.googleapis.com. to restricted.googleapis.com., and an A record for restricted.googleapis.com. that lists 199.36.153.4 to 199.36.153.7. Use private.googleapis.com. and 199.36.153.8 to 199.36.153.11 when you need all APIs and not only those that VPC Service Controls supports. If you use a Private Service Connect endpoint (Module 5) the A record points to the endpoint address instead. Do the same for gcr.io, pkg.dev and run.app where needed, because those domains are separate from googleapis.com.

What it is confused with

Often confusedDifference
Private zone vs public zone with private addressesA public zone is served on the internet to everyone. Putting 10.x addresses there leaks internal layout and still does not resolve reliably. Use a private zone.
DNS peering vs VPC Network PeeringDNS peering only forwards DNS queries to the target network's DNS context. VPC Network Peering exchanges routes for traffic. They are independent. You need no VPC peering for DNS peering.
Forwarding zone vs inbound forwarding policyA forwarding zone sends cloud queries out to other DNS servers. An inbound policy lets on-premises resolvers send queries in to the Cloud DNS resolver by an internal IP.
Cloud DNS vs Cloud DomainsCloud DNS hosts zones. Cloud Domains (or any registrar) sells and registers domain names. You can register elsewhere and still host zones in Cloud DNS.
Internal DNS vs private zonesInternal DNS names (VM.ZONE.c.PROJECT_ID.internal) are created automatically per VM. A private zone is yours: you choose the names and the records. Prefer private zones for service names.

Common misunderstandings

A private zone is not a security boundary. It hides names from the internet, but anyone inside an authorized network can query it. Authorize only the networks that need it.
Zone names must end with a dot in the DNS name. --dns-name="corp.example.internal." is the form the API expects. Without the trailing dot some tools accept it, others fail.
Propagation is fast but TTLs still apply. A record change inside Cloud DNS is served within seconds, but resolvers and applications that cached the old answer keep it until the TTL expires. Lower the TTL before a planned change.

When to use what

  • Internal service names, one VPC network or a hub: private zone in the host project.
  • Resolve a data-center domain from the cloud: forwarding zone with the on-premises resolver IPs (need a route to them over VPN or Interconnect, and a firewall allow for UDP and TCP 53).
  • Let on-premises resolve a cloud private zone: inbound forwarding policy and a DNS server forwarder that points to the inbound address.
  • Share one set of zones with many networks: peering zones that target the hub.
  • Pin Google APIs to the restricted or private VIP: private zone for googleapis.com.
VM asks 169.254.169.254 for a name Cloud DNS resolver 1. response policy 2. zone, longest suffix 3. public DNS fallback network vpc-hub Private zone corp.example.internal. to 10.10.0.20 Forwarding zone onprem.example.com. to 10.99.0.2 Peering zone shared.example.internal. to hub network Public DNS no zone matched The zone whose DNS name is the longest suffix of the query wins. A matched private zone that lacks the record returns NXDOMAIN; it does not fall through.

Figure 1. The resolver checks response policies, then zones by longest suffix, then public DNS. A forwarding zone answers from outside Google Cloud, a peering zone from another network.

Host project: prj-net-hub Network vpc-hub private zones · googleapis.com override forwarding zone to on-premises Service project A VMs on vpc-hub shared subnet resolve hub zones directly Service project B own zone b.example.internal. bound to vpc-hub via dns.peer Spoke VPC (not shared) peering zone targets vpc-hub no copies of zones DNS peering On-premises DNS 10.99.0.2 over VPN

Figure 2. Zones live where the network lives. Service projects on shared subnets need nothing extra; separate networks use peering zones that target the hub.

Check in Figure 1 that the dashed line to public DNS is only used when no zone matches. In Figure 2, notice that the DNS peering line goes to a different network, while the Shared VPC projects resolve through the network they already use.

The animation shows two lookups from one VM: first a name that matches a private zone, then a name that matches a forwarding zone to on-premises. Notice that the VM always asks the same resolver and Cloud DNS chooses the destination by the matching zone.

Run zone commands in the project that owns the zone (for a Shared VPC, usually the host project). Placeholders are in capitals. IDs and addresses in the expected output are illustrative.

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

Purpose. Turns on the Cloud DNS API in the project. Enabling an API is a metadata change and is free.

gcloud services enable dns.googleapis.com --project=PROJECT_ID
Operation "operations/acat.p2-123456789012-0a1b2c3d" finished successfully.

Common error. API [dns.googleapis.com] not enabled on project on every later command: run this first. In production the project factory enables APIs.

gcloud dns managed-zones create --visibility=private (write, low)

Purpose. Creates a private zone and attaches it to one or more VPC networks.

gcloud dns managed-zones create zone-corp-internal \
  --project=PROJECT_ID \
  --dns-name="corp.example.internal." \
  --description="Internal service names" \
  --visibility=private \
  --networks=vpc-hub
Created [https://dns.googleapis.com/dns/v1/projects/PROJECT_ID/managedZones/zone-corp-internal].
NAME                  DNS_NAME                  DESCRIPTION             VISIBILITY
zone-corp-internal    corp.example.internal.    Internal service names  private

Flags. --dns-name is the domain, with a trailing dot. --visibility=private makes the zone resolvable only from the networks in --networks (comma separated network names in the same project; for a network in another project use the full URL https://www.googleapis.com/compute/v1/projects/HOST_PROJECT_ID/global/networks/vpc-hub). The zone name is a label for the zone, not the DNS name.

Cost. Low: a managed zone has a small monthly charge and queries are metered. A lab zone deleted the same day costs well under a few USD.

Common errors. The network does not exist: the network name or project is wrong. Forbidden: dns.networks.bindPrivateDNSZone: the caller lacks permission on the network project; grant roles/dns.admin in the zone project and roles/dns.peer on the network project (at project or folder level).

gcloud dns record-sets create (write, low)

Purpose. Adds a record to a zone.

gcloud dns record-sets create app.corp.example.internal. \
  --project=PROJECT_ID \
  --zone=zone-corp-internal \
  --type=A \
  --ttl=300 \
  --rrdatas=10.10.0.20
NAME                        TYPE  TTL  DATA
app.corp.example.internal.  A     300  10.10.0.20

Flags. --type is the record type, --rrdatas is a comma-separated list of data (use several for several A records). To change a record use gcloud dns record-sets update with the same flags, and to remove it use delete NAME --type=A --zone=.... Check gcloud dns record-sets --help for the flags in your SDK version.

gcloud dns record-sets list (read, free)

Purpose. Lists the records in a zone. The first check when a name does not resolve.

gcloud dns record-sets list --zone=zone-corp-internal --project=PROJECT_ID
NAME                        TYPE  TTL    DATA
corp.example.internal.      NS    21600  ns-gcp-private.googledomains.com.
corp.example.internal.      SOA   21600  ns-gcp-private.googledomains.com. cloud-dns-hostmaster.google.com. 1 21600 3600 259200 300
app.corp.example.internal.  A     300    10.10.0.20

gcloud dns managed-zones create for forwarding (write, low)

Purpose. Creates a private zone that forwards queries to your DNS servers on premises. The forwarding target must be reachable over a VPN or Interconnect route (Hour 5), and your firewall must allow DNS (UDP and TCP port 53) from the Google range 35.199.192.0/19 to the on-premises server.

gcloud dns managed-zones create zone-onprem-fwd \
  --project=PROJECT_ID \
  --dns-name="onprem.example.com." \
  --description="Forward to data center DNS" \
  --visibility=private \
  --networks=vpc-hub \
  --forwarding-targets=10.99.0.2,10.99.0.3

Use --private-forwarding-targets when the targets are on the private network and you want the traffic always to use a private path. Check gcloud dns managed-zones create --help for the flags in your SDK version.

gcloud dns managed-zones create for peering (write, low)

gcloud dns managed-zones create zone-peer-to-hub \
  --project=SPOKE_PROJECT_ID \
  --dns-name="corp.example.internal." \
  --description="Peer to hub DNS" \
  --visibility=private \
  --networks=vpc-spoke \
  --target-network=vpc-hub \
  --target-project=HOST_PROJECT_ID

Production use. The caller needs roles/dns.peer on the target project. Queries for corp.example.internal. from the spoke network are answered by the hub network's DNS configuration. A peering zone cannot be chained: the hub must hold the data or forward it, not peer again.

gcloud dns policies create (write, low)

Purpose. Enables inbound DNS forwarding (so on-premises resolvers can query Cloud DNS) and DNS query logging for a network.

gcloud dns policies create policy-hub-dns \
  --project=PROJECT_ID \
  --description="Inbound forwarding and logging" \
  --networks=vpc-hub \
  --enable-inbound-forwarding \
  --enable-logging

List inbound entry points with gcloud compute addresses list --filter="purpose=DNS_RESOLVER" and use these addresses as the forwarding target on premises.

Production use. Keep all zones and records in Terraform (google_dns_managed_zone, google_dns_record_set). Do not edit records in the console. A reviewed change is the only protection against a typo in googleapis.com that breaks every API call in a network.

Lab 6: private zone and record, resolved from a VM (about 15 minutes, low cost)

Goal. Create a private zone for an internal domain, add one record, and prove that a VM in the network resolves it while a lookup from outside the network does not.

Prerequisites. A sandbox project with billing linked and a budget set, the Compute Engine API and Cloud DNS API enabled, a custom-mode VPC (vpc-hub or any lab network) with a subnet, and a VM without an external IP reachable by IAP (see Module 5). Roles: roles/dns.admin and roles/compute.networkViewer on the project. IDs in the expected output are illustrative.

  1. Enable the API: gcloud services enable dns.googleapis.com --project=PROJECT_ID.
  2. Create the private zone attached to the network:
    gcloud dns managed-zones create zone-lab-internal \
      --dns-name="lab.example.internal." \
      --description="Lab private zone" \
      --visibility=private \
      --networks=vpc-hub
  3. Verify the zone: gcloud dns managed-zones describe zone-lab-internal --format="value(visibility,dnsName)".
    private	lab.example.internal.
  4. Add an A record: gcloud dns record-sets create web.lab.example.internal. --zone=zone-lab-internal --type=A --ttl=60 --rrdatas=10.10.0.20.
  5. Connect to the VM: gcloud compute ssh vm-egress-test --zone=ZONE --tunnel-through-iap (create a VM first if you removed it).
  6. On the VM resolve the name. It must return the private address:
    getent hosts web.lab.example.internal
    dig +short web.lab.example.internal @169.254.169.254
    10.10.0.20     web.lab.example.internal
    10.10.0.20
  7. Prove that the name is private. From your workstation or Cloud Shell, run nslookup web.lab.example.internal 8.8.8.8. It must fail with NXDOMAIN, because the zone is not on the public internet.
  8. Test the longest-suffix rule: create a record for a name that is not in the zone, for example look up missing.lab.example.internal on the VM. The answer is NXDOMAIN, not a public answer.
  9. Optional: add a CNAME www.lab.example.internal. pointing to web.lab.example.internal. and resolve it.

Verification summary. The zone is private, the record is listed by record-sets list, the VM resolves it, and a public resolver returns NXDOMAIN.

Cost. Low (usually well under a few USD per day for this lab). Budgets send alerts and do not cap spend.

Cleanup. Delete the records first, then the zone. A zone with records other than the default NS and SOA cannot be deleted.

gcloud dns record-sets delete web.lab.example.internal. --zone=zone-lab-internal --type=A
gcloud dns managed-zones delete zone-lab-internal
gcloud compute instances delete vm-egress-test --zone=ZONE --quiet

Real cases (typical patterns)

  • Hub zones, no copies. A platform team kept all private zones in the host project of a Shared VPC and used peering zones for the few networks that were not shared. When a payment service moved to a new address, one record change fixed all consumers. Previously every team held its own hosts file or its own zone, and four of them were stale.
  • Hybrid names after a VPN cut-over. An application moved to Google Cloud but still called a database by its data-center name. Without a forwarding zone, the lookup returned NXDOMAIN and the team hard-coded an IP. A forwarding zone plus a firewall rule for the Google DNS range 35.199.192.0/19 fixed it. The hard-coded address caused an outage months later, when the database moved.
  • Override zone for Google APIs. A security team enforced the restricted VIP with a private zone for googleapis.com. It forgot gcr.io and pkg.dev, so container pulls kept using public addresses and bypassed the intended path. The review added both domains to the same Terraform module.

Practices

  • Create zones through Terraform in the network project; give application teams permission to manage records only in their own zone (roles/dns.admin on that zone resource, or a delegated subzone), not on the whole project.
  • Name zones for the domain and visibility (zone-corp-internal, zone-pub-example-com) and put a description that names the owner team.
  • Use a dedicated internal domain that you control (for example under a registered domain, such as int.example.com) rather than invented suffixes such as .local or .corp, which can clash with other software and with future top-level domains.
  • Turn on DNS query logging on a policy for networks with sensitive workloads, and route the logs to the central log project (Hour 6). Logs are billed by volume.
  • Test changes with a short TTL first; raise the TTL after verification. Remember that clients cache.
  • Document which networks each private zone is attached to. A zone that is attached to a network that should not see it is an information leak.
Security note. DNS is a data-exfiltration channel. Even with no internet egress, a workload that can resolve public names can send data in DNS queries. Use a response policy or a forwarding policy to restrict resolution on sensitive networks, and monitor DNS logs for long random subdomains. Protect delegated public zones with registrar locks and limit who has roles/dns.admin on production projects, since changing a record is the same as redirecting traffic.

Symptoms and first checks

SymptomLikely causeFirst check
Private name returns NXDOMAIN on a VMNetwork is not listed in the zone, or the record is missinggcloud dns managed-zones describe ZONE --format="value(privateVisibilityConfig.networks)" and record-sets list
Public name returns NXDOMAIN after you created a private zone for the same domainThe private zone shadows the public one for names it does not containAdd the missing records, or use a more specific zone and a forwarding or peering zone
Service project VM cannot resolve a host-project zoneVM is on its own network, not the shared one; or the zone is attached to a different networkgcloud compute instances describe VM --format="value(networkInterfaces[0].network)"
On-premises name does not resolve from the cloudNo route or firewall rule to the forwarding target, or wrong target IPdig @TARGET_IP name from a VM; check UDP and TCP 53 and the source range 35.199.192.0/19
On-premises cannot resolve cloud namesNo inbound forwarding policy, or on-premises forwarder points to the wrong addressgcloud dns policies list; gcloud compute addresses list --filter="purpose=DNS_RESOLVER"
Peering zone returns SERVFAILMissing roles/dns.peer, or the target network cannot answerRun the same query from a VM in the target network; check IAM on the target project
Container image pull goes to public IPsOverride zone has googleapis.com but not gcr.io or pkg.devdig +short gcr.io on the VM
Old address still returned after a changeClient or resolver cache, high TTLCheck the TTL in record-sets list and flush the cache on the client

Triage order

  1. Ask the resolver directly: dig +short NAME @169.254.169.254 from the failing VM. This removes application caches.
  2. Confirm the VM's network (not only the project) and the zones attached to it.
  3. Find the matching zone by longest suffix, then list its record sets.
  4. For forwarding, test the target from the same network and check route and firewall for port 53.
  5. Look at DNS query logs (if enabled) and at the Cloud DNS audit logs for recent changes.
  6. Only then look at the application: caches, search domains and the TTL it honours.

Video content changes often, so the links below are search pages and official documentation rather than pinned videos. Check the date of a video against the current Cloud DNS documentation.

Official reading: Cloud DNS overview · Zones overview · Cloud DNS best practices · Configure Private Google Access.

or score ≥ 70% on the quiz

Module 7 · Lab: host project, Shared VPC, subnet, NAT and firewall policy

43–53 · Build the network hub end to end in a sandbox, verify every step, and tear it down in the right order
Hands-onShared VPCCloud NATFirewall policy10 min
Learning objectives
  • Create a host project and a service project, enable Shared VPC, and share one subnet with a group at subnet level.
  • Add a Cloud Router, a Cloud NAT gateway and a hierarchical firewall policy, and verify each layer with a read-only command.
  • Tear the environment down in the dependency order so that no billable resource or orphaned association is left behind.

The short answer

This module builds a network hub in miniature: one host project that owns a custom VPC, one service project that uses a shared subnet, a Cloud NAT gateway for outbound internet access, and a hierarchical firewall policy associated with a folder. Modules 1 to 6 gave you the pieces. The lab shows how they depend on each other, in which order you create them and in which order you remove them.

What you will build

LayerResourceWhere it livesWhy
HierarchyLab folder (or an existing sandbox folder) with two projectsOrganizationPolicies and the firewall policy are inherited from the folder
Shared VPCHost project and one attached service projectHost projectCentral control of the network, local control of the workloads
NetworkCustom-mode VPC vpc-lab-hub, subnet snet-lab-euw1 (10.20.0.0/24)Host projectNo default network, planned addresses, Private Google Access on
Accessroles/compute.networkUser on the subnetSubnet in host projectLeast privilege: only one subnet is usable
EgressCloud Router rtr-lab-euw1 and Cloud NAT nat-lab-egressHost projectOutbound only; no external IP on the VMs
GuardrailFirewall policy fp-lab-baseline with an association to the folderOrganization (policy), folder (association)One baseline rule set for every project below

Why this order

  1. Host project first. It needs the Compute Engine API before it can be made a host or hold a network.
  2. Shared VPC enabled before the network is used. Technically you can create networks earlier, but enabling first prevents the case where a project already has resources that you later share by mistake.
  3. Network and subnet before attaching service projects. A service project with nothing to use is harmless, but you grant access to the subnet, so it has to exist.
  4. NAT after the subnet. The gateway needs a router in the region of the subnet.
  5. Firewall policy last. It is independent of the network, but you want to see how it interacts with a working environment, and you can test one rule at a time.

Teardown reverses this order, because each object holds a reference to the one before it.

How the pieces interact

  • Shared VPC and IAM. The service project's users need roles/compute.instanceAdmin.v1 in their own project to create VMs and roles/compute.networkUser on the shared subnet to attach a VM to it. The Compute Engine service agent and the service accounts that create instance groups need the same network role on the subnet.
  • Hierarchical firewall policy and VPC rules. Traffic is evaluated against organization policies first, then folder policies, then VPC firewall rules and network firewall policies. A goto_next rule hands the decision down. An allow or deny in a policy is final.
  • NAT and firewall. NAT translates, the policies decide. An egress deny rule still blocks traffic that NAT would otherwise carry.

What it is confused with

Often confusedDifference
Hierarchical firewall policy vs VPC firewall rulesHierarchical policies are created at the organization or folder and apply to many projects. VPC firewall rules and network firewall policies are scoped to one network. Policy rules are not visible in gcloud compute firewall-rules list.
Association vs ruleA rule says what to allow or deny. An association says where the policy applies. A policy with no association enforces nothing.
Detaching a service project vs deleting itDetaching removes the project's right to use the shared network. Deleting a project that is still attached fails or leaves the host with a dangling reference. Detach first.

Common misunderstandings

Shared VPC needs an organization. Hosts and service projects must belong to the same organization. A personal project with no organization cannot use Shared VPC or hierarchical firewall policies. In that case run Modules 5 and 6 in a single project and skip steps 3, 5, 6 and 8 here.
The default network is not part of this design. New projects created by older flows still include a default network with permissive rules. Step 2 checks and removes it. The Organization Policy constraints/compute.skipDefaultNetworkCreation (Hour 3) prevents it for good.
Organization ORG_ID Folder lab-network (FOLDER_ID) · firewall policy fp-lab-baseline associated here Firewall policy 1000 allow ssh from IAP · 2000 deny rdp Host project prj-lab-net-hub VPC vpc-lab-hub (custom mode) subnet snet-lab-euw1 10.20.0.0/24 Private Google Access on networkUser granted on this subnet only Cloud Router rtr-lab-euw1 hosts NAT config Cloud NAT nat-lab-egress outbound only Service project prj-lab-app VM vm-lab-app, no external IP uses subnet of the host own quotas and billing link applies to all projects

Figure 1. The target state of the lab. The firewall policy is associated with the folder and so reaches both projects. The VM lives in the service project but uses the host project's subnet.

1 host project 2 enable XPN 3 VPC, subnet 4 attach svc 5 NAT 6 policy Create 1 VM, policy 2 NAT, router 3 detach svc 4 subnet, VPC 5 disable XPN 6 projects Delete (reverse) Each object references the one on its left. Remove from the leaves toward the root.

Figure 2. Creation order on top, deletion order below. The lab's cleanup section follows the bottom row.

In Figure 1 check what is in each project: the network, router and NAT are in the host project, and the VM is the only thing in the service project. The firewall policy line comes from the folder, not from either project.

The animation replays the lab in order: project, Shared VPC, network, attachment, NAT, firewall policy and association. Each step is a real API operation that the commands in the next tab perform.

All commands below are used in the lab. Set the variables once in your shell, then paste commands as shown. Never put credentials in these variables. IDs and addresses in the expected output are illustrative.

export ORG_ID=123456789012
export FOLDER_ID=987654321098
export BILLING_ACCOUNT_ID=0X0X0X-0X0X0X-0X0X0X
export HOST_PROJECT_ID=prj-lab-net-hub-4821
export SERVICE_PROJECT_ID=prj-lab-app-4821
export REGION=europe-west1
export ZONE=europe-west1-b
export GROUP_EMAIL=lab-devs@example.com

gcloud projects create and gcloud billing projects link (write, free)

Purpose. Creates a project under the lab folder and links billing so that the Compute Engine API can be enabled. Creating a project and linking billing is metadata only.

gcloud projects create $HOST_PROJECT_ID \
  --folder=$FOLDER_ID \
  --name="Lab network hub" \
  --labels=env=lab,owner=platform

gcloud billing projects link $HOST_PROJECT_ID \
  --billing-account=$BILLING_ACCOUNT_ID
Create in progress for [https://cloudresourcemanager.googleapis.com/v1/projects/prj-lab-net-hub-4821].
Waiting for [operations/cp.1234567890123456] to finish...done.
billingAccountName: billingAccounts/0X0X0X-0X0X0X-0X0X0X
billingEnabled: true
name: projects/prj-lab-net-hub-4821/billingInfo
projectId: prj-lab-net-hub-4821

Common errors. The project ID you specified is already in use: IDs are globally unique, change the suffix. PERMISSION_DENIED ... resourcemanager.projects.create: you need roles/resourcemanager.projectCreator on the folder. Billing: the caller does not have permission: you need roles/billing.user on the billing account.

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

gcloud services enable compute.googleapis.com --project=$HOST_PROJECT_ID
Operation "operations/acat.p2-123456789012-0a1b2c3d" finished successfully.

gcloud compute shared-vpc enable (write, free)

Purpose. Turns the project into a Shared VPC host project. This requires the Shared VPC Admin role (roles/compute.xpnAdmin) at the organization or folder.

gcloud compute shared-vpc enable $HOST_PROJECT_ID

The command prints nothing on success. Verify with:

gcloud compute shared-vpc get-host-project $HOST_PROJECT_ID
gcloud compute shared-vpc organizations list-host-projects $ORG_ID
kind: compute#project
name: prj-lab-net-hub-4821
xpnProjectStatus: HOST

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

gcloud compute networks create vpc-lab-hub \
  --project=$HOST_PROJECT_ID \
  --subnet-mode=custom

gcloud compute networks subnets create snet-lab-euw1 \
  --project=$HOST_PROJECT_ID \
  --network=vpc-lab-hub \
  --region=$REGION \
  --range=10.20.0.0/24 \
  --enable-private-ip-google-access
NAME           SUBNET_MODE  BGP_ROUTING_MODE  IPV4_RANGE  GATEWAY_IPV4
vpc-lab-hub    CUSTOM       REGIONAL

NAME            REGION        NETWORK      RANGE
snet-lab-euw1   europe-west1  vpc-lab-hub  10.20.0.0/24

Cost. Free. Networks and subnets have no charge.

gcloud compute shared-vpc associated-projects add (write, free)

gcloud compute shared-vpc associated-projects add $SERVICE_PROJECT_ID \
  --host-project=$HOST_PROJECT_ID
(no output on success)
gcloud compute shared-vpc list-associated-resources $HOST_PROJECT_ID
RESOURCE_ID           RESOURCE_TYPE
prj-lab-app-4821      PROJECT

gcloud compute networks subnets add-iam-policy-binding (write, free)

gcloud compute networks subnets add-iam-policy-binding snet-lab-euw1 \
  --project=$HOST_PROJECT_ID \
  --region=$REGION \
  --member="group:$GROUP_EMAIL" \
  --role="roles/compute.networkUser"
Updated IAM policy for subnetwork [snet-lab-euw1].
bindings:
- members:
  - group:lab-devs@example.com
  role: roles/compute.networkUser
etag: BwYabc12345=
version: 1

gcloud compute routers create and nats create (write, low)

gcloud compute routers create rtr-lab-euw1 \
  --project=$HOST_PROJECT_ID --network=vpc-lab-hub --region=$REGION

gcloud compute routers nats create nat-lab-egress \
  --project=$HOST_PROJECT_ID --router=rtr-lab-euw1 --region=$REGION \
  --auto-allocate-nat-external-ips --nat-all-subnet-ip-ranges \
  --enable-logging --log-filter=ERRORS_ONLY

Cost. Low (usually well under a few USD per day for this lab): the NAT gateway is metered by gateway time and by data processed. Budgets send alerts and do not cap spend.

gcloud compute firewall-policies (write, free)

Purpose. Creates a hierarchical policy at the organization, adds two rules, and associates it with the lab folder. Rules and policies have no direct charge.

gcloud compute firewall-policies create \
  --organization=$ORG_ID \
  --short-name=fp-lab-baseline \
  --description="Lab baseline"

gcloud compute firewall-policies rules create 1000 \
  --firewall-policy=fp-lab-baseline --organization=$ORG_ID \
  --direction=INGRESS --action=allow \
  --src-ip-ranges=35.235.240.0/20 --layer4-configs=tcp:22 \
  --description="Allow SSH from IAP"

gcloud compute firewall-policies rules create 2000 \
  --firewall-policy=fp-lab-baseline --organization=$ORG_ID \
  --direction=INGRESS --action=deny \
  --src-ip-ranges=0.0.0.0/0 --layer4-configs=tcp:3389 \
  --description="Deny RDP from anywhere"

gcloud compute firewall-policies associations create \
  --firewall-policy=fp-lab-baseline --organization=$ORG_ID \
  --folder=$FOLDER_ID --name=assoc-lab-folder

Check gcloud compute firewall-policies --help for the flags in your SDK version; the policy can be referred to by its numeric ID or, together with --organization, by its short name. Verify:

gcloud compute firewall-policies associations list --organization=$ORG_ID --format="table(name,attachmentTarget)"
gcloud compute firewall-policies describe fp-lab-baseline --organization=$ORG_ID
NAME                ATTACHMENT_TARGET
assoc-lab-folder    folders/987654321098
Production use. Every command here has a Terraform resource (google_compute_shared_vpc_host_project, google_compute_shared_vpc_service_project, google_compute_subnetwork_iam_member, google_compute_router_nat, google_compute_firewall_policy, google_compute_firewall_policy_rule, google_compute_firewall_policy_association). Use the console and the CLI to learn, and Terraform to run it (Hour 7).

Lab 7: build the network hub in a sandbox (about 10 minutes of work, low cost)

Goal. Create a host project, a Shared VPC network with one subnet, a service project that uses it, Cloud NAT, and a firewall policy associated with a sandbox folder. Prove each layer, then delete everything.

Prerequisites.

  • A sandbox organization and a sandbox folder (FOLDER_ID). Never run this in production folders. Hierarchical firewall policies and Shared VPC need an organization.
  • Roles: roles/resourcemanager.projectCreator on the folder, roles/billing.user on the billing account, roles/compute.xpnAdmin on the folder or organization, roles/compute.orgFirewallPolicyAdmin on the organization, and roles/compute.networkAdmin in the host project (project owners have it). If one is missing, ask the platform team or use a sandbox organization of your own.
  • A budget set on the billing account (Hour 1, Module 3). Budgets send alerts and do not cap spend.
  • A group (GROUP_EMAIL) in your Cloud Identity domain for the subnet grant. For a solo test use your own user with user:you@example.com.
  • Variables from the commands tab exported in the shell. No keys, no passwords.

IDs in the expected output are illustrative.

  1. Create the host project and link billing. Run the projects create, billing projects link and services enable commands for HOST_PROJECT_ID.
    Verify: gcloud projects describe $HOST_PROJECT_ID --format="value(parent.id,labels.env)"
    987654321098	lab
  2. Remove the default network, if present.
    gcloud compute networks list --project=$HOST_PROJECT_ID
    gcloud compute firewall-rules list --project=$HOST_PROJECT_ID --format="value(name)" | xargs -r -n1 gcloud compute firewall-rules delete --project=$HOST_PROJECT_ID --quiet
    gcloud compute networks delete default --project=$HOST_PROJECT_ID --quiet
    Verify: gcloud compute networks list --project=$HOST_PROJECT_ID returns Listed 0 items. In Cloud Shell the xargs -r form works. In a shell without it, delete the four default rules by name (default-allow-icmp, default-allow-internal, default-allow-rdp, default-allow-ssh).
  3. Enable Shared VPC on the host. gcloud compute shared-vpc enable $HOST_PROJECT_ID.
    Verify: gcloud compute shared-vpc organizations list-host-projects $ORG_ID lists HOST_PROJECT_ID.
  4. Create the custom VPC and the shared subnet with Private Google Access.
    Verify: gcloud compute networks subnets describe snet-lab-euw1 --project=$HOST_PROJECT_ID --region=$REGION --format="value(ipCidrRange,privateIpGoogleAccess)"
    10.20.0.0/24	True
  5. Create and attach the service project. Create SERVICE_PROJECT_ID under the same folder, link billing, enable compute.googleapis.com, then run associated-projects add.
    Verify: gcloud compute shared-vpc list-associated-resources $HOST_PROJECT_ID lists the service project.
  6. Grant subnet-level access. Run subnets add-iam-policy-binding for GROUP_EMAIL.
    Verify: gcloud compute networks subnets get-iam-policy snet-lab-euw1 --project=$HOST_PROJECT_ID --region=$REGION shows the group with roles/compute.networkUser.
  7. Check what the service project can see. This command lists the subnets that the caller may use from the service project:
    gcloud compute networks subnets list-usable --project=$SERVICE_PROJECT_ID
    PROJECT              REGION        NETWORK      SUBNET         RANGE
    prj-lab-net-hub-4821 europe-west1  vpc-lab-hub  snet-lab-euw1  10.20.0.0/24
    If the list is empty, the caller does not have roles/compute.networkUser on the subnet. Group membership changes can take a few minutes.
  8. Create the router and the NAT gateway in the host project.
    Verify: gcloud compute routers nats describe nat-lab-egress --router=rtr-lab-euw1 --region=$REGION --project=$HOST_PROJECT_ID --format="value(name,natIpAllocateOption)"
    nat-lab-egress	AUTO_ONLY
  9. Create the firewall policy, its rules and the association. Run the firewall-policies commands from the commands tab.
    Verify: gcloud compute firewall-policies associations list --organization=$ORG_ID shows assoc-lab-folder with target folders/FOLDER_ID.
  10. Test it with a small VM in the service project.
    gcloud compute instances create vm-lab-app \
      --project=$SERVICE_PROJECT_ID --zone=$ZONE \
      --machine-type=e2-micro --no-address \
      --subnet=projects/$HOST_PROJECT_ID/regions/$REGION/subnetworks/snet-lab-euw1 \
      --image-family=debian-12 --image-project=debian-cloud
    gcloud compute ssh vm-lab-app --project=$SERVICE_PROJECT_ID --zone=$ZONE --tunnel-through-iap
    On the VM run curl -s -o /dev/null -m 8 -w "%{http_code}\n" https://example.com. Expected: 200 (NAT works). SSH succeeded through IAP, which proves that rule 1000 matched. If SSH fails with a timeout, check that the IAP API is enabled and that the policy is associated with the folder that contains both projects.

Expected result. A host project with Shared VPC enabled, one attached service project, a usable subnet, a working NAT gateway and a policy with two rules associated to the folder. A VM with no external IP reaches the internet and accepts SSH from IAP only.

Cost. Low (usually well under a few USD per day for this lab): one e2-micro VM and one NAT gateway for the time the lab runs. Everything else is free. Budgets send alerts and do not cap spend. Do the cleanup the same day.

Cleanup (in this order).

# 1. VM, then NAT and router
gcloud compute instances delete vm-lab-app --project=$SERVICE_PROJECT_ID --zone=$ZONE --quiet
gcloud compute routers nats delete nat-lab-egress --router=rtr-lab-euw1 --region=$REGION --project=$HOST_PROJECT_ID --quiet
gcloud compute routers delete rtr-lab-euw1 --region=$REGION --project=$HOST_PROJECT_ID --quiet

# 2. Firewall policy: association, rules, policy
gcloud compute firewall-policies associations delete assoc-lab-folder --firewall-policy=fp-lab-baseline --organization=$ORG_ID --quiet
gcloud compute firewall-policies rules delete 1000 --firewall-policy=fp-lab-baseline --organization=$ORG_ID --quiet
gcloud compute firewall-policies rules delete 2000 --firewall-policy=fp-lab-baseline --organization=$ORG_ID --quiet
gcloud compute firewall-policies delete fp-lab-baseline --organization=$ORG_ID --quiet

# 3. Detach the service project, then remove the network
gcloud compute shared-vpc associated-projects remove $SERVICE_PROJECT_ID --host-project=$HOST_PROJECT_ID
gcloud compute networks subnets delete snet-lab-euw1 --region=$REGION --project=$HOST_PROJECT_ID --quiet
gcloud compute networks delete vpc-lab-hub --project=$HOST_PROJECT_ID --quiet

# 4. Disable Shared VPC, then delete both projects
gcloud compute shared-vpc disable $HOST_PROJECT_ID
gcloud projects delete $SERVICE_PROJECT_ID --quiet
gcloud projects delete $HOST_PROJECT_ID --quiet

Verify cleanup. gcloud projects list --filter="parent.id=$FOLDER_ID" shows no lab projects (deleted projects stay in a pending state for 30 days and can be restored). gcloud compute firewall-policies list --organization=$ORG_ID no longer lists fp-lab-baseline. If you reserved static addresses, release them too.

Real cases (typical patterns)

  • The lab as a template. A platform team turned this exact sequence into a Terraform module called "network hub". It creates the host project, enables Shared VPC, creates the VPC and subnets from a reviewed address plan, binds networkUser per subnet to team groups, and creates one router and NAT per region. New environments take minutes, and each environment gets the same baseline firewall policy association.
  • Teardown that left a hole. A sandbox clean-up script deleted the service project but not the host project's subnet grants and DNS zone bindings. Later, a new project reused the same group and silently inherited access to an old subnet. The fix was a checklist and Terraform, so deleting a service project also removes its bindings.
  • Baseline policy surprises. A folder-level deny rule for RDP was added after a security review. One team's jump host stopped working, because the rule applied to every project below. The incident showed that associations are powerful. The team now tests new rules in a sandbox folder, uses logging on deny rules, and rolls them out folder by folder.

Practices

  • Label lab and sandbox projects (env=lab, owner=..., expires=YYYY-MM-DD) so that a scheduled job can find and delete forgotten ones.
  • Keep the host project separate from workloads. No application VMs in the host, only the network resources.
  • Grant roles/compute.networkUser to groups on specific subnets. Grant roles/compute.xpnAdmin only to the platform group, and review it.
  • Associate policies with folders, not individual projects. A policy that is attached to dozens of projects one by one cannot be audited.
  • Create new firewall policy rules in a sandbox folder first, with logging enabled. A rule that blocks the wrong thing is hard to see after it applies.
  • Run the lab commands from Cloud Shell or a controlled workstation with your own user, not with a service account key. Use impersonation if you need a service account.
Security note. Do not leave the default network or its default allow rules in the host project. Do not grant roles/compute.networkUser at the organization or folder to a broad group; one grant then covers every subnet that is ever created. The Shared VPC Admin role can attach any project to the host, which is a path to every subnet, so protect it like an administrator role.

Symptoms and first checks

SymptomLikely causeFirst check
gcloud compute shared-vpc enable fails with a permission errorMissing roles/compute.xpnAdmin, or the project has no organizationgcloud projects describe HOST_PROJECT_ID --format="value(parent.type,parent.id)"
associated-projects add failsProject is in another organization, or already attached to a different hostgcloud compute shared-vpc get-host-project SERVICE_PROJECT_ID
Subnet missing from list-usableNo networkUser on that subnet for the caller; propagation delaygcloud compute networks subnets get-iam-policy SUBNET --region=REGION --project=HOST_PROJECT_ID
VM creation fails with Required 'compute.subnetworks.use' permissionSame as above, or the service project's service account lacks the roleGrant the role to the principal that creates the VM
VM has no internet accessNAT created in the wrong project or region, or NAT scope excludes the subnetgcloud compute routers nats describe NAT --router=ROUTER --region=REGION --project=HOST_PROJECT_ID
SSH through IAP times outPolicy rule missing, association on the wrong folder, or IAP API not enabledgcloud compute firewall-policies associations list --organization=ORG_ID
Firewall policy delete failsPolicy still has associationsDelete the associations, then the rules, then the policy
Network or subnet cannot be deletedA router, NAT, VM or forwarding rule still uses itgcloud compute networks subnets describe SUBNET --region=REGION --format="value(usedBy)" (or list instances in all service projects)
shared-vpc disable failsService projects are still attachedgcloud compute shared-vpc list-associated-resources HOST_PROJECT_ID

Triage order

  1. Which project is the command running against (--project or gcloud config get project)? Host and service projects are easy to mix up.
  2. Is the project in the organization and folder you expect?
  3. Do the roles exist at the right scope (organization or folder for admin roles, subnet for networkUser)?
  4. Read back the resource you just created with its describe or list.
  5. For traffic, test one layer at a time: route, NAT, firewall policy, VPC rule, DNS.
  6. For deletion errors, find what still references the object, and delete it first.

Video content changes often, so the links below are search pages and official documentation rather than pinned videos. Check the date of a video against the current documentation, because Shared VPC and firewall policy features change.

Official reading: Shared VPC overview · Provision Shared VPC · Hierarchical firewall policies · Set up and manage Cloud NAT.

or score ≥ 70% on the quiz

Module 8 · Troubleshooting networks

53–60 · A layered triage for no egress, private DNS failures, invisible shared subnets, firewall priority conflicts and CIDR overlap
TroubleshootingConnectivity TestsFirewall evaluationCIDR overlap7 min
Learning objectives
  • Apply a layered triage (identity, route, firewall, NAT, DNS, application) to any "it cannot connect" report in a Shared VPC.
  • Use Connectivity Tests, effective firewall listings, routes and logs to find which layer blocks a packet.
  • Fix the five most common landing-zone network failures: no egress, private DNS not resolving, shared subnet not visible, firewall priority conflicts and overlapping CIDR ranges.

The short answer

Almost every network ticket in a landing zone says "it cannot connect". The fastest way through is to stop guessing and walk the layers in a fixed order, from the platform down to the application. Each layer has one read-only command that proves it is healthy. The first layer that is not healthy is your problem. This module gives you the order, the commands and the five patterns that cause most tickets.

The triage layers

#LayerQuestionFirst command
1Identity and projectAre you testing the right project and principal? Is the resource where you think it is?gcloud config list, gcloud compute instances describe VM --format="value(networkInterfaces[0].network,networkInterfaces[0].subnetwork)"
2Network attachmentIs the VM on the shared network and the expected subnet?gcloud compute networks subnets list-usable --project=SERVICE_PROJECT_ID
3RoutesIs there a route to the destination, with a next hop that works?gcloud compute routes list --project=HOST_PROJECT_ID --filter="network:NETWORK"
4Firewall (all levels)Which rule decides for this packet, from the organization policy down to the VPC rule?gcloud compute instances network-interfaces get-effective-firewalls VM --zone=ZONE
5NAT or external IPFor internet traffic, does a NAT gateway cover this subnet? For Google APIs, is Private Google Access on?gcloud compute routers nats describe NAT --router=ROUTER --region=REGION
6DNSDoes the name resolve to the expected address from the VM?dig +short NAME @169.254.169.254
7Application and OSIs the service listening? Is a host firewall or proxy in the way?ss -ltnp, curl -v, host firewall status

Run the layers in order. A route problem looks identical to a firewall problem from the application ("timeout"), and a DNS problem looks like a NAT problem if you only test by name. Test by IP address first to remove DNS from the picture, then by name.

The five patterns

1. No egress

Symptom. Timeouts to internet hosts; apt and pip hang; curl to a Google API times out. Causes, in order of frequency. No NAT for the subnet or region; NAT in the wrong project (service instead of host); Private Google Access off for API-only traffic; an egress deny in a policy; a missing default route after someone deleted default-route-to-internet in a hardened network; port exhaustion under load. Check. NAT describe, subnet privateIpGoogleAccess, routes list, effective firewalls (egress), NAT logs.

2. Private DNS not resolving

Symptom. NXDOMAIN or SERVFAIL for an internal name. Causes. The zone is not attached to the VM's network (project mixed up with network); the record is missing or has a trailing-dot mistake; a more specific zone shadows the name (longest suffix); the forwarding target is unreachable; a peering zone lacks roles/dns.peer; an override zone for googleapis.com exists but gcr.io or pkg.dev are missing. Check. dig @169.254.169.254 from the VM, zone describe for networks, record-sets list.

3. Shared subnet not visible

Symptom. The subnet is missing in the console or gcloud compute instances create --subnet=... fails with compute.subnetworks.use. Causes. No roles/compute.networkUser on the subnet for the person or for the service account that creates the resource (managed instance groups use the Google APIs service agent PROJECT_NUMBER@cloudservices.gserviceaccount.com, GKE uses its own service agents); service project not attached; subnet in a different region than the zone; propagation after a group change. Check. shared-vpc list-associated-resources, subnets get-iam-policy, subnets list-usable.

4. Firewall priority conflicts

Symptom. A rule that "should allow" does nothing, or traffic is blocked and nobody can find the rule. Causes. A hierarchical policy at the organization or folder matched first (and it does not appear in firewall-rules list); two rules in the same policy with the same priority are not allowed, but two rules with close priority and opposite actions are easily misread; goto_next was used where allow was meant; the allow rule targets a tag or service account that the VM does not carry; the rule is for the wrong direction; the rule exists but the destination uses another protocol. Check. Effective firewalls on the interface, then logging on the suspect rule.

5. CIDR overlap

Symptom. Subnet creation fails with an overlap error; VPN or peering creation fails; or connections work from some networks only. Causes. Two networks use the same private range (the classic 10.0.0.0/16 everywhere), a subnet overlaps with an on-premises range, or a secondary range for GKE overlaps with a primary range. Check. Compare ranges from subnets list with the IP plan; an overlap cannot be fixed by a flag. The repair is to renumber one side, which usually means recreating resources, or to use Private Service Connect for the overlapping service.

Firewall evaluation order, once more

  1. Organization firewall policy rules, by priority (lowest number first).
  2. Folder firewall policy rules, from the topmost folder down to the folder that contains the project.
  3. VPC firewall rules and global network firewall policy rules (the order between these two is set per network, with VPC rules first by default).
  4. Regional network firewall policies.
  5. Implied rules: allow all egress, deny all ingress, at the lowest priority.

goto_next in a policy rule means "this level has no opinion, continue with the next level". An allow or deny action ends the evaluation. Rules with goto_next are how a central policy delegates a decision to the project owners.

What it is confused with

Often confusedDifference
Route vs firewallA route says where a packet may go. A firewall says whether it may go. A missing route and a deny rule both give a timeout. Check both.
Timeout vs refusedA timeout usually means a drop (firewall, route, NAT). A connection refused means the packet arrived and nothing listens, so the network is fine.
Connectivity Test vs a real connectionA Connectivity Test analyzes configuration, so it can show a path as reachable even when the application is down. Always follow it with a real test from the VM.
Firewall logs vs VPC Flow LogsFirewall rule logging records connections that match a rule you chose. Flow Logs sample all traffic on a subnet. Use rule logging to prove a rule matched; use Flow Logs to see what flows exist.

Common misunderstandings

"I created an allow rule, so it must work." A deny in a higher level wins before your rule is read. Always read the effective list.
"The VM is in my project, so I own its network." In a Shared VPC the routes, NAT, firewall rules and DNS zones are in the host project. Opening a ticket with the network team costs less than an hour of local experiments.
"Ping works, so the network is fine." ICMP and TCP are filtered separately. Test the real protocol and port.
Report: it cannot connect 1 Right project, VM and subnet? 2 Route to the destination? 3 Effective firewall: allowed at every level? 4 NAT or Private Google Access? 5 DNS answer correct? 6 Application listening? Platform Policy Workload list-usable · describe routes list get-effective-firewalls nats describe · PGA dig · curl · ss Stop at the first layer that fails. Change one thing, then test again from the beginning.

Figure 1. The triage ladder. Each rung has a read-only command in the right column. A timeout at the application only means that the layers above were not proven.

Organization hierarchical policy rules by priority Folders hierarchical policy top folder to lower VPC network level VPC firewall rules network firewall policy Implied rules allow all egress deny all ingress How to read it allow or deny in a level ends the evaluation: no lower level is read. goto_next passes the decision to the next level. Priority numbers are compared only inside one policy or rule set. Hierarchical rules are not listed by gcloud compute firewall-rules list.

Figure 2. The order in which firewall levels are evaluated for a packet. A rule at priority 100 in the VPC can never override a deny at priority 5000 in a folder policy.

In Figure 1 notice that the ladder moves from the platform team's layers to the workload's layers. In Figure 2 see that the arrows only go one way, so a decision made early is final.

The animation follows a Connectivity Test that finds an egress deny rule, then the fix and the re-run. It shows the same order that you use by hand: route first, firewall levels next, and NAT after the packet is allowed.

All commands in this module are read-only unless marked. Run them with an identity that can view the host project and the service project. IDs and addresses in the expected output are illustrative.

gcloud network-management connectivity-tests create (write, free to low)

Purpose. Analyses the path from a source to a destination and returns the first thing that blocks it. Creating a test is a metadata operation; configuration analysis is free of charge, and live data-plane tests, where available, have their own pricing. Check the Network Intelligence Center documentation before running many.

gcloud services enable networkmanagement.googleapis.com --project=SERVICE_PROJECT_ID

gcloud network-management connectivity-tests create test-app-to-web \
  --project=SERVICE_PROJECT_ID \
  --source-instance=projects/SERVICE_PROJECT_ID/zones/ZONE/instances/vm-lab-app \
  --destination-ip-address=203.0.113.10 \
  --destination-port=443 \
  --protocol=TCP
Create request issued for: [test-app-to-web]
Waiting for operation [operation-1234567890-abc] to complete...done.
Created connectivity test [test-app-to-web].
gcloud network-management connectivity-tests describe test-app-to-web \
  --project=SERVICE_PROJECT_ID \
  --format="yaml(reachabilityDetails.result,reachabilityDetails.traces[0].steps)"
reachabilityDetails:
  result: UNREACHABLE
  traces:
  - steps:
    - state: START_FROM_INSTANCE
    - state: APPLY_EGRESS_FIREWALL_RULE
      firewall:
        displayName: deny-all-egress
        action: DENY
    - state: ABORT

Flags. --source-instance and --destination-ip-address (or --destination-instance) define the path; --destination-port and --protocol narrow the test. For Shared VPC, create the test in the project that owns the source and make sure you may view the host project. Check gcloud network-management connectivity-tests create --help for the flags in your SDK version.

Common errors. PERMISSION_DENIED on the host project: the analysis needs permission to read the network configuration (for example roles/compute.networkViewer on the host). A result of REACHABLE with a failing application: the configuration is fine, look at the application and the host.

gcloud compute instances network-interfaces get-effective-firewalls (read, free)

Purpose. Lists all firewall rules that apply to a VM's network interface, including hierarchical policies, in order. This is the most useful single command for a firewall priority conflict.

gcloud compute instances network-interfaces get-effective-firewalls vm-lab-app \
  --project=SERVICE_PROJECT_ID --zone=ZONE --network-interface=nic0
TYPE                 SOURCE           DIRECTION  PRIORITY  ACTION     DESCRIPTION
org-firewall-policy  fp-lab-baseline  INGRESS    1000      allow      Allow SSH from IAP
org-firewall-policy  fp-lab-baseline  INGRESS    2000      deny       Deny RDP from anywhere
network-firewall     vpc-lab-hub      EGRESS     100       deny       deny-all-egress
network-firewall     vpc-lab-hub      EGRESS     65535     allow      implied-allow-egress

The exact column names depend on your SDK version. The point is the order and the source of each rule.

gcloud compute routes list (read, free)

gcloud compute routes list --project=HOST_PROJECT_ID \
  --filter="network:vpc-lab-hub" \
  --format="table(name,destRange,nextHopGateway.basename(),nextHopPeering,priority)"
NAME                          DEST_RANGE     NEXT_HOP_GATEWAY         NEXT_HOP_PEERING  PRIORITY
default-route-to-internet     0.0.0.0/0      default-internet-gateway                   1000
default-route-snet-lab-euw1   10.20.0.0/24                                              0

Purpose. Confirms that a route to the destination exists. If you see no 0.0.0.0/0 route in a hardened network, internet and some Google API paths are intentionally closed.

gcloud compute networks subnets list-usable and get-iam-policy (read, free)

gcloud compute networks subnets list-usable --project=SERVICE_PROJECT_ID
gcloud compute networks subnets get-iam-policy SUBNET --region=REGION --project=HOST_PROJECT_ID \
  --format="yaml(bindings)"

Purpose. The two commands that explain "shared subnet not visible". The first shows what the caller can use. The second shows who has roles/compute.networkUser on the subnet.

gcloud compute routers nats describe and NAT logs (read, free)

gcloud compute routers nats describe NAT --router=ROUTER --region=REGION --project=HOST_PROJECT_ID

gcloud logging read \
  'resource.type="nat_gateway" AND jsonPayload.allocation_status="DROPPED"' \
  --project=HOST_PROJECT_ID --limit=5 \
  --format="table(timestamp,jsonPayload.connection.src_ip,jsonPayload.connection.dest_ip,jsonPayload.allocation_status)"
TIMESTAMP                     SRC_IP     DEST_IP        ALLOCATION_STATUS
2026-11-25T10:21:04.120Z      10.20.0.5  203.0.113.10   DROPPED

NAT logging must be enabled on the gateway (Module 5). Log queries are billed only by Cloud Logging's normal rules; reads of a few entries are free in practice.

gcloud dns managed-zones describe and dig (read, free)

gcloud dns managed-zones describe ZONE --project=HOST_PROJECT_ID \
  --format="yaml(dnsName,visibility,privateVisibilityConfig)"
dig +short NAME @169.254.169.254

Purpose. Shows which networks see a zone, and what the resolver in the VM's network answers. Run dig on the VM.

gcloud compute firewall-policies rules update --enable-logging (write, low)

Purpose. Turns on logging for a rule that you suspect, to prove that traffic matches it. Logging volume is billed by Cloud Logging, so use it temporarily.

gcloud compute firewall-policies rules update 2000 \
  --firewall-policy=fp-lab-baseline --organization=ORG_ID --enable-logging

Check gcloud compute firewall-policies rules update --help for the flags in your SDK version. Read the log with:

gcloud logging read 'logName:"compute.googleapis.com%2Ffirewall" AND jsonPayload.rule_details.priority=2000' \
  --project=SERVICE_PROJECT_ID --limit=5
Production use. Save these commands as a runbook ("network triage") and make the same read-only role available to the on-call team: roles/compute.networkViewer on host projects and the network management viewer role for Connectivity Tests. Triage that requires a ticket to get access is slow triage.

Lab 8: break it on purpose, then find it (about 15 minutes, low cost)

Goal. Take the environment from Module 7, introduce three faults one at a time, and use only the triage commands to find each. This trains the order of the layers more than any list.

Prerequisites. The Module 7 lab environment still running (host project, shared VPC, snet-lab-euw1, NAT, policy, vm-lab-app). If you cleaned it up, rebuild it first. Enable the Network Management API in the service project. IDs in the expected output are illustrative.

  1. Baseline. On the VM: curl -s -o /dev/null -m 8 -w "%{http_code}\n" https://example.com returns 200.
  2. Fault 1: no NAT. From your workstation, delete the NAT gateway: gcloud compute routers nats delete nat-lab-egress --router=rtr-lab-euw1 --region=REGION --project=HOST_PROJECT_ID --quiet. The curl now returns 000.
    Find it. Run the layer commands in order: subnets list-usable, routes list, get-effective-firewalls (egress allowed), then nats describe returns NOT_FOUND. Re-create the gateway (Module 5 command) and test again.
  3. Fault 2: egress deny. Create a VPC rule that blocks outbound HTTPS:
    gcloud compute firewall-rules create deny-egress-https \
      --project=HOST_PROJECT_ID --network=vpc-lab-hub \
      --direction=EGRESS --action=DENY --rules=tcp:443 \
      --destination-ranges=0.0.0.0/0 --priority=100
    The curl now fails again, although NAT exists.
    Find it. Run get-effective-firewalls. The deny shows with priority 100. Run a Connectivity Test and read the step APPLY_EGRESS_FIREWALL_RULE. Delete the rule: gcloud compute firewall-rules delete deny-egress-https --project=HOST_PROJECT_ID --quiet.
  4. Fault 3: private DNS. Create a private zone lab.example.internal. attached to a second, empty VPC network (create vpc-lab-empty with --subnet-mode=custom) and not to vpc-lab-hub, add an A record, and resolve it from the VM. It returns NXDOMAIN.
    Find it. gcloud dns managed-zones describe ... --format="yaml(privateVisibilityConfig)" shows the network list without vpc-lab-hub. Update the zone with gcloud dns managed-zones update ZONE --networks=vpc-lab-hub and resolve again.
  5. Write the runbook. In five lines write the order in which you checked the layers and the command you used for each. This list is the deliverable.

Expected result. For each fault you named the layer, the command that proved it and the fix, in under five minutes each.

Cost. Low (usually well under a few USD per day) for the VM and the NAT gateway. Budgets send alerts and do not cap spend.

Cleanup. Delete the test rule and the lab DNS zone (records first), then follow the Module 7 cleanup order. Delete connectivity tests: gcloud network-management connectivity-tests delete test-app-to-web --project=SERVICE_PROJECT_ID.

Real cases (typical patterns)

  • The "mystery" deny. A team created an allow rule for a new service and it never worked. The VPC rule list showed the rule at priority 100. The cause was a folder policy rule at priority 800 that denied the port. After the team learned to read the effective firewall list, the average time to find such rules went from hours to minutes, and the central team added a naming convention (fp-baseline-deny-rdp) that explains the rule's purpose.
  • The overlap that appeared in month nine. A project used 10.0.0.0/16 in two separate networks. It worked until the company connected one network to on-premises, which already used 10.0.0.0/16. Renumbering took a quarter. Afterwards the IP plan became a reviewed file in the network repository and a pull-request check rejects overlapping ranges.
  • Missing network user for managed groups. A new managed instance group could not create VMs in a shared subnet: Required 'compute.subnetworks.use' permission. The user had the role, but the group's creating identity (the Google APIs service agent of the service project) did not. The fix was a grant on the subnet for that service agent, added to the project factory so every new project gets it.

Practices

  • Keep a short triage runbook per scenario (no egress, DNS, shared subnet, firewall, overlap) with the exact commands, and review it after each incident.
  • Give on-call engineers read-only network visibility across host and service projects. Do not give them write access by default.
  • Log what you may need to prove: NAT errors, firewall deny rules for sensitive ports, DNS query logs on sensitive networks. Set retention and cost expectations first.
  • Validate changes in a sandbox folder with a Connectivity Test before rolling out a policy at folder or organization level.
  • Use CI to check CIDR plans, rule names and priorities before applying Terraform.
  • After an incident, add the missing guardrail (an alert, a CI check, a documented grant) and not only a fix.
Security note. Under pressure people open firewalls wide ("allow 0.0.0.0/0 tcp:0-65535") to see if it helps. Make that action need review, log it, and set an expiry. Temporary diagnostic rules left behind are one of the most common causes of exposed services. Also avoid giving broad roles such as roles/compute.networkAdmin to application teams to "unblock" them; a narrow subnet grant is almost always enough.

Symptoms and first checks

SymptomLikely causeFirst check
Timeout to a public IP from a VM without external IPNo NAT for the subnet, or NAT in the wrong project or regiongcloud compute routers nats describe NAT --router=ROUTER --region=REGION --project=HOST_PROJECT_ID
Timeout only to Google APIsPrivate Google Access off, wrong DNS answer for restricted VIP, or egress denysubnets describe --format="get(privateIpGoogleAccess)"; dig +short storage.googleapis.com
NXDOMAIN for an internal nameZone not attached to the VM's network, or record missingmanaged-zones describe then record-sets list
Name resolves, connection times outFirewall or route; DNS is fineget-effective-firewalls, routes list, Connectivity Test
Allow rule exists, traffic still blockedA higher level (organization or folder policy) denies firstget-effective-firewalls on the interface
Cannot create a VM in a shared subnetNo roles/compute.networkUser on the subnet for the caller or the creating service accountsubnets get-iam-policy
Invalid IPv4Range ... overlaps with existing subnetworkCIDR overlap inside the networkgcloud compute networks subnets list --network=NETWORK --format="table(name,region,ipCidrRange)"
VPN or peering creation fails with an overlap or route conflictCIDR overlap with another network or on-premisesCompare ranges with the IP plan, then renumber or use Private Service Connect
Connections reset or hang after a whileStateful firewall or NAT idle timeout, port exhaustionNAT logs for DROPPED, minPortsPerVm in nats describe
Connectivity Test says REACHABLE but the app failsService not listening, host firewall, application proxy settingsss -ltnp and curl -v from the VM; the network layers are cleared

Triage order

  1. Reproduce from the real source (the VM or subnet), with an IP address first, then with the name.
  2. Confirm the project, network and subnet of the source and the destination.
  3. Run a Connectivity Test and read the first failing step.
  4. Read the effective firewall list for the interface, including hierarchical policies.
  5. Check routes, then NAT or Private Google Access, then DNS.
  6. Only after the network layers are cleared, check the application, the OS firewall and the proxy.
  7. Change one thing at a time, write down the change, and remove temporary rules when done.

Video content changes often, so the links below are search pages and official documentation rather than pinned videos. Check the date of a video against the current Network Intelligence Center documentation.

Official reading: Connectivity Tests overview · Firewall policies overview · Troubleshooting Cloud NAT · VPC networks.

or score ≥ 70% on the quiz

Command cheat sheet

Network hub: Shared VPC, firewall policies, egress and DNS
Hour 4

Hour 4 command cheat sheet: network hub

Use this page next to the lab. Replace the UPPERCASE placeholders (PROJECT_ID, HOST_PROJECT_ID, SERVICE_PROJECT_ID, ORG_ID, FOLDER_ID, REGION, ZONE, GROUP_EMAIL). Commands marked write change state; "free" means metadata only, "low" means a small metered resource (usually well under a few USD per day for a lab). Budgets send alerts and do not cap spend. Where a flag is not listed here, check gcloud … --help for the flags in your SDK version.

VPC networks and subnets

CommandPurposeKey flagsGotcha
gcloud compute networks create NAME (write, free)Create a VPC network--subnet-mode=custom, --project, --bgp-routing-modeWithout custom you may get auto mode, with a subnet in every region and ranges you did not plan.
gcloud compute networks subnets create NAME (write, free)Create a regional subnet--network, --region, --range, --secondary-range=NAME=CIDR, --enable-private-ip-google-accessThe primary range cannot be shrunk, only expanded. Overlap with any peered or on-premises range is refused.
gcloud compute networks subnets describe NAME (read, free)Read range, Private Google Access, secondary ranges--region, --format="get(privateIpGoogleAccess)"Region is required. A subnet in another region is a different object.
gcloud compute networks subnets update NAME (write, free)Turn Private Google Access on, expand a range--enable-private-ip-google-access, --regionSetting is per subnet, not per network. Check every region in use.
gcloud compute networks delete default (write, free)Remove the default network--quietDelete its firewall rules first. Prevent recreation with constraints/compute.skipDefaultNetworkCreation.
gcloud compute routes list (read, free)Check which routes exist--filter="network:NETWORK", --format=table(...)A missing 0.0.0.0/0 route is intentional in hardened networks, so confirm before adding one.

Shared VPC

CommandPurposeKey flagsGotcha
gcloud compute shared-vpc enable HOST_PROJECT_ID (write, free)Make a project a Shared VPC hostProject ID onlyNeeds roles/compute.xpnAdmin and an organization. Enable the Compute Engine API first.
gcloud compute shared-vpc associated-projects add SERVICE_PROJECT_ID (write, free)Attach a service project--host-project=HOST_PROJECT_IDA project can have only one host. Both must be in the same organization.
gcloud compute shared-vpc list-associated-resources HOST_PROJECT_ID (read, free)List attached service projectsHost project IDRun it before disabling or deleting anything.
gcloud compute shared-vpc get-host-project SERVICE_PROJECT_ID (read, free)Find which host a project usesProject IDEmpty result means the project is not attached.
gcloud compute shared-vpc associated-projects remove SERVICE_PROJECT_ID (write, free)Detach a service project--host-projectDelete the service project's VMs and load balancers on the shared network first.
gcloud compute shared-vpc disable HOST_PROJECT_ID (write, free)Stop being a hostProject IDFails while service projects are attached.
gcloud compute networks subnets add-iam-policy-binding SUBNET (write, free)Grant subnet-level network access--region, --project=HOST, --member, --role=roles/compute.networkUserAlso grant it to the service agents that create instance groups or clusters, not only to people.
gcloud compute networks subnets list-usable (read, free)Show which shared subnets the caller can use--project=SERVICE_PROJECT_IDEmpty list usually means a missing networkUser grant or an attachment problem.

IP address plan

CommandPurposeKey flagsGotcha
gcloud compute networks subnets list (read, free)Dump all ranges to compare against the plan--network, --format="table(name,region,ipCidrRange,secondaryIpRanges)"Include secondary ranges in the overlap check. GKE uses them for Pods and Services.
gcloud compute networks subnets expand-ip-range NAME (write, free)Grow a subnet's primary range--region, --prefix-lengthExpansion is one way. Plan the larger block in advance, so that the neighbouring addresses are free.
gcloud compute addresses create NAME (write, free while in use, charged when reserved and idle)Reserve an internal or external address--region or --global, --subnet, --addresses, --purposeRelease unused static external addresses; idle ones are billed.

Hierarchical firewall policies

CommandPurposeKey flagsGotcha
gcloud compute firewall-policies create (write, free)Create a policy at the organization--organization=ORG_ID, --short-name, --descriptionA policy with no association does nothing. Needs roles/compute.orgFirewallPolicyAdmin.
gcloud compute firewall-policies rules create PRIORITY (write, free)Add a rule--firewall-policy, --organization, --direction, --action=allow|deny|goto_next, --src-ip-ranges, --dest-ip-ranges, --layer4-configs=tcp:22, --enable-loggingLower number is evaluated first. Priorities are unique inside a policy. goto_next passes the decision down.
gcloud compute firewall-policies associations create (write, free)Apply the policy to the organization or a folder--firewall-policy, --organization, --folder=FOLDER_ID, --nameAssociation affects every project below the node immediately. Test in a sandbox folder.
gcloud compute firewall-policies associations list (read, free)See where policies apply--organization or --folderRules from hierarchical policies are not shown by firewall-rules list.
gcloud compute firewall-policies describe POLICY (read, free)Read rules and associations--organizationThe policy may need to be identified by numeric ID in some SDK versions.
gcloud compute instances network-interfaces get-effective-firewalls VM (read, free)See all rules that apply to a VM interface--zone, --network-interface=nic0The best first command for "traffic is blocked and I cannot find why".

Egress: Cloud Router and Cloud NAT

CommandPurposeKey flagsGotcha
gcloud compute routers create NAME (write, free)Create the router that hosts NAT--network, --region, --asn (only for BGP)Regional. Create in the host project for a Shared VPC.
gcloud compute routers nats create NAME (write, low)Create the NAT gateway--router, --region, --auto-allocate-nat-external-ips or --nat-external-ip-pool, --nat-all-subnet-ip-ranges, --enable-logging, --log-filterGives outbound access only. Use manual IPs when partners allow-list addresses.
gcloud compute routers nats describe NAME (read, free)Verify scope and allocation--router, --regionCheck sourceSubnetworkIpRangesToNat, so the subnet is covered.
gcloud compute routers get-nat-mapping-info ROUTER (read, free)Show NAT IP and ports per VM--regionGood for port-exhaustion checks and "which IP does this VM use".
gcloud compute routers nats delete NAME (write, free)Remove the gateway--router, --region, --quietDelete the NAT before the router. Release static NAT addresses afterwards.
gcloud compute addresses create ... --purpose=PRIVATE_SERVICE_CONNECT (write, low)Reserve an address for a Private Service Connect endpoint--global, --addresses, --networkThe address must be outside every subnet range. Check the flags in your SDK version.

Cloud DNS

CommandPurposeKey flagsGotcha
gcloud services enable dns.googleapis.com (write, free)Enable the API--projectNeeded before any gcloud dns command.
gcloud dns managed-zones create NAME (write, low)Create a private, forwarding or peering zone--dns-name="x.example.internal.", --visibility=private, --networks, --forwarding-targets, --target-network, --target-projectDNS name needs a trailing dot. A private zone shadows a public name it does not contain.
gcloud dns record-sets create NAME (write, low)Add a record--zone, --type, --ttl, --rrdatasName ends with a dot. Lower the TTL before a planned change.
gcloud dns record-sets list (read, free)Read the records of a zone--zone, --filterThe default NS and SOA records are always present.
gcloud dns managed-zones describe NAME (read, free)See which networks see a zone--format="yaml(privateVisibilityConfig)"First check when a name does not resolve from a VM.
gcloud dns policies create NAME (write, low)Inbound forwarding and query logging--networks, --enable-inbound-forwarding, --enable-loggingQuery logs are billed by Cloud Logging volume.
gcloud dns managed-zones delete NAME (write, free)Remove a zoneZone nameDelete non-default records first, or the delete fails.

Triage commands

CommandPurposeKey flagsGotcha
gcloud network-management connectivity-tests create NAME (write, free to low)Analyze the path from a source to a destination--source-instance, --destination-ip-address, --destination-port, --protocolAnalyses configuration. A REACHABLE result does not prove the application works.
gcloud network-management connectivity-tests describe NAME (read, free)Read the result and the blocking step--format="yaml(reachabilityDetails)"Delete tests when finished.
gcloud logging read 'resource.type="nat_gateway" ...' (read, free)Find NAT drops and errors--limit, --formatNAT logging must be enabled on the gateway.
dig +short NAME @169.254.169.254 (on the VM)Ask the VPC resolver directly+short, @resolverBypasses application and OS caches. Test by IP first, then by name.

Cleanup order

  1. VMs, then NAT gateway, then Cloud Router.
  2. Firewall policy: association, rules, then the policy.
  3. DNS records, then zones and policies.
  4. Detach service projects, then delete subnets and the VPC network.
  5. gcloud compute shared-vpc disable, then delete the projects.
Check before production. Flags and defaults change between gcloud CLI releases. Run gcloud COMMAND --help for your version, and test in a sandbox folder before you change policies at the organization.

Capstone lab and final quiz

Network hub: Shared VPC, firewall policies, egress and DNS
Hour 4

Capstone lab: a private network hub with a workload that proves it

Goal. Build the Hour 4 network hub from scratch and prove it with one workload. At the end you have: a host project and a service project, a custom-mode Shared VPC with one shared subnet, a Cloud Router and Cloud NAT for outbound traffic, a private DNS zone that resolves an internal name, a firewall policy associated with a folder, and a VM with no external IP in the service project that (a) accepts SSH only through Identity-Aware Proxy, (b) reaches the internet through NAT, (c) reaches Google APIs through Private Google Access, and (d) resolves a private name. Then you delete everything in the right order.

This lab combines Modules 1 to 8. It takes about 30 to 40 minutes. IDs in the expected output are illustrative.

Prerequisites

  • A sandbox organization, a sandbox folder (FOLDER_ID) and a billing account (BILLING_ACCOUNT_ID). Do not use production folders.
  • Roles: roles/resourcemanager.projectCreator on the folder, roles/billing.user on the billing account, roles/compute.xpnAdmin and roles/compute.orgFirewallPolicyAdmin on the organization, and owner or equivalent rights on the two lab projects. roles/dns.admin in the host project.
  • A budget set on the billing account before you start (Hour 1). Budgets send alerts and do not cap spend.
  • A group (GROUP_EMAIL) for the subnet grant. For a solo test, use your own user (user:you@example.com).
  • The gcloud CLI (current release channel) or Cloud Shell. No service account keys and no passwords.

Set the variables

export ORG_ID=123456789012
export FOLDER_ID=987654321098
export BILLING_ACCOUNT_ID=0X0X0X-0X0X0X-0X0X0X
export HOST_PROJECT_ID=lz-net-host-xyz123
export SERVICE_PROJECT_ID=lz-net-app-xyz123
export REGION=europe-west1
export ZONE=europe-west1-b
export GROUP_EMAIL=lab-devs@example.com

Steps with verification

  1. Create the two projects, link billing and enable APIs.
    for P in $HOST_PROJECT_ID $SERVICE_PROJECT_ID; do
      gcloud projects create $P --folder=$FOLDER_ID --labels=env=lab,owner=platform
      gcloud billing projects link $P --billing-account=$BILLING_ACCOUNT_ID
      gcloud services enable compute.googleapis.com --project=$P
    done
    gcloud services enable dns.googleapis.com iap.googleapis.com --project=$HOST_PROJECT_ID
    gcloud services enable iap.googleapis.com networkmanagement.googleapis.com --project=$SERVICE_PROJECT_ID
    Verify. gcloud projects list --filter="parent.id=$FOLDER_ID" --format="table(projectId,labels.env)" lists both projects with lab.
    PROJECT_ID           ENV
    lz-net-host-xyz123   lab
    lz-net-app-xyz123    lab
    Cost: free.
  2. Remove the default network from both projects, if it exists.
    for P in $HOST_PROJECT_ID $SERVICE_PROJECT_ID; do
      for R in $(gcloud compute firewall-rules list --project=$P --format="value(name)"); do
        gcloud compute firewall-rules delete $R --project=$P --quiet
      done
      gcloud compute networks delete default --project=$P --quiet
    done
    Verify. gcloud compute networks list --project=$HOST_PROJECT_ID prints Listed 0 items. (the command may print an error if the default network never existed; that is fine).
  3. Enable Shared VPC on the host. gcloud compute shared-vpc enable $HOST_PROJECT_ID
    Verify. gcloud compute shared-vpc organizations list-host-projects $ORG_ID shows lz-net-host-xyz123.
  4. Create the VPC and the shared subnet.
    gcloud compute networks create vpc-hub --project=$HOST_PROJECT_ID --subnet-mode=custom
    
    gcloud compute networks subnets create snet-app-euw1 \
      --project=$HOST_PROJECT_ID --network=vpc-hub --region=$REGION \
      --range=10.30.0.0/24 --enable-private-ip-google-access
    Verify. gcloud compute networks subnets describe snet-app-euw1 --project=$HOST_PROJECT_ID --region=$REGION --format="value(ipCidrRange,privateIpGoogleAccess)"
    10.30.0.0/24	True
    Cost: free.
  5. Attach the service project and grant subnet-level access.
    gcloud compute shared-vpc associated-projects add $SERVICE_PROJECT_ID --host-project=$HOST_PROJECT_ID
    
    gcloud compute networks subnets add-iam-policy-binding snet-app-euw1 \
      --project=$HOST_PROJECT_ID --region=$REGION \
      --member="group:$GROUP_EMAIL" --role="roles/compute.networkUser"
    Verify. gcloud compute shared-vpc list-associated-resources $HOST_PROJECT_ID lists the service project, and gcloud compute networks subnets list-usable --project=$SERVICE_PROJECT_ID lists snet-app-euw1 for a caller that holds the role. If you are the project owner and the subnet is missing, also grant the role to your own user.
  6. Create the Cloud Router and Cloud NAT in the host project.
    gcloud compute routers create rtr-hub-euw1 --project=$HOST_PROJECT_ID --network=vpc-hub --region=$REGION
    
    gcloud compute routers nats create nat-hub-egress \
      --project=$HOST_PROJECT_ID --router=rtr-hub-euw1 --region=$REGION \
      --auto-allocate-nat-external-ips --nat-all-subnet-ip-ranges \
      --enable-logging --log-filter=ERRORS_ONLY
    Verify. gcloud compute routers nats describe nat-hub-egress --router=rtr-hub-euw1 --region=$REGION --project=$HOST_PROJECT_ID --format="value(name,sourceSubnetworkIpRangesToNat)"
    nat-hub-egress	ALL_SUBNETWORKS_ALL_IP_RANGES
    Cost: low. The NAT gateway is metered by gateway time and data processed.
  7. Create the private DNS zone and a record.
    gcloud dns managed-zones create zone-hub-internal \
      --project=$HOST_PROJECT_ID \
      --dns-name="hub.example.internal." \
      --description="Capstone private zone" \
      --visibility=private --networks=vpc-hub
    
    gcloud dns record-sets create api.hub.example.internal. \
      --project=$HOST_PROJECT_ID --zone=zone-hub-internal \
      --type=A --ttl=60 --rrdatas=10.30.0.10
    Verify. gcloud dns record-sets list --zone=zone-hub-internal --project=$HOST_PROJECT_ID --filter="type=A"
    NAME                       TYPE  TTL  DATA
    api.hub.example.internal.  A     60   10.30.0.10
    Cost: low.
  8. Create the hierarchical firewall policy and associate it with the folder.
    gcloud compute firewall-policies create --organization=$ORG_ID \
      --short-name=fp-hub-baseline --description="Capstone baseline"
    
    gcloud compute firewall-policies rules create 1000 \
      --firewall-policy=fp-hub-baseline --organization=$ORG_ID \
      --direction=INGRESS --action=allow \
      --src-ip-ranges=35.235.240.0/20 --layer4-configs=tcp:22 \
      --description="Allow SSH from IAP"
    
    gcloud compute firewall-policies rules create 2000 \
      --firewall-policy=fp-hub-baseline --organization=$ORG_ID \
      --direction=INGRESS --action=deny \
      --src-ip-ranges=0.0.0.0/0 --layer4-configs=tcp:3389 \
      --description="Deny RDP from anywhere"
    
    gcloud compute firewall-policies associations create \
      --firewall-policy=fp-hub-baseline --organization=$ORG_ID \
      --folder=$FOLDER_ID --name=assoc-hub-folder
    Verify. gcloud compute firewall-policies associations list --organization=$ORG_ID --format="table(name,attachmentTarget)"
    NAME               ATTACHMENT_TARGET
    assoc-hub-folder   folders/987654321098
    Check gcloud compute firewall-policies --help for the flags in your SDK version. Cost: free.
  9. Create the workload VM in the service project, with no external IP.
    gcloud compute instances create vm-hub-app \
      --project=$SERVICE_PROJECT_ID --zone=$ZONE \
      --machine-type=e2-micro --no-address \
      --subnet=projects/$HOST_PROJECT_ID/regions/$REGION/subnetworks/snet-app-euw1 \
      --image-family=debian-12 --image-project=debian-cloud
    Verify. gcloud compute instances describe vm-hub-app --project=$SERVICE_PROJECT_ID --zone=$ZONE --format="value(networkInterfaces[0].networkIP,networkInterfaces[0].accessConfigs)" returns an address in 10.30.0.0/24 and an empty access config list.
    10.30.0.2
    Cost: low (one e2-micro for the time the lab runs).
  10. Prove the four properties from the VM.
    gcloud compute ssh vm-hub-app --project=$SERVICE_PROJECT_ID --zone=$ZONE --tunnel-through-iap
    Then, on the VM:
    # (a) SSH worked through IAP, so policy rule 1000 matched.
    # (b) Internet through NAT
    curl -s -o /dev/null -m 8 -w "%{http_code}\n" https://example.com
    # (c) Google APIs through Private Google Access
    curl -s -o /dev/null -m 8 -w "%{http_code}\n" https://storage.googleapis.com/
    # (d) Private DNS name from the zone
    dig +short api.hub.example.internal @169.254.169.254
    200
    400
    10.30.0.10
    A 400 from the storage endpoint proves that the API was reached (no bucket path was given). A 000 in (b) or (c) means the connection failed.
  11. Break and find one fault (5 minutes). Run gcloud compute routers nats delete nat-hub-egress --router=rtr-hub-euw1 --region=$REGION --project=$HOST_PROJECT_ID --quiet. Repeat the internet test on the VM: it now returns 000 while (c) and (d) still work. Use the triage ladder from Module 8 (route, effective firewall, NAT) to find the missing NAT, then re-create it with the step 6 command.
    Verify. The internet test returns 200 again after the gateway exists.

Expected result

PropertyHow you proved itResult
VM has no external IPdescribe shows no access configOnly a 10.30.0.x address
SSH only through IAPPolicy rule 1000 allows 35.235.240.0/20 on tcp:22SSH through --tunnel-through-iap works
Internet through NATcurl to a public site200
Google APIs without NATcurl to storage.googleapis.com400 (reached)
Private DNSdig against the VPC resolver10.30.0.10

Cost

Low (usually well under a few USD per day for this lab): one e2-micro VM, one NAT gateway, one DNS zone and small data transfer. Everything else is metadata and free. Budgets send alerts and do not cap spend, so do not leave the lab running overnight.

Cleanup (in this order)

# 1. VM, then NAT and router
gcloud compute instances delete vm-hub-app --project=$SERVICE_PROJECT_ID --zone=$ZONE --quiet
gcloud compute routers nats delete nat-hub-egress --router=rtr-hub-euw1 --region=$REGION --project=$HOST_PROJECT_ID --quiet
gcloud compute routers delete rtr-hub-euw1 --region=$REGION --project=$HOST_PROJECT_ID --quiet

# 2. DNS records, then the zone
gcloud dns record-sets delete api.hub.example.internal. --zone=zone-hub-internal --type=A --project=$HOST_PROJECT_ID
gcloud dns managed-zones delete zone-hub-internal --project=$HOST_PROJECT_ID

# 3. Firewall policy: association, rules, policy
gcloud compute firewall-policies associations delete assoc-hub-folder --firewall-policy=fp-hub-baseline --organization=$ORG_ID --quiet
gcloud compute firewall-policies rules delete 1000 --firewall-policy=fp-hub-baseline --organization=$ORG_ID --quiet
gcloud compute firewall-policies rules delete 2000 --firewall-policy=fp-hub-baseline --organization=$ORG_ID --quiet
gcloud compute firewall-policies delete fp-hub-baseline --organization=$ORG_ID --quiet

# 4. Detach, remove the network, disable Shared VPC
gcloud compute shared-vpc associated-projects remove $SERVICE_PROJECT_ID --host-project=$HOST_PROJECT_ID
gcloud compute networks subnets delete snet-app-euw1 --region=$REGION --project=$HOST_PROJECT_ID --quiet
gcloud compute networks delete vpc-hub --project=$HOST_PROJECT_ID --quiet
gcloud compute shared-vpc disable $HOST_PROJECT_ID

# 5. Projects (deleted projects stay restorable for 30 days)
gcloud projects delete $SERVICE_PROJECT_ID --quiet
gcloud projects delete $HOST_PROJECT_ID --quiet

Verify cleanup. gcloud projects list --filter="parent.id=$FOLDER_ID" shows no lab projects (or shows them as pending deletion), and gcloud compute firewall-policies list --organization=$ORG_ID does not list fp-hub-baseline. If you removed the lab folder, delete it last: gcloud resource-manager folders delete FOLDER_ID.

Next step. Turn this page into Terraform (Hour 7): one module for the host project, Shared VPC and subnets, one for NAT and DNS, one for the folder policy, with a pull-request check on the CIDR plan.
Safety. Use only a sandbox organization and folder. Hierarchical firewall policy rules apply to every project under the folder as soon as they are associated.

Knowledge check

Sources and versions

Network hub: Shared VPC, firewall policies, egress and DNS
Hour 4

Reference documentation for Hour 4

These are the official pages behind the modules. Use them to confirm a command, a flag or a limit before you rely on it. Product pages are reorganized from time to time; if a link has moved, search the title on cloud.google.com.

Networking foundations

Firewall

Egress, private access and DNS

Troubleshooting

Command reference and examples

Tool and product versions used in this hour

ToolVersion usedNote
gcloud CLICurrent release channel (check with gcloud version)Commands in this hour are in the GA gcloud compute, gcloud dns, gcloud services, gcloud projects and gcloud network-management groups. Update with gcloud components update, or with your package manager.
Terraform1.x with the Google provider (pin the major version in required_providers)Only referred to in this hour; the full workflow is in Hour 7.
Cloud NAT, Cloud DNS, Shared VPC, firewall policiesGenerally available servicesFeatures such as dynamic port allocation, response policies and regional network firewall policies have their own release notes.
VM image used in labsdebian-12 image familyImage families move forward. Use a family that is current in your project.
Check before production. Command flags, defaults, quotas, roles and product behaviour change between releases. Before you use any command from this course in production: read gcloud COMMAND --help for your installed version, compare with the current documentation above, test in a sandbox folder, and review the plan in your change process. Values in expected output (IDs, addresses, timestamps) are illustrative and are not measurements.

Prices, quotas and limits are not stated in this course because they change. Use the Google Cloud pricing pages and the quota page of your project for current numbers.