Skip to main content

Building Cloud Monitoring Alerts and Dashboards

Create a Cloud Monitoring notification channel, alert policy and dashboard, then test the path so alerts reach a person instead of failing silently.

38 Terms

Overview and What You Will Learn

A Cloud Monitoring alert policy watches a metric and opens an incident when a condition is met, but it only tells a person if a notification channel is attached. A policy with no channel still creates incidents in the console, so it looks healthy while nobody is paged. Dashboards are a separate tool: they visualize metrics for people who are already looking, while alerts reach people who are not.

In this lab you will:

  • Create an email notification channel
  • Create an alert policy from a YAML file that references that channel
  • Build a small dashboard for the same VM
  • Trigger the alert on purpose and confirm that a notification arrives
  • Audit a project for policies that have no channel attached

Why This Matters in Production

A common outage pattern is an alert that exists but notifies nobody. A team configures a disk space policy, never attaches a channel, and finds out days later when the disk is full, with a long history of incidents sitting unread in the console. On a payments platform at a company like Razorpay, a silent alert is worse than no alert, because everyone believes the risk is covered.

Core Principles

Monitoring has three connected parts, and a gap in any one of them breaks the chain. The policy decides when something is wrong, the incident records that it happened, and the channel decides who finds out.

flowchart LR M[Metric crosses
threshold] --> P[Alert policy
condition met] P --> I[Incident opened
always logged] I -->|channel attached| C[Notification channel] C --> H([Person is told]) I -->|no channel| S([Silent failure]) classDef step fill:#DBEAFE,color:#1E293B classDef good fill:#10B981,color:#FFFFFF classDef bad fill:#EF4444,color:#FFFFFF class M,P,I,C step class H good class S bad
Concept What it does
Alert policy Defines the condition and who to notify
Incident The record created when a condition is met
Notification channel Email, SMS, Slack, PagerDuty or webhook destination
Dashboard Charts for humans who are actively watching

Detailed Step-by-Step Practical Lab

Milestone 1: Create a Project and a VM to Monitor

Compute Engine needs billing on the project. Use a suffix so the project ID is unique.

Bash
export BILLING_ACCOUNT=0A1B2C-3D4E5F-6A7B8C
export PROJECT_ID=monitoring-lab-$(date +%s | tail -c 6)
gcloud projects create $PROJECT_ID --name="Monitoring Lab"
gcloud billing projects link $PROJECT_ID --billing-account=$BILLING_ACCOUNT
gcloud config set project $PROJECT_ID
gcloud services enable compute.googleapis.com monitoring.googleapis.com
gcloud compute instances create vm-monitor-test \
--zone=asia-south1-a \
--machine-type=e2-medium \
--image-family=debian-12 \
--image-project=debian-cloud
Milestone 2: Create the Notification Channel

The channel is the destination. Create it first so the policy can reference it.

Bash
gcloud monitoring channels create \
--display-name="Ops Team Email" \
--type=email \
--channel-labels=email_address=ops-team@devops.in
export CHANNEL=$(gcloud monitoring channels list \
--filter='displayName="Ops Team Email"' \
--format='value(name)')
echo $CHANNEL
# projects/monitoring-lab-12345/notificationChannels/1234567890123456789

If your gcloud version does not recognize gcloud monitoring, use gcloud beta monitoring or gcloud alpha monitoring with the same arguments. In the Cloud console you can also use Send test notification on the channel to confirm delivery before relying on it.

Milestone 3: Create the Alert Policy from a File

Writing the policy as a file is clearer and more repeatable than a long list of flags, and it can be stored in version control. CPU utilization is reported as a fraction between 0 and 1, so 0.85 means 85 percent.

YAML
# high-cpu-policy.yaml
displayName: High CPU on vm-monitor-test
combiner: OR
conditions:
- displayName: CPU above 85 percent for 5 minutes
conditionThreshold:
filter: 'resource.type = "gce_instance" AND metric.type = "compute.googleapis.com/instance/cpu/utilization"'
comparison: COMPARISON_GT
thresholdValue: 0.85
duration: 300s
aggregations:
- alignmentPeriod: 60s
perSeriesAligner: ALIGN_MEAN
notificationChannels:
- CHANNEL_NAME
documentation:
mimeType: text/markdown
content: |
CPU has stayed above 85 percent for 5 minutes on a production VM.
Check recent deploys, then the runbook at https://runbooks.devops.in/high-cpu
Bash
# Substitute the real channel name and create the policy
sed "s|CHANNEL_NAME|$CHANNEL|" high-cpu-policy.yaml > policy-rendered.yaml
gcloud monitoring policies create --policy-from-file=policy-rendered.yaml
# Verify the channel is attached
gcloud monitoring policies list \
--format="table(displayName, notificationChannels)"

The documentation block is included in the notification, so whoever receives it sees what to do next.

Milestone 4: Build a Dashboard

A dashboard gives people a place to look during and after an incident. Define it as a file as well.

