Skip to main content

Configuring Firewall Rules with Network Tags

Learn how GCP firewall rules target VMs by network tag or service account instead of subnet, and test both so no VM is left unprotected.

38 Terms

Overview and What You Will Learn

A GCP firewall rule is defined on a VPC network and applies only to the VMs it targets, chosen by network tag, by service account, or by selecting every VM. It is not attached to a subnet. In this lab, you will create a rule that targets a tag, prove it reaches only the tagged VM, and then repeat the test with a rule that targets a service account.

Why This Matters in Production

An engineer coming from AWS or Azure writes a rule expecting it to cover every VM in a subnet, like a security group or NSG. A new VM without the matching tag is simply never selected by the rule, and nothing reports an error. Think of a Stripe-style payments team launching a new API node that quietly misses its allow rule, or worse, a node that is missing the tag that applies a deny rule.

Core Principles

GCP firewall rules live at the VPC level, and each rule has a target that decides which VMs it applies to. With no target, a rule applies to every VM in the network. With --target-tags, it applies only to VMs carrying that tag. With --target-service-accounts, it applies only to VMs running as that service account. A single rule cannot mix tags and service accounts as targets.

flowchart TD R{{Firewall rule
target-tags: web-server}} -->|tag matches| V1[vm-tagged
tag: web-server] R -.->|no match| V2[vm-untagged
no tag] V1 --> OK([Traffic allowed]) V2 --> NO([Blocked by
implied deny]) classDef rule fill:#326CE5,color:#FFFFFF classDef vm fill:#DBEAFE,color:#1E293B classDef good fill:#10B981,color:#FFFFFF classDef bad fill:#EF4444,color:#FFFFFF class R rule class V1,V2 vm class OK good class NO bad

Every VPC network also has two implied rules that you cannot delete: deny all ingress and allow all egress, both at priority 65535. A VM that no allow rule selects therefore falls through to the implied ingress deny. Rules are evaluated by priority, where a lower number wins, and new rules default to priority 1000.

Detailed Step-by-Step Practical Lab

Set the variables used throughout the lab. Project IDs are globally unique, so change the suffix if the create command fails.

Bash
export PROJECT_ID=gcp-firewall-lab-mumbai-2026
export ZONE=asia-south1-a
  1. Create the project, link billing, enable the APIs, and build a VPC with one subnet:
Bash
gcloud projects create $PROJECT_ID --name="Firewall Tags Lab"
gcloud config set project $PROJECT_ID
gcloud billing projects link $PROJECT_ID \
--billing-account=012345-6789AB-CDEF01
gcloud services enable compute.googleapis.com iam.googleapis.com
gcloud compute networks create vpc-lab --subnet-mode=custom
gcloud compute networks subnets create subnet-lab \
--network=vpc-lab \
--region=asia-south1 \
--range=10.0.1.0/24
  1. Allow SSH through Identity-Aware Proxy to every VM in the network. This rule has no target, so it applies to all VMs. The VMs in this lab have no external IP, so IAP is how you reach them:
Bash
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
  1. Create a rule that allows port 8080 from inside the subnet, but only to VMs tagged web-server. Port 8080 stands in for a web port so the lab can run without certificates:
Bash
gcloud compute firewall-rules create allow-web-by-tag \
--network=vpc-lab \
--direction=INGRESS \
--action=ALLOW \
--rules=tcp:8080 \
--source-ranges=10.0.1.0/24 \
--target-tags=web-server
  1. Create three VMs: one with the tag, one without it, and a client to run the tests from:
Bash
gcloud compute instances create vm-tagged \
--zone=$ZONE --machine-type=e2-small \
--image-family=debian-12 --image-project=debian-cloud \
--network=vpc-lab --subnet=subnet-lab \
--no-address --tags=web-server
gcloud compute instances create vm-untagged \
--zone=$ZONE --machine-type=e2-small \
--image-family=debian-12 --image-project=debian-cloud \
--network=vpc-lab --subnet=subnet-lab \
--no-address
gcloud compute instances create vm-client \
--zone=$ZONE --machine-type=e2-small \
--image-family=debian-12 --image-project=debian-cloud \
--network=vpc-lab --subnet=subnet-lab \
--no-address
  1. Confirm which tags each VM actually carries:
