惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
V
Visual Studio Blog
C
Check Point Blog
Google DeepMind News
Google DeepMind News
S
SegmentFault 最新的问题
博客园 - 聂微东
量子位
T
Tailwind CSS Blog
罗磊的独立博客
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Y
Y Combinator Blog
L
LangChain Blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Security Latest
Security Latest
M
MIT News - Artificial intelligence
Know Your Adversary
Know Your Adversary
MongoDB | Blog
MongoDB | Blog
Google DeepMind News
Google DeepMind News
大猫的无限游戏
大猫的无限游戏
H
Help Net Security
爱范儿
爱范儿
T
The Exploit Database - CXSecurity.com
有赞技术团队
有赞技术团队
V
Vulnerabilities – Threatpost
Martin Fowler
Martin Fowler
A
Arctic Wolf
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 司徒正美
Cyberwarzone
Cyberwarzone
阮一峰的网络日志
阮一峰的网络日志
The Hacker News
The Hacker News
Apple Machine Learning Research
Apple Machine Learning Research
宝玉的分享
宝玉的分享
GbyAI
GbyAI
Latest news
Latest news
云风的 BLOG
云风的 BLOG
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
腾讯CDC
AWS News Blog
AWS News Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
Lohrmann on Cybersecurity
博客园 - Franky
S
Securelist
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Threatpost
美团技术团队

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Reusable VPC, Subnets, and Firewall Rules Module
Abraham Naib · 2026-05-09 · via DEV Community

In the previous Terraform labs, I created Google Cloud resources directly from the root configuration.

That worked, but the structure was still quite simple.

Every resource was defined directly inside the main Terraform configuration. For a small lab, that is fine. But as the infrastructure grows, putting everything in one root configuration can become harder to maintain.

So in this lab, I started learning Terraform modules.

The goal is to turn the previous VPC and subnet configuration into a reusable local module.

But instead of only creating one VPC and one subnet, I made the lab slightly more practical by creating:

  • one custom VPC network
  • two subnets
  • two firewall rules
  • reusable module inputs
  • module outputs
  • remote state using Google Cloud Storage

What is a Terraform Module?

A Terraform module is a collection of Terraform configuration files that are managed together.

In simple terms, a module is like a reusable infrastructure component.

For this lab, I created a local module called:

modules/gcp-network

Enter fullscreen mode Exit fullscreen mode

This module is responsible for creating the GCP network resources.

The root configuration calls that module and passes values into it.

Root Module vs Child Module

The folder where I run Terraform commands is the root module.

In this lab, the root module is:

05-gcp-network-module/

Enter fullscreen mode Exit fullscreen mode

The reusable child module is:

05-gcp-network-module/modules/gcp-network/

Enter fullscreen mode Exit fullscreen mode

The root module is the entry point.

The child module is the reusable implementation.

The mental model is:

Root module = caller
Child module = reusable implementation
Child module variables = function parameters
Child module outputs = return values

Enter fullscreen mode Exit fullscreen mode

Since I have written JavaScript before, this feels similar to calling a function.

The root module passes values into the child module, and the child module creates the infrastructure based on those values.

Final Folder Structure

The folder structure for this lab is:

05-gcp-network-module/
├── backend.tf
├── main.tf
├── variables.tf
├── outputs.tf
├── terraform.tfvars
├── terraform.tfvars.example
└── modules/
    └── gcp-network/
        ├── main.tf
        ├── variables.tf
        └── outputs.tf

Enter fullscreen mode Exit fullscreen mode

For GitHub, I only commit:

05-gcp-network-module/
├── backend.tf
├── main.tf
├── variables.tf
├── outputs.tf
├── terraform.tfvars.example
└── modules/
    └── gcp-network/
        ├── main.tf
        ├── variables.tf
        └── outputs.tf

Enter fullscreen mode Exit fullscreen mode

I do not commit:

terraform.tfvars
.terraform/
terraform.tfstate

Enter fullscreen mode Exit fullscreen mode

Backend Configuration

