GCP Firewall Rules: VPC Firewalls, Hierarchical Firewalls, and Tags
A production-focused guide to GCP Firewall Rules: VPC Firewalls, Hierarchical Firewalls, and Tags on Google Cloud Platform..
20+ years shipping production infrastructure and CI/CD at scale. Lessons pulled from things that broke in production.
- ✓Google Cloud Platform account, gcloud CLI installed and configured, basic understanding of VPC networking, familiarity with IAM and service accounts, Terraform (optional but recommended)
GCP Firewall Rules: VPC Firewalls, Hierarchical Firewalls, and Tags is like having a specialized tool that handles firewall rules so you don't have to build and manage it yourself โ it just works out of the box with Google Cloud's infrastructure.
A single misconfigured firewall rule cost a fintech startup $2M in a breach last year. GCP's firewall model is powerful but unforgiving: one wrong tag or priority can expose your entire database to the internet. Most teams treat firewall rules as an afterthought, slapping on default-allow rules and hoping for the best. That's a production incident waiting to happen. GCP offers three distinct firewall mechanismsโVPC Firewalls, Hierarchical Firewalls, and Tagsโeach with specific use cases and pitfalls. Understanding when to use which is the difference between a secure, scalable network and a compliance nightmare. This guide cuts through the docs to give you the real-world patterns that keep your infrastructure safe.
VPC Firewall Rules: The Foundation
VPC Firewall Rules are the bread and butter of GCP network security. They operate at the VPC network level and are evaluated in priority order (lowest number first). Each rule has a direction (ingress/egress), action (allow/deny), source/destination, protocol, and target. The key insight: rules are statefulโif you allow inbound traffic, the response is automatically allowed. This is a double-edged sword: it simplifies configuration but can mask misconfigurations. For example, allowing SSH from 0.0.0.0/0 on port 22 means any instance with a tag matching that rule is exposed. Always use the principle of least privilege: specify the smallest possible source range and target tags. A common production mistake is using '0.0.0.0/0' for 'temporary debugging' that becomes permanent. Audit your rules regularly with tools like Forseti or gcloud compute firewall-rules list.
Hierarchical Firewalls: Organization-Wide Policies
Hierarchical Firewall Policies let you enforce rules at the organization, folder, or project level, overriding VPC-level rules. They are evaluated before VPC firewall rules, with lower policy priority numbers taking precedence. Use them for mandatory security baselines: block all SSH from the internet, enforce egress to only approved IPs, or require encryption in transit. The gotcha: hierarchical rules are not statefulโyou must explicitly allow return traffic. This catches many teams off guard. For example, if you block all egress at the org level, your instances can't reach DNS or update packages. Always pair hierarchical rules with VPC rules for fine-grained control. A production pattern: use hierarchical rules to enforce 'deny all' by default, then use VPC rules to selectively allow specific traffic.
Network Tags: Dynamic Instance Grouping
Network tags are simple string labels on VM instances that firewall rules use as targets. They are the most flexible way to apply rules to dynamic groupsโe.g., all 'web-server' instances get HTTP access, all 'db' instances get MySQL from the web tier. Tags are not security boundaries; they are just labels. A common anti-pattern is using tags as a substitute for proper network segmentation. Tags are evaluated at instance creation and can be changed without restarting, but changes take effect immediately. Production tip: use tags in combination with service accounts for defense in depth. Never rely solely on tags for securityโthey can be misapplied or forgotten. Automate tag assignment with instance templates or Deployment Manager.
Priority and Evaluation Order: The Hidden Pitfall
Firewall rules are evaluated in priority order (lowest number first) until a match is found. If no rule matches, traffic is denied by default (implicit deny). The catch: rules with the same priority are evaluated in an arbitrary order. This can lead to unpredictable behavior if you have overlapping rules. Always use unique priorities and leave gaps (e.g., 100, 200, 300) for future rules. A common mistake: setting a deny rule with priority 1000 and an allow rule with priority 65535โthe deny never gets evaluated because the allow matches first. Use a 'deny all' rule with priority 65535 as a safety net. Hierarchical rules are evaluated before VPC rules, so a hierarchical deny will block traffic even if a VPC rule allows it.
Ingress vs Egress: Common Misconfigurations
Ingress rules control incoming traffic, egress rules control outgoing. Most teams focus on ingress and forget egress, leading to data exfiltration risks. Egress rules are equally important: restrict outbound traffic to only necessary destinations (e.g., specific API endpoints, DNS, NTP). A common misconfiguration: allowing all egress to 0.0.0.0/0 for 'convenience'. This means any compromised instance can phone home. Use egress deny rules with high priority and allow only specific IP ranges. For Google APIs, use the restricted.googleapis.com VIP (199.36.153.4/30) or private Google access. Remember: hierarchical egress rules are stateless, so you must allow return traffic explicitly.
Service Accounts and Firewall Rules: Defense in Depth
Service accounts authenticate your VMs to Google APIs, but they don't affect firewall rules directly. However, combining service accounts with firewall rules adds a layer of identity-based access. For example, you can use IAM conditions to restrict which service accounts can create firewall rules. Also, use firewall rules logging to monitor traffic from specific service accounts. A production pattern: create a custom service account for each application tier and use firewall rules that allow traffic only between those service accounts (via source tags). This prevents a compromised web server from talking to the database directly if it doesn't have the right tag.
Firewall Rules Logging: Visibility into Traffic
Firewall rules logging lets you capture metadata about connections that match a rule. Enable it on critical rules (e.g., deny rules, allow rules to sensitive resources). Logs are sent to Cloud Logging and can be used for audit, troubleshooting, and threat detection. The cost: logging incurs additional charges and can generate high volume. Enable sampling or filter to only log denies. A production insight: log all deny rules to detect scanning or misconfigurations. Use log-based metrics to alert on spikes in denied traffic. Also, log allow rules for sensitive ports (e.g., SSH, RDP) to track access.
Testing Firewall Rules Safely
Never test firewall rules directly in production. Use a separate test VPC or project. GCP provides the 'gcloud compute firewall-rules test' command to simulate traffic. This is invaluable for verifying rules before deployment. Also, use connectivity tests in VPC Network Peering to validate end-to-end paths. A production workflow: write rules in a staging environment, run automated tests (e.g., using nmap or custom scripts), then promote to production via Infrastructure as Code (e.g., Terraform). Always have a rollback plan: keep previous rule versions in source control.
Infrastructure as Code for Firewall Rules
Managing firewall rules manually is error-prone. Use Terraform, Deployment Manager, or Config Connector to define rules as code. This enables version control, code review, and automated testing. A Terraform example: define a module for common rules (e.g., allow SSH from bastion, allow HTTP from load balancers). Use variables for source ranges and tags to avoid hardcoding. Production tip: use a CI/CD pipeline that runs 'terraform plan' and validates rules against a policy (e.g., no 0.0.0.0/0 for SSH). Also, use Terraform's 'precondition' to enforce naming conventions.
Common Pitfalls and How to Avoid Them
- Overly permissive source ranges: Using 0.0.0.0/0 for any rule is a red flag. Always restrict to specific IP ranges or use tags. 2. Missing egress rules: Default egress allow is dangerous. Implement default-deny egress. 3. Tag sprawl: Too many tags become unmanageable. Use a naming convention and automate tag assignment. 4. Ignoring priority: Overlapping priorities cause unpredictable behavior. Use unique priorities. 5. Not logging: Without logs, you're blind to attacks. Enable logging on deny rules. 6. Manual changes: Always use IaC to prevent drift. 7. Not testing: Test in a separate environment. 8. Forgetting hierarchical rules: They override VPC rules and can break connectivity.
Real-World Production Patterns
Pattern 1: Bastion host with strict ingress. Allow SSH only from a bastion host's IP range, and use IAP TCP forwarding as an alternative. Pattern 2: Micro-segmentation with tags. Each application tier has a unique tag, and firewall rules allow only necessary inter-tier traffic. Pattern 3: Egress allow-list for dependencies. Allow outbound to specific Google APIs, DNS (8.8.8.8), and NTP (pool.ntp.org). Pattern 4: Hierarchical deny for compliance. Block all SSH from the internet at the org level, then allow only from bastion at the project level. Pattern 5: Logging and alerting. Enable logging on deny rules and create log-based metrics for brute-force detection.
Monitoring and Auditing Firewall Rules
Regularly audit your firewall rules for unused, overly permissive, or misconfigured rules. Use tools like Forseti Security or gcloud commands to generate reports. Set up automated compliance checks: e.g., ensure no rule has source range 0.0.0.0/0 for SSH. Use Cloud Asset Inventory to track firewall rule changes. Production insight: schedule a weekly cron job that exports firewall rules to Cloud Storage and compares with the previous version. Alert on any new rule with priority < 1000 (high priority). Also, use VPC Flow Logs to verify that firewall rules are actually being usedโif a rule never matches, consider removing it.
Secure Tags: IAM-Governed Tagging for Firewall Policies
Cloud NGFW introduces secure tagsโIAM-governed tags created and managed in Resource Manager as tag keys and tag values. Unlike network tags (simple strings with no access control), secure tags have full IAM support. You can set purpose=GCE_FIREWALL on a tag key and restrict it to a specific VPC network or an entire organization. Secure tags can be used as sources for ingress rules and targets for ingress/egress rules in hierarchical, global, and regional network firewall policies. Critically, VPC firewall rules do NOT support secure tagsโonly policy-based firewalls do. Each VM network interface supports up to 10 secure tag values. Use secure tags to implement micro-segmentation where developers can bind tags to their VMs but cannot modify the firewall rules themselves, enforcing a clear separation of duties.
Migrating VPC Firewall Rules to Global Network Firewall Policies
VPC firewall rules have limitations: no batch editing, no IAM-governed tags, no advanced features like FQDN objects or threat detection. Cloud NGFW's global network firewall policies solve these. GCP provides a migration tool (gcloud CLI) that converts VPC firewall rules into global network firewall policy rules. For rules with network tags, the tool can create equivalent IAM-governed secure tags. For rules without tags or service accounts, migration is straightforward. After migration, you associate the new policy with your VPC network and disable the old VPC rules. The migration tool preserves priority order but may reorder deny/allow rules for consistency. Plan the migration incrementally: start with a non-production network, validate, then roll out to production.
| File | Command / Code | Purpose |
|---|---|---|
| create-firewall-rule.sh | gcloud compute firewall-rules create allow-internal-ssh \ | VPC Firewall Rules |
| create-hierarchical-policy.sh | gcloud compute firewall-policies create org-policy \ | Hierarchical Firewalls |
| add-tag-to-instance.sh | gcloud compute instances add-tags web-server-1 \ | Network Tags |
| list-rules-priority.sh | gcloud compute firewall-rules list --sort-by=priority | Priority and Evaluation Order |
| create-egress-allow.sh | gcloud compute firewall-rules create allow-egress-google-apis \ | Ingress vs Egress |
| create-service-account-firewall.sh | gcloud compute firewall-rules create allow-web-to-db \ | Service Accounts and Firewall Rules |
| enable-firewall-logging.sh | gcloud compute firewall-rules update allow-internal-ssh \ | Firewall Rules Logging |
| test-firewall-rule.sh | gcloud compute firewall-rules test-iam-policy \ | Testing Firewall Rules Safely |
| firewall.tf | resource "google_compute_firewall" "allow-ssh-from-bastion" { | Infrastructure as Code for Firewall Rules |
| audit-firewall.sh | gcloud compute firewall-rules list --format="table(name,network,direction,priori... | Common Pitfalls and How to Avoid Them |
| iap-tunneling.sh | gcloud compute ssh my-instance --tunnel-through-iap --zone=us-central1-a | Real-World Production Patterns |
| audit-unused-rules.sh | gcloud compute firewall-rules list --filter="disabled=false" --format="table(nam... | Monitoring and Auditing Firewall Rules |
| create-secure-tag.sh | gcloud alpha resource-manager tags keys create firewall-tier \ | Secure Tags |
| migrate-vpc-rules.sh | gcloud compute firewall-policies migrate-rules \ | Migrating VPC Firewall Rules to Global Network Firewall Poli |
Key takeaways
Common mistakes to avoid
3 patternsIgnoring gcp firewall rules best practices
Over-provisioning without rightsizing analysis
Skipping IAM least-privilege principles
Interview Questions on This Topic
What is GCP Firewall Rules: VPC Firewalls, Hierarchical Firewalls, and Tags and when would you use it in production?
Frequently Asked Questions
20+ years shipping production infrastructure and CI/CD at scale. Lessons pulled from things that broke in production.
That's Google Cloud. Mark it forged?
6 min read · try the examples if you haven't