Bash
gcloud compute instances describe vm-tagged \
--zone=$ZONE --format="value(tags.items)"
gcloud compute instances describe vm-untagged \
--zone=$ZONE --format="value(tags.items)"
  1. Start a simple web server on port 8080 on both target VMs, using a systemd transient unit so it keeps running after the SSH session ends:
Bash
for VM in vm-tagged vm-untagged; do
gcloud compute ssh $VM --zone=$ZONE --tunnel-through-iap \
--command="sudo systemd-run --unit=demo-web python3 -m http.server 8080"
done
  1. Test from the client. The tagged VM should return 200. The untagged VM should print 000 after the timeout, because the allow rule never selected it:
Bash
export TAGGED_IP=$(gcloud compute instances describe vm-tagged \
--zone=$ZONE --format="value(networkInterfaces[0].networkIP)")
export UNTAGGED_IP=$(gcloud compute instances describe vm-untagged \
--zone=$ZONE --format="value(networkInterfaces[0].networkIP)")
gcloud compute ssh vm-client --zone=$ZONE --tunnel-through-iap \
--command="curl -s -m 5 -o /dev/null -w '%{http_code}' http://$TAGGED_IP:8080; echo; curl -s -m 5 -o /dev/null -w '%{http_code}' http://$UNTAGGED_IP:8080; echo"
  1. Now target a service account instead. Create the account, a rule that targets it, and a VM that runs as it:
Bash
gcloud iam service-accounts create web-server-sa
gcloud compute firewall-rules create allow-web-by-sa \
--network=vpc-lab \
--direction=INGRESS \
--action=ALLOW \
--rules=tcp:8080 \
--source-ranges=10.0.1.0/24 \
--target-service-accounts=web-server-sa@$PROJECT_ID.iam.gserviceaccount.com
gcloud compute instances create vm-sa \
--zone=$ZONE --machine-type=e2-small \
--image-family=debian-12 --image-project=debian-cloud \
--network=vpc-lab --subnet=subnet-lab \
--no-address \
--service-account=web-server-sa@$PROJECT_ID.iam.gserviceaccount.com
  1. Start the web server on vm-sa and test it from the client. It has no tag, so only the service account rule can be letting it through:
Bash
gcloud compute ssh vm-sa --zone=$ZONE --tunnel-through-iap \
--command="sudo systemd-run --unit=demo-web python3 -m http.server 8080"
export SA_IP=$(gcloud compute instances describe vm-sa \
--zone=$ZONE --format="value(networkInterfaces[0].networkIP)")
gcloud compute ssh vm-client --zone=$ZONE --tunnel-through-iap \
--command="curl -s -m 5 -o /dev/null -w '%{http_code}' http://$SA_IP:8080; echo"
  1. Clean up:
Bash
gcloud compute instances delete vm-tagged vm-untagged vm-client vm-sa \
--zone=$ZONE --quiet
gcloud compute firewall-rules delete allow-iap-ssh allow-web-by-tag allow-web-by-sa --quiet
gcloud compute networks subnets delete subnet-lab --region=asia-south1 --quiet
gcloud compute networks delete vpc-lab --quiet
gcloud projects delete $PROJECT_ID --quiet

Production Best Practices & Common Pitfalls

Common Mistake

Assuming a rule with --target-tags or --target-service-accounts covers every VM in the subnet. Any VM without that exact tag or identity is silently unaffected, so a new VM can launch with no allow rule, or with no deny rule you meant it to have.

Security

Anyone with permission to edit an instance's tags can change which firewall rules apply to it. Tags are free-form strings with no IAM check on their meaning. For security-critical rules, target service accounts, or use secure tags with network firewall policies.

Tip