This lab still uses remote state with Google Cloud Storage.

In backend.tf, I configured the GCS backend:

terraform {
  backend "gcs" {
    bucket = "terraform-gcp-learning-lab-terraform-state"
    prefix = "terraform-gcp-learning-lab/05-gcp-network-module"
  }
}

Enter fullscreen mode Exit fullscreen mode

The bucket is:

terraform-gcp-learning-lab-terraform-state

Enter fullscreen mode Exit fullscreen mode

The state path is:

terraform-gcp-learning-lab/05-gcp-network-module/default.tfstate

Enter fullscreen mode Exit fullscreen mode

Each lab should have its own state prefix.

This avoids accidentally mixing state from different labs.

Root main.tf

The root main.tf configures the provider and calls the child module.

terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "6.8.0"
    }
  }
}

provider "google" {
  project = var.project
  region  = var.region
}

module "network" {
  source = "./modules/gcp-network"

  environment    = var.environment
  region         = var.region
  network_name   = var.network_name
  subnets        = var.subnets
  firewall_rules = var.firewall_rules
}

Enter fullscreen mode Exit fullscreen mode

The most important part is this:

module "network" {
  source = "./modules/gcp-network"
}

Enter fullscreen mode Exit fullscreen mode

This tells Terraform to use the local module inside:

modules/gcp-network

Enter fullscreen mode Exit fullscreen mode

The root module passes values such as:

environment
region
network_name
subnets
firewall_rules

Enter fullscreen mode Exit fullscreen mode

into the child module.

Root variables.tf

In the root variables.tf, I declared the values that the lab accepts.

variable "project" {
  description = "The Google Cloud project ID where resources will be created."
  type        = string

  validation {
    condition     = length(var.project) > 0
    error_message = "The project variable must not be empty."
  }
}

variable "region" {
  description = "Default Google Cloud region for regional resources."
  type        = string
  default     = "asia-southeast2"

  validation {
    condition     = contains(["asia-southeast2", "asia-southeast1", "us-central1"], var.region)
    error_message = "Region must be one of: asia-southeast2, asia-southeast1, or us-central1."
  }
}

variable "environment" {
  description = "Environment name used for resource naming."
  type        = string
  default     = "dev"

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be one of: dev, staging, or prod."
  }
}

variable "network_name" {
  description = "Base name of the VPC network."
  type        = string
  default     = "network-module"

  validation {
    condition     = can(regex("^[a-z]([-a-z0-9]*[a-z0-9])?$", var.network_name))
    error_message = "Network name must use lowercase letters, numbers, and hyphens. It must start with a letter and end with a letter or number."
  }
}

variable "subnets" {
  description = "Map of subnets to create inside the VPC."
  type = map(object({
    cidr_range = string
    region     = optional(string)
  }))

  validation {
    condition = alltrue([
      for subnet_key, subnet in var.subnets :
      can(regex("^[a-z]([-a-z0-9]*[a-z0-9])?$", subnet_key)) &&
      can(cidrhost(subnet.cidr_range, 0))
    ])

    error_message = "Each subnet key must be a valid lowercase name, and each cidr_range must be a valid CIDR block."
  }
}

variable "firewall_rules" {
  description = "Map of ingress firewall rules to create."
  type = map(object({
    description   = optional(string)
    source_ranges = list(string)
    target_tags   = optional(list(string), [])
    allow = list(object({
      protocol = string
      ports    = optional(list(string))
    }))
  }))

  default = {}

  validation {
    condition = alltrue(flatten([
      for rule_name, rule in var.firewall_rules : [
        for source_range in rule.source_ranges :
        can(cidrhost(source_range, 0))
      ]
    ]))

    error_message = "Every firewall source range must be a valid CIDR block."
  }
}

Enter fullscreen mode Exit fullscreen mode

This is more advanced than the previous labs because I am no longer passing only simple strings.

For subnets, I used:

map(object({
  cidr_range = string
  region     = optional(string)
}))

Enter fullscreen mode Exit fullscreen mode

