# VPC networking A custom-mode VPC, a subnet, outbound internet through Cloud NAT, and a firewall rule. - `auto_create_subnetworks = false` gives a custom-mode network: only the subnets you declare. - `private_ip_google_access = true` lets workloads without external addresses reach Google APIs. - Cloud Run reaches the VPC with Direct VPC egress: `template.vpc_access.network_interfaces` naming this network and subnet. It needs no connector resource. - Firewall rules match by `target_service_accounts` or `target_tags`. A rule with neither applies to the whole network. ```hcl variable "project_id" { type = string description = "Project to deploy into." } variable "region" { type = string description = "Region for regional resources." } resource "google_compute_network" "main" { project = var.project_id name = "main" auto_create_subnetworks = false routing_mode = "REGIONAL" } resource "google_compute_subnetwork" "workloads" { project = var.project_id name = "workloads" region = var.region network = google_compute_network.main.id ip_cidr_range = "10.10.0.0/24" private_ip_google_access = true log_config { aggregation_interval = "INTERVAL_5_SEC" flow_sampling = 0.5 metadata = "INCLUDE_ALL_METADATA" } } resource "google_compute_router" "egress" { project = var.project_id name = "egress" region = var.region network = google_compute_network.main.id } resource "google_compute_router_nat" "egress" { project = var.project_id name = "egress" region = var.region router = google_compute_router.egress.name nat_ip_allocate_option = "AUTO_ONLY" source_subnetwork_ip_ranges_to_nat = "ALL_SUBNETWORKS_ALL_IP_RANGES" log_config { enable = true filter = "ERRORS_ONLY" } } resource "google_compute_firewall" "allow_health_checks" { project = var.project_id name = "allow-health-checks" network = google_compute_network.main.id direction = "INGRESS" priority = 1000 # Google Cloud load balancer health check ranges. source_ranges = ["130.211.0.0/22", "35.191.0.0/16"] target_tags = ["web"] allow { protocol = "tcp" ports = ["8080"] } } resource "google_cloud_run_v2_service" "internal" { project = var.project_id name = "internal" location = var.region ingress = "INGRESS_TRAFFIC_INTERNAL_ONLY" template { containers { image = "us-docker.pkg.dev/cloudrun/container/hello" } vpc_access { egress = "PRIVATE_RANGES_ONLY" network_interfaces { network = google_compute_network.main.id subnetwork = google_compute_subnetwork.workloads.id } } } } ```