Prefer service account targeting for production tiers. A service account is a real IAM identity attached at VM creation, it appears in audits, and it cannot be mistyped the way a tag can.

  • Priority decides conflicts. A lower number wins, so a specific deny at priority 500 overrides a broader allow at priority 1000.
  • Egress works the same way. An egress rule's targets are the VMs sending the traffic, selected by their own tag or service account.
  • Avoid rules with no target. A rule with no target tags or service accounts applies to every VM in the network, including ones created later.
  • Name tags like an interface. Agree on a short list such as web-server and db-server, and document it, since nothing validates tag spelling.

Quick Reference & Troubleshooting Commands

Command Description
gcloud compute firewall-rules create --target-tags=TAG Create a rule scoped to tagged VMs
gcloud compute firewall-rules create --target-service-accounts=EMAIL Create a rule scoped to a service account
gcloud compute instances create --tags=TAG Assign network tags at creation
gcloud compute instances add-tags VM --tags=TAG Add a tag to an existing VM
gcloud compute instances describe VM --format="value(tags.items)" Check a VM's current tags
gcloud compute firewall-rules list --filter="network:vpc-lab" List all rules on a network with priorities

Resources

Artifact Registry

Google Cloud's current, unified package and container image storage service, the successor to the older Container Registry. It supports container images alongside language packages like npm, Maven, and Python packages in one service, and supports cleanup policies to automatically remove old, untagged image versions.

BigQuery

Google Cloud's serverless data warehouse for analytics, priced based on the volume of data a query actually scans rather than pre-provisioned compute capacity. Selecting only needed columns and querying a properly partitioned table's relevant date range are the two highest-impact levers for controlling BigQuery cost.

Bigtable (GCP)

A wide-column NoSQL database built for very high throughput at extremely low latency, suited to time-series data, IoT telemetry, and analytics workloads with massive write volume. It is a specialized tool distinct from Firestore's document model or Cloud SQL's relational model.

Billing Account (GCP)

A separate object from a Project that holds the actual payment method for Google Cloud usage. One Billing Account can be linked to many Projects, all of whose usage is billed to that same account, letting a company centralize payment while individual Projects retain their own separate IAM control over resources.

Cloud Armor

A security policy service attached to a Global External HTTP(S) Load Balancer, filtering malicious requests before they reach the backend. It supports rate-based rules blocking a single source IP exceeding a request threshold, and preconfigured WAF rules blocking common attack patterns like SQL injection, Google's equivalent of AWS WAF or Azure WAF.

Cloud Functions (GCP)

Google Cloud's event-driven, single-purpose compute service, the most granular and shortest-lived compute unit in GCP's compute spectrum. It fits a narrow niche compared to Cloud Run - a specific triggered action like resizing an uploaded image, rather than a full application with multiple routes and business logic.

Cloud Load Balancing

Google Cloud's family of load balancing products, spanning Global External HTTP(S) Load Balancers (public, distributed globally via a single IP), Regional External Load Balancers, and Internal Load Balancers reachable only from within the VPC. The right type depends on traffic type and whether the backend should ever be reachable from the public internet.

Cloud Logging

Google Cloud's service for collecting, storing, and querying log data from every GCP service and custom applications. Its query filter syntax lets logs be narrowed by resource, severity, and specific field values, and Log Sinks can route matching logs to BigQuery, Cloud Storage, or Pub/Sub for long-term retention beyond the default window.

Cloud Monitoring

Google Cloud's metrics, dashboards, and alerting service. An alert policy requires a Notification Channel explicitly attached to actually notify someone when it fires - without one, the policy still evaluates and logs its own firing history, but nobody is ever told, a common and easy-to-miss misconfiguration.

Cloud NAT

A service providing outbound-only internet connectivity for resources with no external IP address, GCP's equivalent of an AWS or Azure NAT Gateway. Cloud NAT requires a Cloud Router in the same region and provides zero inbound connectivity capability - a resource behind it remains completely unreachable from the internet.

Cloud Run