For firewall_rules, I used a more complex object structure because each firewall rule can contain:

  • description
  • source ranges
  • target tags
  • allowed protocols and ports

Child Module variables.tf

Inside the child module, I also declared the variables that the module expects.

File:

modules/gcp-network/variables.tf

Enter fullscreen mode Exit fullscreen mode

variable "environment" {
  description = "Environment name used for resource naming."
  type        = string
}

variable "region" {
  description = "Default Google Cloud region for regional resources."
  type        = string
}

variable "network_name" {
  description = "Base name of the VPC network."
  type        = string
}

variable "subnets" {
  description = "Map of subnets to create inside the VPC."
  type = map(object({
    cidr_range = string
    region     = optional(string)
  }))
}

variable "firewall_rules" {
  description = "Map of ingress firewall rules to create."
  type = map(object({
    description   = optional(string)
    source_ranges = list(string)
    target_tags   = optional(list(string), [])
    allow = list(object({
      protocol = string
      ports    = optional(list(string))
    }))
  }))

  default = {}
}

Enter fullscreen mode Exit fullscreen mode

At first, having variables in both the root module and child module felt repetitive.

But the purpose is different.

The root variables receive values from the outside, usually from terraform.tfvars.

The child module variables define the input contract of the reusable module.

The flow is:

terraform.tfvars
      ↓
root variables.tf
      ↓
root main.tf module block
      ↓
child module variables.tf
      ↓
child module main.tf resources

Enter fullscreen mode Exit fullscreen mode

Child Module main.tf

Inside the child module, I defined the actual GCP resources.

File:

modules/gcp-network/main.tf

Enter fullscreen mode Exit fullscreen mode

locals {
  final_network_name = "${var.environment}-${var.network_name}"
}

resource "google_compute_network" "vpc_network" {
  name                    = local.final_network_name
  auto_create_subnetworks = false
}

resource "google_compute_subnetwork" "subnets" {
  for_each = var.subnets

  name          = "${var.environment}-${each.key}-subnet"
  region        = coalesce(each.value.region, var.region)
  network       = google_compute_network.vpc_network.id
  ip_cidr_range = each.value.cidr_range
}