YAML
# vm-dashboard.yaml
displayName: vm-monitor-test overview
mosaicLayout:
columns: 12
tiles:
- width: 6
height: 4
widget:
title: CPU utilization
xyChart:
dataSets:
- timeSeriesQuery:
timeSeriesFilter:
filter: 'metric.type="compute.googleapis.com/instance/cpu/utilization" resource.type="gce_instance"'
aggregation:
alignmentPeriod: 60s
perSeriesAligner: ALIGN_MEAN
- xPos: 6
width: 6
height: 4
widget:
title: Network received bytes
xyChart:
dataSets:
- timeSeriesQuery:
timeSeriesFilter:
filter: 'metric.type="compute.googleapis.com/instance/network/received_bytes_count" resource.type="gce_instance"'
aggregation:
alignmentPeriod: 60s
perSeriesAligner: ALIGN_RATE
Bash
gcloud monitoring dashboards create --config-from-file=vm-dashboard.yaml
gcloud monitoring dashboards list --format="table(displayName, name)"
Milestone 5: Trigger the Alert and Confirm the Notification

Test the entire path, not just the configuration. Generate CPU load, wait for the condition to hold for five minutes, and check your inbox and the Alerting page.

Bash
# Start one busy loop per vCPU (e2-medium has 2)
gcloud compute ssh vm-monitor-test --zone=asia-south1-a --tunnel-through-iap \
--command='for i in 1 2; do (yes > /dev/null &); done'
# Wait roughly 6 to 8 minutes, then open Monitoring > Alerting in the console.
# You should see an open incident and receive an email at ops-team@devops.in.
# Stop the load afterwards
gcloud compute ssh vm-monitor-test --zone=asia-south1-a --tunnel-through-iap \
--command='pkill yes'

The incident closes automatically after the metric returns to normal, and a resolved notification is sent.

Milestone 6: Reproduce and Detect the Silent Failure

Create a policy without any channel to see the failure mode, then learn to find it.

Bash
# Same policy file with the channel list removed
grep -v -e 'notificationChannels' -e 'CHANNEL_NAME' high-cpu-policy.yaml \
| sed 's/displayName: High CPU on vm-monitor-test/displayName: Silent test (no channel)/' \
> silent-policy.yaml
gcloud monitoring policies create --policy-from-file=silent-policy.yaml
# Find every policy that has no notification channel
gcloud monitoring policies list \
--filter='NOT notificationChannels:*' \
--format="table(displayName, enabled)"

This silent policy still evaluates and opens incidents under the same conditions. The only difference is that no one is told. Run the audit command regularly, or in CI against your project, so an unattended alert is caught before an incident exposes it.

Milestone 7: Clean Up
Bash
gcloud monitoring policies list --format="value(name)" | \
while read policy; do
gcloud monitoring policies delete "$policy" --quiet
done
gcloud monitoring dashboards list --format="value(name)" | \
while read dash; do
gcloud monitoring dashboards delete "$dash" --quiet
done
gcloud monitoring channels delete "$CHANNEL" --quiet
gcloud compute instances delete vm-monitor-test --zone=asia-south1-a --quiet
gcloud projects delete $PROJECT_ID --quiet

Production Best Practices & Common Pitfalls

  1. Always attach a channel, then test it. A configured alert is not a working alert until a real notification has arrived.
  2. Route by severity. Page the on-call engineer for customer-impacting outages, and send low-urgency warnings to a team inbox or chat room.
  3. Use sensible durations. A five minute window absorbs harmless CPU bursts and avoids repeated false alarms.
  4. Write documentation in the alert. Include the likely cause, the dashboard link and the runbook.
  5. Alert on missing data. For critical metrics, add an absence condition so a dead agent or stopped service also triggers.
  6. Define alerts as code. YAML files or Terraform keep policies reviewable and repeatable.
  7. Monitor what matters to users. Use uptime checks and error-rate or latency alerts, not only machine metrics.
Common Mistake

Creating a policy and assuming it is complete without checking its notification channels. The policy fires and logs correctly either way, and the only symptom of a missing channel is silence.

Tip

Disk and memory metrics are not collected by default on Compute Engine. Install the Ops Agent on the VM to get them, then alert on disk percent used before the disk fills.

Remember

Dashboards help people who are looking. Alert policies reach people who are not.

Quick Reference & Troubleshooting Commands

Command Description
gcloud monitoring channels create Create a notification channel
gcloud monitoring channels list List channels
gcloud monitoring policies create --policy-from-file=FILE Create a policy from YAML or JSON
gcloud monitoring policies list List policies
gcloud monitoring dashboards create --config-from-file=FILE Create a dashboard
Symptom Likely cause and fix
Incident exists but no email No channel attached, update the policy with a channel
Alert never fires Wrong metric filter, or threshold in the wrong unit (fraction vs percent)
Too many repeated alerts Duration too short, lengthen it or add aggregation
Disk or memory metrics missing Ops Agent not installed on the VM
gcloud monitoring not found Older gcloud, update it or use gcloud beta monitoring

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 Operations, Security, and Production Readiness

All 6 Topics

Frequently Asked Questions

Is Building Cloud Monitoring Alerts and Dashboards 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 Building Cloud Monitoring Alerts and Dashboards topic cover?

Create a Cloud Monitoring notification channel, alert policy and dashboard, then test the path so alerts reach a person instead of failing silently.

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