A fully managed, serverless platform for running containerized applications, scaling automatically to zero when idle and billing only for actual invocations. It combines the flexibility of running any container with zero OS management overhead, making it the right default for a standard stateless containerized web service.

Cloud SQL

Google Cloud's managed relational database service, supporting MySQL, PostgreSQL, and SQL Server. It is the right default for a traditional relational workload with moderate scale needs, handling patching, backups, and replication automatically without requiring OS-level access to the underlying database server.

Cloud Spanner

A globally distributed, strongly consistent relational database offering both SQL semantics and horizontal scalability beyond what a single Cloud SQL instance can provide. It is the right choice specifically when a workload needs both relational query capability and massive scale simultaneously, not simply because a workload feels large or important.

Cloud Storage Bucket

The top-level container for objects in Google Cloud Storage, GCP's object storage service equivalent to AWS S3 or Azure Blob Storage. Every object uploaded to Cloud Storage must belong to exactly one bucket, and bucket-level settings control default storage class, location, and access permissions for everything inside it.

Cloud VPN (GCP)

A service connecting an on-premises network to a GCP VPC over an encrypted tunnel, similar to VPN Gateway in Azure or a Site-to-Site VPN in AWS. It requires a Cloud Router as its foundation and is distinct from VPC Network Peering, which connects two GCP VPCs directly rather than an external network.

Compute Engine

Google Cloud's Infrastructure-as-a-Service offering, providing full virtual machines with complete OS-level control. It is the right choice specifically when a workload needs custom software, specific OS configurations, or hardware-level access that GKE and Cloud Run don't expose.

Error Reporting (GCP)

A Google Cloud operations service that automatically aggregates and groups application errors from logs and instrumented code, surfacing recurring error patterns and their frequency without requiring manual log searching for each individual occurrence.

Firestore

A serverless NoSQL document database built for mobile and web application data, flexible schemas, and real-time client synchronization. It is not a strong fit for workloads needing complex relational joins or multi-row transactions across unrelated entities, which point instead to Cloud SQL or Spanner.

GCP Audit Log

A specific category of Cloud Logging entry recording administrative actions and data access. Admin Activity logs (configuration changes) are always enabled and cannot be disabled; Data Access logs (who read or wrote actual data) are disabled by default for most services and must be explicitly enabled before that history exists.

GCP Firewall Rule

A rule defined at the VPC level controlling inbound or outbound traffic, applied using network tags or Service Accounts on instances rather than being tied to a specific subnet boundary. A firewall rule only affects VMs carrying the exact matching tag or identity - a VM without it is entirely unaffected, silently, with no error to flag the mismatch.

GCP Folder

An optional grouping node in the GCP resource hierarchy, sitting between the Organization and individual Projects. Folders are commonly used to group Projects by team, department, or environment, letting IAM permissions and Organization Policies be applied once at the Folder level rather than repeated across every Project inside it.

GCP IAM Role Types

Google Cloud IAM roles come in three types: Basic roles (Owner, Editor, Viewer) which are broad and legacy; Predefined roles curated by Google and scoped to a specific service's specific needs; and Custom roles built from individual permissions for access needs a predefined role doesn't precisely match.

GCP Organization

The top-level node in Google Cloud's resource hierarchy, tied to a Google Workspace or Cloud Identity domain. An Organization contains Folders and Projects, and policies or IAM permissions set at this level automatically apply to everything beneath it across the entire company.

GCP Project

The fundamental unit of organization in Google Cloud - every resource belongs to exactly one Project, which serves as the boundary for billing, IAM permissions, and API enablement. A Project has a permanent, globally unique Project ID chosen at creation and never changeable, distinct from its display name which can be updated freely.

GCP Quota

A default limit on how much of a specific resource (like VM CPUs or API calls) can be used per Project per region, designed to prevent runaway costs and protect shared infrastructure. Quotas can be checked and increased through the Console ahead of a known future need, such as a planned launch event.

GCP Storage Class