resource "google_compute_firewall" "ingress_rules" {
  for_each = var.firewall_rules

  name          = "${var.environment}-${each.key}"
  network       = google_compute_network.vpc_network.name
  description   = each.value.description
  direction     = "INGRESS"
  source_ranges = each.value.source_ranges
  target_tags   = each.value.target_tags

  dynamic "allow" {
    for_each = each.value.allow

    content {
      protocol = allow.value.protocol
      ports    = allow.value.ports
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

There are several important concepts here.

Using locals

I used a local value to build the final network name:

locals {
  final_network_name = "${var.environment}-${var.network_name}"
}

Enter fullscreen mode Exit fullscreen mode

This means if:

environment  = "dev"
network_name = "network-module"

Enter fullscreen mode Exit fullscreen mode

then the final network name becomes:

dev-network-module

Enter fullscreen mode Exit fullscreen mode

Creating Multiple Subnets with for_each

Instead of creating subnet resources one by one, I used for_each.

resource "google_compute_subnetwork" "subnets" {
  for_each = var.subnets

  name          = "${var.environment}-${each.key}-subnet"
  region        = coalesce(each.value.region, var.region)
  network       = google_compute_network.vpc_network.id
  ip_cidr_range = each.value.cidr_range
}

Enter fullscreen mode Exit fullscreen mode

This lets Terraform create multiple subnet resources from a map.

For example, in my terraform.tfvars, I defined:

subnets = {
  app = {
    cidr_range = "10.40.1.0/24"
  }

  db = {
    cidr_range = "10.40.2.0/24"
  }
}

Enter fullscreen mode Exit fullscreen mode

Terraform then creates:

dev-app-subnet
dev-db-subnet

Enter fullscreen mode Exit fullscreen mode

This is better than duplicating two separate google_compute_subnetwork blocks.

Creating Firewall Rules with for_each

I also used for_each for firewall rules.

resource "google_compute_firewall" "ingress_rules" {
  for_each = var.firewall_rules

  name          = "${var.environment}-${each.key}"
  network       = google_compute_network.vpc_network.name
  description   = each.value.description
  direction     = "INGRESS"
  source_ranges = each.value.source_ranges
  target_tags   = each.value.target_tags

  dynamic "allow" {
    for_each = each.value.allow

    content {
      protocol = allow.value.protocol
      ports    = allow.value.ports
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

This allows me to define firewall rules from a map instead of hardcoding each rule directly in the module.

Using a Dynamic Block

The firewall rule uses a dynamic block:

dynamic "allow" {
  for_each = each.value.allow

  content {
    protocol = allow.value.protocol
    ports    = allow.value.ports
  }
}

Enter fullscreen mode Exit fullscreen mode

I used this because a firewall rule can allow multiple protocols.

For example, the internal rule allows:

  • TCP
  • UDP
  • ICMP

Instead of hardcoding multiple allow blocks, the dynamic block generates them from the input value.

Child Module Outputs

The child module also exposes outputs.

File:

modules/gcp-network/outputs.tf

Enter fullscreen mode Exit fullscreen mode

output "network_name" {
  description = "The name of the VPC network."
  value       = google_compute_network.vpc_network.name
}

output "network_id" {
  description = "The ID of the VPC network."
  value       = google_compute_network.vpc_network.id
}

output "network_self_link" {
  description = "The self-link of the VPC network."
  value       = google_compute_network.vpc_network.self_link
}

output "subnets" {
  description = "Subnets created by this module."

  value = {
    for subnet_key, subnet in google_compute_subnetwork.subnets :
    subnet_key => {
      name       = subnet.name
      id         = subnet.id
      region     = subnet.region
      cidr_range = subnet.ip_cidr_range
      self_link  = subnet.self_link
    }
  }
}

output "firewall_rules" {
  description = "Firewall rules created by this module."

  value = {
    for rule_key, rule in google_compute_firewall.ingress_rules :
    rule_key => {
      name          = rule.name
      id            = rule.id
      source_ranges = rule.source_ranges
      target_tags   = rule.target_tags
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

These outputs allow the root module to consume and display the values created inside the child module.

Root Outputs

The root module then exposes selected module outputs.

File:

outputs.tf

Enter fullscreen mode Exit fullscreen mode

output "network_name" {
  description = "The VPC network name created by the network module."
  value       = module.network.network_name
}

output "network_id" {
  description = "The VPC network ID created by the network module."
  value       = module.network.network_id
}

output "subnets" {
  description = "Subnets created by the network module."
  value       = module.network.subnets
}

output "firewall_rules" {
  description = "Firewall rules created by the network module."
  value       = module.network.firewall_rules
}

output "lab_summary" {
  description = "Summary of this module-based network lab."

  value = {
    project        = var.project
    environment    = var.environment
    region         = var.region
    network_name   = module.network.network_name
    subnet_count   = length(module.network.subnets)
    firewall_count = length(module.network.firewall_rules)
  }
}

Enter fullscreen mode Exit fullscreen mode

The root output references the child module output like this:

module.network.network_name

Enter fullscreen mode Exit fullscreen mode

This means:

Get the network_name output from the network module.

Enter fullscreen mode Exit fullscreen mode

terraform.tfvars

For local values, I used terraform.tfvars.

project      = "terraform-gcp-learning-lab"
region       = "asia-southeast2"
environment  = "dev"
network_name = "network-module"

subnets = {
  app = {
    cidr_range = "10.40.1.0/24"
  }

  db = {
    cidr_range = "10.40.2.0/24"
  }
}

firewall_rules = {
  allow-iap-ssh = {
    description   = "Allow SSH through IAP only."
    source_ranges = ["35.235.240.0/20"]
    target_tags   = ["iap-ssh"]

    allow = [
      {
        protocol = "tcp"
        ports    = ["22"]
      }
    ]
  }

  allow-internal = {
    description   = "Allow internal traffic between lab subnets."
    source_ranges = ["10.40.0.0/16"]

    allow = [
      {
        protocol = "tcp"
        ports    = ["0-65535"]
      },
      {
        protocol = "udp"
        ports    = ["0-65535"]
      },
      {
        protocol = "icmp"
      }
    ]
  }
}

Enter fullscreen mode Exit fullscreen mode

This creates:

  • one VPC
  • two subnets
  • two firewall rules

The IAP SSH source range is:

35.235.240.0/20

Enter fullscreen mode Exit fullscreen mode

This is used for Identity-Aware Proxy TCP forwarding.

I used this instead of opening SSH to:

0.0.0.0/0

Enter fullscreen mode Exit fullscreen mode

because opening SSH to the whole internet is not a good habit.

Initialize Terraform

After preparing the files, I ran:

terraform init

Enter fullscreen mode Exit fullscreen mode

Because this lab uses a module, Terraform also initialized the module.

The expected output includes something like:

Initializing modules...
- network in modules/gcp-network

Enter fullscreen mode Exit fullscreen mode

This is different from the previous labs.

Previously, Terraform initialized only the backend and provider.

Now, Terraform also recognizes the local child module.

Format and Validate

Because this lab has Terraform files inside the module folder, I used:

terraform fmt -recursive

Enter fullscreen mode Exit fullscreen mode

Then I validated the configuration:

terraform validate

Enter fullscreen mode Exit fullscreen mode

Expected output:

Success! The configuration is valid.

Enter fullscreen mode Exit fullscreen mode

Plan

Next, I ran:

terraform plan

Enter fullscreen mode Exit fullscreen mode

The expected plan was:

Plan: 5 to add, 0 to change, 0 to destroy.

Enter fullscreen mode Exit fullscreen mode

Terraform planned to create:

module.network.google_compute_network.vpc_network
module.network.google_compute_subnetwork.subnets["app"]
module.network.google_compute_subnetwork.subnets["db"]
module.network.google_compute_firewall.ingress_rules["allow-iap-ssh"]
module.network.google_compute_firewall.ingress_rules["allow-internal"]

Enter fullscreen mode Exit fullscreen mode

This is an important difference.

Previously, resource addresses looked like this:

google_compute_network.vpc_network

Enter fullscreen mode Exit fullscreen mode

Now, because the resource is created inside a module, the address starts with:

module.network

Enter fullscreen mode Exit fullscreen mode

For example:

module.network.google_compute_network.vpc_network

Enter fullscreen mode Exit fullscreen mode

This means the resource is managed inside the network module.

Apply

After reviewing the plan, I applied the configuration:

terraform apply

Enter fullscreen mode Exit fullscreen mode

Then I typed:

yes

Enter fullscreen mode Exit fullscreen mode

Terraform created the resources successfully.

Terraform Output

After the apply completed, I checked the outputs:

terraform output

Enter fullscreen mode Exit fullscreen mode

The result was:

firewall_rules = {
  "allow-iap-ssh" = {
    "id" = "projects/terraform-gcp-learning-lab/global/firewalls/dev-allow-iap-ssh"
    "name" = "dev-allow-iap-ssh"
    "source_ranges" = toset([
      "35.235.240.0/20",
    ])
    "target_tags" = toset([
      "iap-ssh",
    ])
  }
  "allow-internal" = {
    "id" = "projects/terraform-gcp-learning-lab/global/firewalls/dev-allow-internal"
    "name" = "dev-allow-internal"
    "source_ranges" = toset([
      "10.40.0.0/16",
    ])
    "target_tags" = toset(null) /* of string */
  }
}
lab_summary = {
  "environment" = "dev"
  "firewall_count" = 2
  "network_name" = "dev-network-module"
  "project" = "terraform-gcp-learning-lab"
  "region" = "asia-southeast2"
  "subnet_count" = 2
}
network_id = "projects/terraform-gcp-learning-lab/global/networks/dev-network-module"
network_name = "dev-network-module"
subnets = {
  "app" = {
    "cidr_range" = "10.40.1.0/24"
    "id" = "projects/terraform-gcp-learning-lab/regions/asia-southeast2/subnetworks/dev-app-subnet"
    "name" = "dev-app-subnet"
    "region" = "asia-southeast2"
    "self_link" = "https://www.googleapis.com/compute/v1/projects/terraform-gcp-learning-lab/regions/asia-southeast2/subnetworks/dev-app-subnet"
  }
  "db" = {
    "cidr_range" = "10.40.2.0/24"
    "id" = "projects/terraform-gcp-learning-lab/regions/asia-southeast2/subnetworks/dev-db-subnet"
    "name" = "dev-db-subnet"
    "region" = "asia-southeast2"
    "self_link" = "https://www.googleapis.com/compute/v1/projects/terraform-gcp-learning-lab/regions/asia-southeast2/subnetworks/dev-db-subnet"
  }
}

Enter fullscreen mode Exit fullscreen mode

The output confirms that Terraform created:

  • one VPC network
  • two subnets
  • two firewall rules

The lab_summary output is especially useful because it gives a quick summary:

firewall_count = 2
subnet_count   = 2
network_name   = "dev-network-module"

Enter fullscreen mode Exit fullscreen mode

Verify the VPC in Google Cloud

I also verified the VPC using the Google Cloud CLI.

gcloud compute networks list --filter="name=dev-network-module"

Enter fullscreen mode Exit fullscreen mode

Output:

NAME                SUBNET_MODE  BGP_ROUTING_MODE  IPV4_RANGE  GATEWAY_IPV4  INTERNAL_IPV6_RANGE
dev-network-module  CUSTOM       REGIONAL

Enter fullscreen mode Exit fullscreen mode

This confirms that the VPC network was created in custom subnet mode.

Verify the Subnets

Then I checked the subnets:

gcloud compute networks subnets list \
  --filter="network:dev-network-module"

Enter fullscreen mode Exit fullscreen mode

Output:

NAME            REGION           NETWORK             RANGE         STACK_TYPE  IPV6_ACCESS_TYPE  INTERNAL_IPV6_PREFIX  EXTERNAL_IPV6_PREFIX  UTILIZATION_DETAILS
dev-app-subnet  asia-southeast2  dev-network-module  10.40.1.0/24  IPV4_ONLY
dev-db-subnet   asia-southeast2  dev-network-module  10.40.2.0/24  IPV4_ONLY

Enter fullscreen mode Exit fullscreen mode

This confirms that both subnets were created:

Subnet CIDR Range
dev-app-subnet 10.40.1.0/24
dev-db-subnet 10.40.2.0/24

Verify Remote State

Because this lab uses the GCS backend, I verified the remote state file:

gcloud storage ls gs://terraform-gcp-learning-lab-terraform-state/terraform-gcp-learning-lab/05-gcp-network-module/

Enter fullscreen mode Exit fullscreen mode

Output:

gs://terraform-gcp-learning-lab-terraform-state/terraform-gcp-learning-lab/05-gcp-network-module/default.tfstate

Enter fullscreen mode Exit fullscreen mode

This confirms that the Terraform state is stored in Google Cloud Storage.

Destroy

Because this is still a learning lab, I destroyed the resources after testing:

terraform destroy

Enter fullscreen mode Exit fullscreen mode

Then I typed:

yes

Enter fullscreen mode Exit fullscreen mode

Terraform destroyed the resources managed by this lab.

The GCS state bucket was not destroyed because it was created outside this Terraform configuration.

What I Learned

This lab helped me understand Terraform modules much better.

Previously, I created infrastructure directly in the root configuration.

Now, I separated the configuration into two layers:

Root module = decides what to deploy
Child module = defines how to deploy it

Enter fullscreen mode Exit fullscreen mode

The root module calls the child module:

module "network" {
  source = "./modules/gcp-network"
}

Enter fullscreen mode Exit fullscreen mode

The child module creates the actual resources:

  • VPC
  • subnets
  • firewall rules