Hour 4: Network hub: Shared VPC, firewall policies, egress and 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)
| # | Module | Minutes | Main commands |
|---|---|---|---|
| 1 | VPC fundamentals | 6 | gcloud compute networks create, subnets create, routes list |
| 2 | Shared VPC | 8 | gcloud compute shared-vpc enable, associated-projects add |
| 3 | IP address plan | 7 | subnets create --secondary-range, expand-ip-range |
| 4 | Hierarchical firewall policies | 8 | gcloud compute firewall-policies create, rules create, associations create |
| 5 | Egress and private access | 7 | gcloud compute routers create, routers nats create |
| 6 | Cloud DNS | 7 | gcloud dns managed-zones create, record-sets create |
| 7 | Lab: host project, shared VPC, subnet, NAT, firewall policy | 10 | All of the above, with verification |
| 8 | Troubleshooting networks | 7 | get-effective-firewalls, routes list, nat get-status |
| Total | 60 | ||
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
| Resource | Created in | Cost |
|---|---|---|
| VPC networks, subnets, routes, firewall rules, firewall policies and associations | Modules 1, 3, 4, 7 | Free (metadata only) |
| Shared VPC host enablement and service project attachment | Modules 2, 7 | Free |
| Cloud DNS private zone and a few record sets | Modules 6, 7 | Low (usually well under a few USD per day for this lab) |
| Cloud Router and Cloud NAT gateway | Modules 5, 7 | Low 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, 7 | Low (usually well under a few USD per day). Delete it when the test is done. |
Setup
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
| Role | On | Needed for |
|---|---|---|
roles/compute.xpnAdmin (Shared VPC Admin) | Lab folder or organization | Enable the host project and attach service projects (Modules 2 and 7) |
roles/compute.networkAdmin | Host project | Create networks, subnets, Cloud Router, Cloud NAT |
roles/compute.securityAdmin | Host project | VPC firewall rules (also in the no-organization fallback) |
roles/compute.orgFirewallPolicyAdmin and roles/compute.orgFirewallPolicyUser | Organization | Create and associate hierarchical firewall policies (Module 4) |
roles/dns.admin | Host project | Cloud DNS zones and record sets (Module 6) |
roles/serviceusage.serviceUsageAdmin | Both projects | Enable APIs |
roles/billing.user | Billing account | Link 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
- 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_IDonly 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 listshows the identity you expect.gcloud organizations listshows 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_IDworks (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
- 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
| Piece | Scope | What it does |
|---|---|---|
| VPC network | Global, inside one project | Container for subnets, routes and firewall rules. Has a routing mode (regional or global dynamic routing) and an MTU setting. |
| Subnet | Regional | A primary IPv4 range and optional secondary ranges. Can enable Private Google Access and flow logs. |
| Route | Global (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 policy | Global, regional, or hierarchical | Allow or deny traffic by direction, priority, source or destination, protocol and port, and target. |
| Network interface | Per VM | The 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
- 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.
- Default route. A new network also has a system generated route
0.0.0.0/0to thedefault-internet-gatewayat 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. - 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.
- 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.
- 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
/24therefore gives 252 usable addresses, not 256. The smallest primary IPv4 range you can create is/29.
Auto mode, custom mode, and the default network
| Item | Auto mode network | Custom mode network |
|---|---|---|
| Subnets | One subnet per region, created automatically, each a /20 inside 10.128.0.0/9; new regions add subnets later | None until you create them |
| IP control | Fixed block, cannot overlap with other auto mode networks | You choose every range |
| Hybrid and peering | Ranges can collide with on-premises or other networks; cannot be used with VPN or peering of the same range | Designed to be planned with the rest of the estate |
| Landing zone use | Avoid | Use |
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 with | Difference |
|---|---|
| AWS VPC or Azure VNet | Those 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 zone | A subnet is regional. A VM in any zone of the region can use it. There is no subnet per zone. |
| VPC network vs project | A project can hold several networks. A network lives in one project (or is shared from a host project, Module 2). |
| Firewall rule vs route | A route decides where a packet goes. A firewall rule decides whether it may pass. You need both to be right. |
Common misunderstandings
compute.skipDefaultNetworkCreation at the organization or folder.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.
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
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.
- Set the project and region once:
gcloud config set project PROJECT_ID gcloud config set compute/region REGION
- Enable the API and look at what Google created:
gcloud services enable compute.googleapis.com gcloud compute networks list
Verification. If the list showsdefault AUTO, the organization does not skip default networks. Note the result. - Remove the default network and its four rules (commands in the previous tab). Verification.
gcloud compute networks listnow printsListed 0 items. - Create the custom network
vpc-labwith--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) andGLOBAL. - Create
snet-lab-REGIONwith range10.16.0.0/24and Private Google Access. Verification. Run thesubnets describecommand; the gateway is10.16.0.1. - 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 for10.16.0.0/24at priority 0. - 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. - 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 --quietVerify 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
defaultnetwork. When the company connected the project to on-premises over a VPN, the on-premises address plan used part of10.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-sshanddefault-allow-rdprules from0.0.0.0/0in dozens of projects. The fix was a two-part change: enforcecompute.skipDefaultNetworkCreationand a hierarchical firewall policy (Module 4) that deniestcp:22andtcp:3389except 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).
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
| Symptom | Likely cause | First check |
|---|---|---|
| VM in another region cannot be reached by internal IP | Ingress denied by default; no allow rule | gcloud compute firewall-rules list --filter="network:NETWORK", then run a Connectivity Test |
Invalid IPv4 range / range conflicts on subnet create | Overlap with another subnet, peered VPC or reserved range | gcloud compute networks subnets list --network=NETWORK |
The network resource ... is already being used on delete | Instances, routes, forwarding rules or firewall rules still use it | gcloud compute instances list; gcloud compute routes list --filter="network:NETWORK" |
New project already has a default network | Constraint compute.skipDefaultNetworkCreation not enforced | gcloud org-policies describe compute.skipDefaultNetworkCreation --project=PROJECT_ID --effective |
| VM has no internet although a default route exists | No external IP and no Cloud NAT | gcloud compute instances describe VM --format="value(networkInterfaces[0].accessConfigs)" |
Compute Engine API has not been used in project | API not enabled yet | gcloud services list --enabled --filter="name:compute.googleapis.com" |
| Dynamic routes are not used in another region | Network is in regional routing mode | gcloud compute networks describe NETWORK --format="value(routingConfig.routingMode)" |
Triage order
- Confirm the project and network:
gcloud config list project,gcloud compute networks list. - Confirm the subnet and its range:
subnets describe. Check the IP is inside the range and not one of the four reserved addresses. - Check routes for the destination and the next hop.
- Check firewall rules and policies (direction, priority, target, source or destination).
- 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.
- YouTube search: Google Cloud VPC networks and subnets
- YouTube search: custom mode versus auto mode VPC
- YouTube search: VPC routes and firewall rules
Official reading: VPC networks · Routes · Firewall rules overview · Subnets.
Module 2 · Shared VPC
- 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.networkUserwith gcloud. - Verify the attachment with
list-associated-resourcesand 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 person | Granted on | What they can do |
|---|---|---|
Shared VPC Admin (roles/compute.xpnAdmin) | Organization or folder | Enable 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 project | Create networks, subnets, routes, Cloud Router. Cannot edit firewall rules or SSL certificates. |
Security Admin (roles/compute.securityAdmin) | Host project | Create and edit firewall rules and policies, SSL certificates. |
Service Project Admin (roles/compute.networkUser) | One subnet, or the whole host project | Use shared subnets from the service project: create VMs, instance templates, GKE clusters, internal load balancers in them. |
| Application team | Service project | Compute, storage and application roles in their own project. No rights over the host project. |
How it works internally
- Enable the host. An administrator with
roles/compute.xpnAdminrunsgcloud 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. - Attach service projects.
gcloud compute shared-vpc associated-projects add SERVICE_PROJECT_ID --host-project=HOST_PROJECT_IDlinks the service project. Each service project can have only one host. - Grant subnet access. The administrator grants
roles/compute.networkUseron specific subnets (the common, least-privilege choice) or on the whole host project to groups and service accounts that work in the service project. - 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 checkscompute.subnetworks.useon that subnet before the VM is created. - Service accounts used by services. For some products the account that needs
networkUseris not a human. It is a service agent: for managed instance groups and instance templates it is the Google APIs service accountPROJECT_NUMBER@cloudservices.gserviceaccount.com; for GKE it also includes the GKE service agent, which needsroles/container.hostServiceAgentUseron the host project. Check the product documentation for the exact agents.
When to use Shared VPC and when not to
| Situation | Choice |
|---|---|
| Many teams, one organization, central network team, hybrid connectivity | Shared VPC (a host project per environment, such as prod and non-prod) |
| Two organizations, or a partner project in another organization | VPC Network Peering or Private Service Connect, since Shared VPC works only inside one organization |
| A single small team and one project | A normal VPC network in that project is fine |
| Need a very hard isolation between workloads | Separate VPC networks (maybe separate host projects) and a controlled path between them |
What it is confused with
| Often confused with | Difference |
|---|---|
| VPC Network Peering | Peering 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 RAM | RAM 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 only | IAM alone cannot place a VM from project A on a network of project B. Shared VPC is what enables that. |
Common misunderstandings
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.
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.
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.
- 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)"prints10.16.0.0/20. - Enable the host:
gcloud compute shared-vpc enable HOST_PROJECT_ID. Verification. Rungcloud compute projects describe HOST_PROJECT_ID --format="value(xpnProjectStatus)", which printsHOST. - 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_IDlistsSERVICE_PROJECT_ID. - 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 nonetworkUser(a project owner of the service project does not see host subnets automatically). - Grant the subnet role to the group with
subnets add-iam-policy-bindingas in the command tab. Verification.gcloud compute networks subnets get-iam-policy snet-app-REGION --project=HOST_PROJECT_ID --region=REGIONshowsroles/compute.networkUserforGROUP_EMAIL. - As a member of the group (or with impersonation of a lab service account that has the role), run
list-usableagain. Expected result. The subnetsnet-app-REGIONis listed. - Optional. Create
vm-shared-testin 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 from10.16.0.0/20. - Negative test: remove the binding (
remove-iam-policy-binding) and try to create a second VM. Expected result. The errorRequired '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
networkUserto 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.hostServiceAgentUserwas the first problem they hit.
Practices
- Put host projects in a network folder. Give
roles/compute.xpnAdminto a small group at that folder, not at the organization, if you can. - Use the Organization Policy constraints
constraints/compute.restrictSharedVpcHostProjectsandconstraints/compute.restrictSharedVpcSubnetworksto say which hosts and subnets projects may use. This stops a team from attaching to an unauthorized host. - Grant
networkUserper 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-resourcesto the project factory list regularly.
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
| Symptom | Likely cause | First check |
|---|---|---|
| Shared subnet not listed in the service project | No roles/compute.networkUser on the subnet for the caller; or the project is not attached | gcloud compute networks subnets get-iam-policy SUBNET --region=REGION --project=HOST_PROJECT_ID; list-associated-resources |
Required 'compute.subnetworks.use' permission | Caller (user or service account) lacks networkUser on that subnet | Identify the caller in the error or the audit log, then compare with the subnet policy |
| Managed instance group or GKE fails to create nodes | The service agent (Google APIs service account, GKE service agent) lacks networkUser or hostServiceAgentUser in the host | Read the operation error; list the host project IAM policy for PROJECT_NUMBER@cloudservices.gserviceaccount.com |
shared-vpc enable fails with a permission error | No 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 fails | Project already a host, already attached elsewhere, or an Organization Policy blocks the host | gcloud 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 fails | Resources in service projects still use the shared network | List instances and forwarding rules in service projects that reference the host network |
| VM created but cannot reach other VMs | Firewall in the host project (ingress denied) | gcloud compute firewall-rules list --project=HOST_PROJECT_ID --filter="network:vpc-hub" |
Triage order
- Is the service project attached?
get-host-projectfrom the service side. - Which identity made the call? Read the error text and the audit log; a service agent is a different principal from the person.
- Is
networkUsergranted on the correct subnet (and region)? Useget-iam-policy. - Do Organization Policy constraints restrict hosts or subnets? Use
org-policies describe --effective. - 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.
- YouTube search: Shared VPC host and service projects
- YouTube search: Shared VPC subnet IAM
- YouTube search: Shared VPC versus VPC Network Peering
Official reading: Shared VPC overview · Provision Shared VPC · VPC Network Peering.
Module 3 · IP address plan
- 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/8in a hurry. A plan that keeps clear blocks free lets you absorb the next network.
What: the private address space
| Block | Size | Notes for Google Cloud |
|---|---|---|
10.0.0.0/8 | about 16.7 million addresses | The 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/12 | about 1 million addresses | Good for smaller estates. Careful with Docker, which uses 172.17.0.0/16 on a host by default. |
192.168.0.0/16 | 65,536 addresses | Often 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 addresses | Shared 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
| Prefix | Addresses | Usable (4 reserved) | Typical use |
|---|---|---|---|
/16 | 65,536 | 65,532 | Large region block, GKE pods for a cluster |
/20 | 4,096 | 4,092 | An application tier in a region |
/22 | 1,024 | 1,020 | GKE nodes, or GKE Services range |
/24 | 256 | 252 | Small tier, proxy-only subnet, management |
/28 | 16 | 12 | Small 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
/24in 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
/20gives about 4,000 Services, and a/22about 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
| Block | Owner / purpose | Notes |
|---|---|---|
10.0.0.0/12 | On-premises and branch offices | Reserved. Never used in the cloud. |
10.16.0.0/12 | Google Cloud production | Split into /16 per region: 10.16.0.0/16 europe-west1, 10.17.0.0/16 us-east1, ... |
10.32.0.0/12 | Google Cloud non-production | Same layout as production for easy review. |
10.48.0.0/12 | Shared services, hub, management | Proxy-only subnets, private services access ranges, test. |
10.64.0.0/10 | GKE 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/9 | Unused. Reserved to avoid the auto mode block | Keep free. |
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 with | Difference |
|---|---|
| Subnet = network | The VPC network has no range. Subnets do. Plan at subnet level. |
| Public IP planning | External addresses are assigned by Google (ephemeral or reserved). You plan private ranges. |
| Using NAT to hide overlap | Possible 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
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.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.
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.
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.
- Write the plan as a text table (a file or a note) with these rows:
10.16.0.0/20app tier europe-west1,10.16.64.0/20data tier europe-west1 (not created in this lab),10.16.32.0/22GKE nodes with pods10.64.0.0/16and services10.68.0.0/22, and10.48.0.0/24reserved for private services access. Check on paper that none of the five ranges overlap. - 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. - Make a deliberate error: try to create
snet-clashwith--range=10.64.0.0/20, which is inside the pods range ofsnet-gke-REGION. Expected result. The command fails with an overlap error. Secondary ranges are part of the overlap check. - 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)"shows10.48.0.0,24,VPC_PEERING. - 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. - Expand a range:
gcloud compute networks subnets expand-ip-range snet-app-REGION --region=REGION --prefix-length=19, after you confirm that10.16.0.0/19is free in your plan (in this lab no data subnet exists yet, so it is). Verification.subnets describenow shows10.16.0.0/19. Lesson. Expansion works only into free space, and it cannot be undone. If you had created the data tier at10.16.16.0/20first, the command would fail with a conflict. In your plan, leave a sibling block free for growth. - 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
/20pod range. With the default of a/24per node, it could hold only 16 nodes, and autoscaling stopped at that number. New clusters now use a planned/16or 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/9for 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.
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
| Symptom | Likely cause | First check |
|---|---|---|
| Subnet create fails with an overlap error | Range overlaps a primary or secondary range, a peered VPC, or a reserved range | gcloud 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 missing | Overlap between the networks | gcloud compute networks peerings list and compare ranges on both sides |
| GKE cluster creation fails: not enough IP addresses in the range | Pod or Services range too small | Compare cluster node count and maxPodsPerNode to the pod range size |
Cannot add VMs: IP_SPACE_EXHAUSTED or similar | Subnet full (remember 4 reserved) | subnets describe, then expand-ip-range if the neighbour is free |
| Cloud SQL private IP fails to create | Private services access range missing, exhausted, or overlapping | gcloud services vpc-peerings list --network=NETWORK and gcloud compute addresses list --global |
| On-premises hosts cannot reach a subnet that is reachable from the cloud | Route not advertised, or an on-premises range is more specific | Cloud Router advertisements (Hour 5), on-premises route table |
| Internal load balancer creation fails | No proxy-only subnet in the region | gcloud compute networks subnets list --filter="purpose=REGIONAL_MANAGED_PROXY" |
Triage order
- Name the two ranges that collide, with owners. Use the plan table first, the live list second.
- Decide which side can change. A new subnet is easy; a subnet with VMs, load balancers or a cluster is not.
- 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.
- 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.
- YouTube search: Google Cloud VPC IP address planning
- YouTube search: GKE secondary ranges and pod IP planning
- YouTube search: CIDR and subnetting explained
Official reading: Subnets · GKE VPC-native clusters and alias IPs · Private services access · Best practices and reference architectures for VPC design.
Module 4 · Hierarchical firewall policies
- 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.securityAdminon 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
| Piece | Meaning |
|---|---|
| Policy | A 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. |
| Rule | Priority, direction (INGRESS or EGRESS), match (source or destination ranges, layer 4 protocols and ports), action, targets, logging flag. |
| Action | allow, 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. |
| Target | Which 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. |
| Association | The link between the policy and the node (organization or folder) where it applies. |
How it works internally: evaluation order
- Traffic reaches a VM's network interface. Google Cloud evaluates the organization firewall policy first.
- 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.
- 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.
- 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
| Action | Effect | Typical use |
|---|---|---|
deny | Drop the packet; nothing lower can allow it | Block SSH and RDP from the internet for every project; block known bad ranges |
allow | Pass the packet; the VPC rules are not evaluated | Allow health check ranges and IAP so that nobody can break them by a mistake |
goto_next | Delegate to the next level | Say "projects decide this port", or exclude a trusted range from a broad deny rule |
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?
| Need | Use |
|---|---|
| A rule that every project must have and no project can override | Hierarchical 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 sandbox | Different policies on different folders |
| Rule for one network only | Network firewall policy, or a hierarchical rule with --target-resources naming the network |
What it is confused with
| Often confused with | Difference |
|---|---|
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 policies | Attach 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 constraints | Constraints control API actions (who may create what). Firewall policies control packets at runtime. Both belong to guardrails but they are different systems. |
| Cloud Armor | Cloud Armor filters web traffic at the edge of a load balancer. Firewall policies filter traffic to VM network interfaces inside the VPC. |
Common misunderstandings
goto_next when you want the project rules to decide.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.
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
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.
- Create the policy as in the command tab. Verification.
gcloud compute firewall-policies list --organization=ORG_IDshowsfw-org-baseline. - 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_IDshows 100 before 200. - 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, actiongoto_nextfor 300. - 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.
- Associate the policy with the lab folder:
associations createas in the command tab. Verification.gcloud compute firewall-policies associations list --folder=FOLDER_IDshows the association. - 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-firewallslists 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. - 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_IDis 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, denytcp:22andtcp:3389from0.0.0.0/0at 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/22and35.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/0at 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_nextfor ports that teams manage, andallowonly 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).
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
| Symptom | Likely cause | First check |
|---|---|---|
| VPC allow rule is created but traffic is still blocked | A hierarchical deny matches first | gcloud 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 policy | Health check ranges denied | Rules 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 exists | Duplicate priority in the policy | firewall-policies rules list; choose a free number |
| Association fails: target already has a policy | A node holds one policy only | associations list --folder=FOLDER_ID; delete the old association or add rules to the existing policy |
Required 'compute.firewallPolicies.use' permission (or similar) on association | Missing roles/compute.orgFirewallPolicyUser | Check the IAM policy of the organization and the policy for your identity |
| Rule has no effect on some VMs | Target service account or target resource does not match, or the rule direction is wrong | rules describe, then compare with the VM's service account and network |
| IAP SSH stops working after a deny rule | IAP range 35.235.240.0/20 not allowed before the deny | Rule order: allow IAP at a lower number than the deny; test with gcloud compute ssh VM_NAME --tunnel-through-iap |
Triage order
- Identify the packet: source, destination, protocol, port, direction.
- List the associations for the project's folders and the organization, so you know every policy in the path.
- Walk the policies in order (organization, folders down), reading rules by priority until one matches.
- If the result was goto_next or no match, read the VPC firewall rules and network policies, then the implied rules.
- 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.
- YouTube search: Google Cloud hierarchical firewall policies
- YouTube search: IAP TCP forwarding for SSH
- YouTube search: network firewall policies and secure tags
Official reading: Hierarchical firewall policies · Use hierarchical firewall policies and rules · VPC firewall rules · IAP TCP forwarding.
Module 5 · Egress and private access
- 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
| Destination | Tool | Address the workload uses | Where it is configured |
|---|---|---|---|
| Public internet (package mirrors, partner APIs) | Cloud NAT (云 NAT) | Private source IP, translated to an external NAT IP | NAT gateway on a Cloud Router, per region |
Google APIs and services (*.googleapis.com) | Private Google Access | Private source IP; destination is a public Google IP, reached without NAT | Subnet setting, per subnet |
| Google APIs or a producer service on a private IP of your choice | Private Service Connect (PSC) | Private IP of an endpoint in your VPC | Endpoint (forwarding rule) plus DNS |
| On-premises | Cloud VPN or Cloud Interconnect (Hour 5) | Private IP, over a private route | Cloud 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.
- The VM sends a packet to an internet address. The default route (
0.0.0.0/0, next hopdefault-internet-gateway) matches. - 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.
- The source IP becomes a NAT external IP, and the source port becomes a port from the block that was allocated to that VM.
- 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
| Setting | Options | Use when |
|---|---|---|
| NAT IP allocation | Automatic (--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 scope | All 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. |
| Logging | Off, errors only, translations only, or all | Errors 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.comdefault. 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 overridesgoogleapis.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 confused | Difference |
|---|---|
| Cloud NAT vs Private Google Access | NAT 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 VM | An external IP allows inbound connections (subject to firewall rules). NAT never does. NAT also shares addresses across many VMs. |
| Cloud Router vs Cloud NAT | Cloud 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 APIs | PGA 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 firewall | NAT translates addresses. Firewall policies decide whether traffic is allowed. Both apply: a NAT gateway does not bypass a deny-egress rule. |
Common misunderstandings
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.
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.
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.
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.
- Set the project:
gcloud config set project PROJECT_ID. - 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
- Connect with IAP:
gcloud compute ssh vm-egress-test --zone=ZONE --tunnel-through-iap. If this asks to enable the IAP API, accept it. - 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.com000
- 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
A400response from the storage endpoint without a bucket path is the proof that the API was reached, so the code is fine. A000means the connection failed. - Create the Cloud Router and the NAT gateway with the commands from the previous tab.
- Repeat the internet test on the VM. It must now succeed:
200
- Find the external address that the VM used:
gcloud compute routers get-nat-mapping-info rtr-euw1 --region=REGION. Compare it withcurl -s https://ifconfig.merun 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-rangesto 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, andget-nat-mapping-infoshowed 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.comthat mapped torestricted.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_statusand on the drop reason. Do not logALLpermanently: 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.
Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
| VM cannot reach any internet address, DNS works | No NAT gateway for this subnet range or region | gcloud compute routers nats describe NAT --router=ROUTER --region=REGION; look at sourceSubnetworkIpRangesToNat |
Cannot reach storage.googleapis.com, internet works through NAT | Resolution points to a restricted VIP but the route or firewall blocks it, or DNS override is wrong | nslookup storage.googleapis.com on the VM; check the private zone and the route to 199.36.153.4/30 |
| Cannot reach Google APIs, no NAT | Private Google Access is off on this subnet | gcloud compute networks subnets describe SUBNET --region=REGION --format="get(privateIpGoogleAccess)" |
| Intermittent timeouts to one destination under load | NAT port exhaustion for that destination | Logs filter jsonPayload.allocation_status="DROPPED"; get-nat-mapping-info |
| Partner still blocks the old address | Automatic allocation changed the NAT IP, or the VM is on another gateway | get-nat-mapping-info; switch to manual static addresses |
| NAT works in one region only | NAT is regional; the other region has no router or NAT | gcloud compute routers list --filter="network:vpc-hub" |
| Egress blocked although NAT is fine | An egress deny in a firewall policy or a VPC rule | Network Intelligence Center Connectivity Tests, or gcloud compute firewall-policies listing (Module 4) |
| Shared VPC service project VM has no internet | NAT was created in the service project, or in a different network | NAT must be in the host project on a router of the shared network |
Triage order
- Does the VM have an external IP? If yes, NAT is not used for that VM.
- Is the destination Google or the internet? Pick PGA or NAT accordingly.
- Does DNS resolve to the address you expect (
nslookupordig)? - Does a route exist for the destination, and is the next hop correct (
gcloud compute routes list --filter="network:vpc-hub")? - Is egress allowed by the firewall policies and VPC firewall rules (policies are evaluated top-down, Module 4)?
- Read NAT logs and
get-nat-mapping-infofor 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.
- YouTube search: Google Cloud NAT and Cloud Router explained
- YouTube search: Private Google Access and Private Service Connect
- YouTube search: Cloud NAT port exhaustion troubleshooting
Official reading: Cloud NAT overview · Private Google Access · Private Service Connect · Cloud Router overview.
Module 6 · Cloud DNS
- 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
| Object | What it is | Typical landing-zone use |
|---|---|---|
| Public managed zone | Authoritative 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 list | Internal service names, corp.example.internal, Google APIs override. |
| Forwarding zone | Sends queries for a name to the DNS servers you list (internal IPs, over VPN or Interconnect) | Resolve on-premises names from the cloud. |
| Peering zone | Sends queries for a name to another VPC network's DNS context | Hub network holds the zones; spoke networks peer to it. |
| DNS policy | Network-level settings: inbound forwarding (on-premises can query cloud), alternative name servers, logging | Let on-premises DNS resolve cloud private zones; turn on query logging. |
| Response policy | Overrides specific names or patterns with a set answer or a local data rule, ahead of other zones | Block known-bad domains, override a few names without a full zone. |
| Record set | A name, a type (A, AAAA, CNAME, TXT, SRV and so on), a TTL, and data | The 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:
- Response policy rules for the network, if any. A matching rule answers immediately.
- 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. - 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.comis 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 ofroles/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 confused | Difference |
|---|---|
| Private zone vs public zone with private addresses | A 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 Peering | DNS 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 policy | A 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 Domains | Cloud 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 zones | Internal 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
--dns-name="corp.example.internal." is the form the API expects. Without the trailing dot some tools accept it, others fail.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.
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.
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.
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.
- Enable the API:
gcloud services enable dns.googleapis.com --project=PROJECT_ID. - 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
- Verify the zone:
gcloud dns managed-zones describe zone-lab-internal --format="value(visibility,dnsName)".private lab.example.internal.
- 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. - Connect to the VM:
gcloud compute ssh vm-egress-test --zone=ZONE --tunnel-through-iap(create a VM first if you removed it). - 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
- 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 withNXDOMAIN, because the zone is not on the public internet. - Test the longest-suffix rule: create a record for a name that is not in the zone, for example look up
missing.lab.example.internalon the VM. The answer isNXDOMAIN, not a public answer. - Optional: add a CNAME
www.lab.example.internal.pointing toweb.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
NXDOMAINand the team hard-coded an IP. A forwarding zone plus a firewall rule for the Google DNS range35.199.192.0/19fixed 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 forgotgcr.ioandpkg.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.adminon 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.localor.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.
roles/dns.admin on production projects, since changing a record is the same as redirecting traffic.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Private name returns NXDOMAIN on a VM | Network is not listed in the zone, or the record is missing | gcloud 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 domain | The private zone shadows the public one for names it does not contain | Add the missing records, or use a more specific zone and a forwarding or peering zone |
| Service project VM cannot resolve a host-project zone | VM is on its own network, not the shared one; or the zone is attached to a different network | gcloud compute instances describe VM --format="value(networkInterfaces[0].network)" |
| On-premises name does not resolve from the cloud | No route or firewall rule to the forwarding target, or wrong target IP | dig @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 names | No inbound forwarding policy, or on-premises forwarder points to the wrong address | gcloud dns policies list; gcloud compute addresses list --filter="purpose=DNS_RESOLVER" |
Peering zone returns SERVFAIL | Missing roles/dns.peer, or the target network cannot answer | Run the same query from a VM in the target network; check IAM on the target project |
| Container image pull goes to public IPs | Override zone has googleapis.com but not gcr.io or pkg.dev | dig +short gcr.io on the VM |
| Old address still returned after a change | Client or resolver cache, high TTL | Check the TTL in record-sets list and flush the cache on the client |
Triage order
- Ask the resolver directly:
dig +short NAME @169.254.169.254from the failing VM. This removes application caches. - Confirm the VM's network (not only the project) and the zones attached to it.
- Find the matching zone by longest suffix, then list its record sets.
- For forwarding, test the target from the same network and check route and firewall for port 53.
- Look at DNS query logs (if enabled) and at the Cloud DNS audit logs for recent changes.
- 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.
- YouTube search: Cloud DNS private zones, forwarding and peering
- YouTube search: DNS architecture for Shared VPC and hybrid
- YouTube search: restricted.googleapis.com DNS and VPC Service Controls
Official reading: Cloud DNS overview · Zones overview · Cloud DNS best practices · Configure Private Google Access.
Module 7 · Lab: host project, Shared VPC, subnet, NAT and firewall policy
- 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
| Layer | Resource | Where it lives | Why |
|---|---|---|---|
| Hierarchy | Lab folder (or an existing sandbox folder) with two projects | Organization | Policies and the firewall policy are inherited from the folder |
| Shared VPC | Host project and one attached service project | Host project | Central control of the network, local control of the workloads |
| Network | Custom-mode VPC vpc-lab-hub, subnet snet-lab-euw1 (10.20.0.0/24) | Host project | No default network, planned addresses, Private Google Access on |
| Access | roles/compute.networkUser on the subnet | Subnet in host project | Least privilege: only one subnet is usable |
| Egress | Cloud Router rtr-lab-euw1 and Cloud NAT nat-lab-egress | Host project | Outbound only; no external IP on the VMs |
| Guardrail | Firewall policy fp-lab-baseline with an association to the folder | Organization (policy), folder (association) | One baseline rule set for every project below |
Why this order
- Host project first. It needs the Compute Engine API before it can be made a host or hold a network.
- 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.
- 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.
- NAT after the subnet. The gateway needs a router in the region of the subnet.
- 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.v1in their own project to create VMs androles/compute.networkUseron 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_nextrule hands the decision down. Anallowordenyin 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 confused | Difference |
|---|---|
| Hierarchical firewall policy vs VPC firewall rules | Hierarchical 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 rule | A 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 it | Detaching 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
default network with permissive rules. Step 2 checks and removes it. The Organization Policy constraints/compute.skipDefaultNetworkCreation (Hour 3) prevents it for good.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.
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
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.projectCreatoron the folder,roles/billing.useron the billing account,roles/compute.xpnAdminon the folder or organization,roles/compute.orgFirewallPolicyAdminon the organization, androles/compute.networkAdminin 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 withuser:you@example.com. - Variables from the commands tab exported in the shell. No keys, no passwords.
IDs in the expected output are illustrative.
- Create the host project and link billing. Run the
projects create,billing projects linkandservices enablecommands forHOST_PROJECT_ID.
Verify:gcloud projects describe $HOST_PROJECT_ID --format="value(parent.id,labels.env)"987654321098 lab
- 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_IDreturnsListed 0 items.In Cloud Shell thexargs -rform 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). - Enable Shared VPC on the host.
gcloud compute shared-vpc enable $HOST_PROJECT_ID.
Verify:gcloud compute shared-vpc organizations list-host-projects $ORG_IDlistsHOST_PROJECT_ID. - 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
- Create and attach the service project. Create
SERVICE_PROJECT_IDunder the same folder, link billing, enablecompute.googleapis.com, then runassociated-projects add.
Verify:gcloud compute shared-vpc list-associated-resources $HOST_PROJECT_IDlists the service project. - Grant subnet-level access. Run
subnets add-iam-policy-bindingforGROUP_EMAIL.
Verify:gcloud compute networks subnets get-iam-policy snet-lab-euw1 --project=$HOST_PROJECT_ID --region=$REGIONshows the group withroles/compute.networkUser. - 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 haveroles/compute.networkUseron the subnet. Group membership changes can take a few minutes. - 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
- Create the firewall policy, its rules and the association. Run the
firewall-policiescommands from the commands tab.
Verify:gcloud compute firewall-policies associations list --organization=$ORG_IDshowsassoc-lab-folderwith targetfolders/FOLDER_ID. - 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 runcurl -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
networkUserper 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.networkUserto groups on specific subnets. Grantroles/compute.xpnAdminonly 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.
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
| Symptom | Likely cause | First check |
|---|---|---|
gcloud compute shared-vpc enable fails with a permission error | Missing roles/compute.xpnAdmin, or the project has no organization | gcloud projects describe HOST_PROJECT_ID --format="value(parent.type,parent.id)" |
associated-projects add fails | Project is in another organization, or already attached to a different host | gcloud compute shared-vpc get-host-project SERVICE_PROJECT_ID |
Subnet missing from list-usable | No networkUser on that subnet for the caller; propagation delay | gcloud compute networks subnets get-iam-policy SUBNET --region=REGION --project=HOST_PROJECT_ID |
VM creation fails with Required 'compute.subnetworks.use' permission | Same as above, or the service project's service account lacks the role | Grant the role to the principal that creates the VM |
| VM has no internet access | NAT created in the wrong project or region, or NAT scope excludes the subnet | gcloud compute routers nats describe NAT --router=ROUTER --region=REGION --project=HOST_PROJECT_ID |
| SSH through IAP times out | Policy rule missing, association on the wrong folder, or IAP API not enabled | gcloud compute firewall-policies associations list --organization=ORG_ID |
| Firewall policy delete fails | Policy still has associations | Delete the associations, then the rules, then the policy |
| Network or subnet cannot be deleted | A router, NAT, VM or forwarding rule still uses it | gcloud compute networks subnets describe SUBNET --region=REGION --format="value(usedBy)" (or list instances in all service projects) |
shared-vpc disable fails | Service projects are still attached | gcloud compute shared-vpc list-associated-resources HOST_PROJECT_ID |
Triage order
- Which project is the command running against (
--projectorgcloud config get project)? Host and service projects are easy to mix up. - Is the project in the organization and folder you expect?
- Do the roles exist at the right scope (organization or folder for admin roles, subnet for
networkUser)? - Read back the resource you just created with its
describeorlist. - For traffic, test one layer at a time: route, NAT, firewall policy, VPC rule, DNS.
- 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.
- YouTube search: Shared VPC host and service project setup
- YouTube search: hierarchical firewall policies tutorial
- YouTube search: Cloud NAT private VM lab
Official reading: Shared VPC overview · Provision Shared VPC · Hierarchical firewall policies · Set up and manage Cloud NAT.
Module 8 · Troubleshooting networks
- 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
| # | Layer | Question | First command |
|---|---|---|---|
| 1 | Identity and project | Are 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)" |
| 2 | Network attachment | Is the VM on the shared network and the expected subnet? | gcloud compute networks subnets list-usable --project=SERVICE_PROJECT_ID |
| 3 | Routes | Is there a route to the destination, with a next hop that works? | gcloud compute routes list --project=HOST_PROJECT_ID --filter="network:NETWORK" |
| 4 | Firewall (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 |
| 5 | NAT or external IP | For 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 |
| 6 | DNS | Does the name resolve to the expected address from the VM? | dig +short NAME @169.254.169.254 |
| 7 | Application and OS | Is 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
- Organization firewall policy rules, by priority (lowest number first).
- Folder firewall policy rules, from the topmost folder down to the folder that contains the project.
- VPC firewall rules and global network firewall policy rules (the order between these two is set per network, with VPC rules first by default).
- Regional network firewall policies.
- 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 confused | Difference |
|---|---|
| Route vs firewall | A 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 refused | A 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 connection | A 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 Logs | Firewall 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
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.
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
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.
- Baseline. On the VM:
curl -s -o /dev/null -m 8 -w "%{http_code}\n" https://example.comreturns200. - 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. Thecurlnow returns000.
Find it. Run the layer commands in order:subnets list-usable,routes list,get-effective-firewalls(egress allowed), thennats describereturnsNOT_FOUND. Re-create the gateway (Module 5 command) and test again. - 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
Thecurlnow fails again, although NAT exists.
Find it. Runget-effective-firewalls. The deny shows with priority 100. Run a Connectivity Test and read the stepAPPLY_EGRESS_FIREWALL_RULE. Delete the rule:gcloud compute firewall-rules delete deny-egress-https --project=HOST_PROJECT_ID --quiet. - Fault 3: private DNS. Create a private zone
lab.example.internal.attached to a second, empty VPC network (createvpc-lab-emptywith--subnet-mode=custom) and not tovpc-lab-hub, add an A record, and resolve it from the VM. It returnsNXDOMAIN.
Find it.gcloud dns managed-zones describe ... --format="yaml(privateVisibilityConfig)"shows the network list withoutvpc-lab-hub. Update the zone withgcloud dns managed-zones update ZONE --networks=vpc-lab-huband resolve again. - 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/16in two separate networks. It worked until the company connected one network to on-premises, which already used10.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.
roles/compute.networkAdmin to application teams to "unblock" them; a narrow subnet grant is almost always enough.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
| Timeout to a public IP from a VM without external IP | No NAT for the subnet, or NAT in the wrong project or region | gcloud compute routers nats describe NAT --router=ROUTER --region=REGION --project=HOST_PROJECT_ID |
| Timeout only to Google APIs | Private Google Access off, wrong DNS answer for restricted VIP, or egress deny | subnets describe --format="get(privateIpGoogleAccess)"; dig +short storage.googleapis.com |
NXDOMAIN for an internal name | Zone not attached to the VM's network, or record missing | managed-zones describe then record-sets list |
| Name resolves, connection times out | Firewall or route; DNS is fine | get-effective-firewalls, routes list, Connectivity Test |
| Allow rule exists, traffic still blocked | A higher level (organization or folder policy) denies first | get-effective-firewalls on the interface |
| Cannot create a VM in a shared subnet | No roles/compute.networkUser on the subnet for the caller or the creating service account | subnets get-iam-policy |
Invalid IPv4Range ... overlaps with existing subnetwork | CIDR overlap inside the network | gcloud compute networks subnets list --network=NETWORK --format="table(name,region,ipCidrRange)" |
| VPN or peering creation fails with an overlap or route conflict | CIDR overlap with another network or on-premises | Compare ranges with the IP plan, then renumber or use Private Service Connect |
| Connections reset or hang after a while | Stateful firewall or NAT idle timeout, port exhaustion | NAT logs for DROPPED, minPortsPerVm in nats describe |
| Connectivity Test says REACHABLE but the app fails | Service not listening, host firewall, application proxy settings | ss -ltnp and curl -v from the VM; the network layers are cleared |
Triage order
- Reproduce from the real source (the VM or subnet), with an IP address first, then with the name.
- Confirm the project, network and subnet of the source and the destination.
- Run a Connectivity Test and read the first failing step.
- Read the effective firewall list for the interface, including hierarchical policies.
- Check routes, then NAT or Private Google Access, then DNS.
- Only after the network layers are cleared, check the application, the OS firewall and the proxy.
- 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.
- YouTube search: Connectivity Tests in Network Intelligence Center
- YouTube search: firewall policy evaluation order and troubleshooting
- YouTube search: VPC and Cloud NAT troubleshooting
Official reading: Connectivity Tests overview · Firewall policies overview · Troubleshooting Cloud NAT · VPC networks.
Command cheat sheet
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
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud compute networks create NAME (write, free) | Create a VPC network | --subnet-mode=custom, --project, --bgp-routing-mode | Without 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-access | The 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, --region | Setting is per subnet, not per network. Check every region in use. |
gcloud compute networks delete default (write, free) | Remove the default network | --quiet | Delete 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
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud compute shared-vpc enable HOST_PROJECT_ID (write, free) | Make a project a Shared VPC host | Project ID only | Needs 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_ID | A 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 projects | Host project ID | Run it before disabling or deleting anything. |
gcloud compute shared-vpc get-host-project SERVICE_PROJECT_ID (read, free) | Find which host a project uses | Project ID | Empty result means the project is not attached. |
gcloud compute shared-vpc associated-projects remove SERVICE_PROJECT_ID (write, free) | Detach a service project | --host-project | Delete 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 host | Project ID | Fails 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.networkUser | Also 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_ID | Empty list usually means a missing networkUser grant or an attachment problem. |
IP address plan
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
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-length | Expansion 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, --purpose | Release unused static external addresses; idle ones are billed. |
Hierarchical firewall policies
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud compute firewall-policies create (write, free) | Create a policy at the organization | --organization=ORG_ID, --short-name, --description | A 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-logging | Lower 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, --name | Association 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 --folder | Rules from hierarchical policies are not shown by firewall-rules list. |
gcloud compute firewall-policies describe POLICY (read, free) | Read rules and associations | --organization | The 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=nic0 | The best first command for "traffic is blocked and I cannot find why". |
Egress: Cloud Router and Cloud NAT
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
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-filter | Gives outbound access only. Use manual IPs when partners allow-list addresses. |
gcloud compute routers nats describe NAME (read, free) | Verify scope and allocation | --router, --region | Check sourceSubnetworkIpRangesToNat, so the subnet is covered. |
gcloud compute routers get-nat-mapping-info ROUTER (read, free) | Show NAT IP and ports per VM | --region | Good for port-exhaustion checks and "which IP does this VM use". |
gcloud compute routers nats delete NAME (write, free) | Remove the gateway | --router, --region, --quiet | Delete 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, --network | The address must be outside every subnet range. Check the flags in your SDK version. |
Cloud DNS
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud services enable dns.googleapis.com (write, free) | Enable the API | --project | Needed 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-project | DNS 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, --rrdatas | Name 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, --filter | The 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-logging | Query logs are billed by Cloud Logging volume. |
gcloud dns managed-zones delete NAME (write, free) | Remove a zone | Zone name | Delete non-default records first, or the delete fails. |
Triage commands
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
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, --protocol | Analyses 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, --format | NAT logging must be enabled on the gateway. |
dig +short NAME @169.254.169.254 (on the VM) | Ask the VPC resolver directly | +short, @resolver | Bypasses application and OS caches. Test by IP first, then by name. |
Cleanup order
- VMs, then NAT gateway, then Cloud Router.
- Firewall policy: association, rules, then the policy.
- DNS records, then zones and policies.
- Detach service projects, then delete subnets and the VPC network.
gcloud compute shared-vpc disable, then delete the projects.
gcloud COMMAND --help for your version, and test in a sandbox folder before you change policies at the organization.Capstone lab and final quiz
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.projectCreatoron the folder,roles/billing.useron the billing account,roles/compute.xpnAdminandroles/compute.orgFirewallPolicyAdminon the organization, and owner or equivalent rights on the two lab projects.roles/dns.adminin 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
- 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 withlab.PROJECT_ID ENV lz-net-host-xyz123 lab lz-net-app-xyz123 lab
Cost: free. - 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 doneVerify.gcloud compute networks list --project=$HOST_PROJECT_IDprintsListed 0 items.(the command may print an error if the default network never existed; that is fine). - Enable Shared VPC on the host.
gcloud compute shared-vpc enable $HOST_PROJECT_ID
Verify.gcloud compute shared-vpc organizations list-host-projects $ORG_IDshowslz-net-host-xyz123. - 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. - 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_IDlists the service project, andgcloud compute networks subnets list-usable --project=$SERVICE_PROJECT_IDlistssnet-app-euw1for 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. - 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. - 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. - 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
Checkgcloud compute firewall-policies --helpfor the flags in your SDK version. Cost: free. - 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 in10.30.0.0/24and an empty access config list.10.30.0.2
Cost: low (one e2-micro for the time the lab runs). - 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.254200 400 10.30.0.10
A400from the storage endpoint proves that the API was reached (no bucket path was given). A000in (b) or (c) means the connection failed. - 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 returns000while (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 returns200again after the gateway exists.
Expected result
| Property | How you proved it | Result |
|---|---|---|
| VM has no external IP | describe shows no access config | Only a 10.30.0.x address |
| SSH only through IAP | Policy rule 1000 allows 35.235.240.0/20 on tcp:22 | SSH through --tunnel-through-iap works |
| Internet through NAT | curl to a public site | 200 |
| Google APIs without NAT | curl to storage.googleapis.com | 400 (reached) |
| Private DNS | dig against the VPC resolver | 10.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.
Knowledge check
Sources and versions
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
- VPC networks: global network, regional subnets, auto and custom mode, routes.
- Subnets: primary and secondary ranges, expansion, reserved addresses.
- Routes: system-generated and custom routes, next hops, priority.
- Shared VPC overview and Provision Shared VPC: host and service projects, roles, subnet-level grants.
- Best practices and reference architectures for VPC design: IP planning, hub-and-spoke, Shared VPC.
Firewall
- Hierarchical firewall policies: organization and folder policies, actions, evaluation order.
- Use hierarchical firewall policies and rules: create, rules, associations.
- VPC firewall rules: implied rules and rule logging.
- Network firewall policies: the network-level policy that sits below hierarchical policies.
Egress, private access and DNS
- Cloud NAT overview and Set up and manage Cloud NAT: gateways, IP allocation, ports, logging.
- Troubleshoot Cloud NAT: port exhaustion, logs, common errors.
- Cloud Router overview.
- Private Google Access and Configure Private Google Access:
private.googleapis.comandrestricted.googleapis.com. - Private Service Connect: endpoints for Google APIs and published services.
- Cloud DNS overview, Zones overview and Cloud DNS best practices: public, private, forwarding and peering zones, name resolution order.
Troubleshooting
- Connectivity Tests overview (Network Intelligence Center).
- Use VPC Flow Logs.
Command reference and examples
- gcloud compute reference (networks, subnets, routers, firewall-policies, shared-vpc).
- gcloud dns reference.
- gcloud network-management connectivity-tests reference.
- Enterprise foundations blueprint (security foundations) and the open-source terraform-example-foundation repository, which contains a networks layer with Shared VPC, firewall policies, Cloud NAT and DNS.
- terraform-google-network: Terraform module for VPC networks, subnets and routes.
- Terraform Google provider documentation.
Tool and product versions used in this hour
| Tool | Version used | Note |
|---|---|---|
| gcloud CLI | Current 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. |
| Terraform | 1.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 policies | Generally available services | Features such as dynamic port allocation, response policies and regional network firewall policies have their own release notes. |
| VM image used in labs | debian-12 image family | Image families move forward. Use a family that is current in your project. |
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.