A pricing and access tier for Cloud Storage objects - Standard, Nearline, Coldline, or Archive - trading lower storage cost against higher retrieval cost and a longer minimum storage duration. Deleting or overwriting an object before its class's minimum duration elapses still bills as if it were stored the full minimum period.

GKE Autopilot

A mode of Google Kubernetes Engine where Google manages node provisioning, sizing, and patching entirely - you define workloads, and nodes appear automatically to run them, billed per pod resource request rather than per node. It is the lower-effort default for most containerized workloads, versus Standard mode's direct node pool control.

Managed Instance Group

A group of identical Compute Engine VMs created from an Instance Template and managed as a single unit, GCP's equivalent of an AWS Auto Scaling Group or Azure VM Scale Set. A Managed Instance Group can autoscale based on a metric like CPU utilization, adding or removing instances automatically within configured minimum and maximum bounds.

Network Tag (GCP)

A freeform string label attached to a Compute Engine VM at creation time, used to target firewall rules to specific VMs. Network tags are simple but can be forgotten or misspelled at scale, which is why Service Account-based targeting is often preferred for anything security-critical in a growing fleet.

OS Login

A Compute Engine feature that ties SSH access to a user's actual Google Identity and IAM permissions, rather than manually managing individual SSH public keys per VM. Enabling OS Login means revoking a departing employee's GCP access also immediately revokes their SSH access to every VM, with no separate key cleanup needed.

Organization Policy (GCP)

A constraint applied at the Organization, Folder, or Project level that restricts what resources are allowed to look like across everything beneath that level - for example, blocking external IP addresses on VMs or restricting allowed regions. Unlike IAM, which controls who can act, Organization Policy controls what configurations are permitted.

Persistent Disk (GCP)

The block storage attached to a Compute Engine VM, equivalent to an AWS EBS volume or Azure Managed Disk. Persistent Disks come in zonal (replicated within one zone, lower cost) and regional (synchronously replicated across two zones, survives a single zone failure) variants.

Security Command Center

Google Cloud's security posture management service, continuously scanning deployed resources against security best practices and surfacing specific, severity-ranked findings - like a publicly accessible storage bucket - rather than a single opaque score. Findings should be prioritized by actual severity, not treated as a count to minimize.

Service Account (GCP)

An identity used by applications, VMs, and automated processes to authenticate to Google Cloud APIs, rather than by a human user. A Service Account is itself also a resource with its own IAM permissions, and can be attached directly to a VM or impersonated temporarily, both safer alternatives to downloading its long-lived JSON key file.

Shared VPC

A configuration where one Project (the host) owns a VPC network, while other Projects (service projects) attach to it and deploy resources using its subnets. This centralizes network administration in the host Project while letting individual teams in service Projects still manage their own resources independently.

Spot VM (GCP)

A Compute Engine VM using Google's spare, unused capacity at a steep discount, with the trade-off that Google can reclaim the instance with short notice. Spot VMs are appropriate only for fault-tolerant, interruption-tolerant workloads like batch processing, never for customer-facing services needing reliable availability.

VPC (GCP)

A Virtual Private Cloud in Google Cloud is a global resource by default, unlike the regional VPC or VNet model in AWS or Azure - a single GCP VPC can span every region, with individual subnets defined per-region inside it. The default auto-mode VPC pre-creates a subnet in every region, while a custom-mode VPC starts empty until subnets are deliberately defined.

VPC Network Peering

A direct connection between two separate VPCs, potentially in different Projects or Organizations, with traffic never touching the public internet. Peering must be established from both sides to become active, and is explicitly non-transitive - if VPC A peers with B, and B peers with C, A cannot reach C without its own direct peering connection to C.

Explore More in GCP Networking and Connectivity

All 6 Topics

Frequently Asked Questions

Is Configuring Firewall Rules with Network Tags free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Configuring Firewall Rules with Network Tags topic cover?

Learn how GCP firewall rules target VMs by network tag or service account instead of subnet, and test both so no VM is left unprotected.

Found a mistake, an outdated step or a broken link?