Skip to main content

cloud-monitoring-promql-query

We earn commissions when you shop through the links below.

Generates valid PromQL queries from Cloud Monitoring metric descriptors and resource parameters. Use when asked to create, generate, write, or format PromQL queries, PromQL strings, or PromQL aggregations for Cloud Monitoring metrics and resources. Don't use for raw metric discovery or metric selection.

v1.0.1New

Install this skill

No account required. Pick your tool, or use the command that detects it for you.

Run in your terminal. It detects your AI tool.

npx @skills-hub-ai/cli install google-cloud-skills-cloud-monitoring-promql-query
Or get the file:
Browse all CLI commands →
Manual setup by platform

Claude Code

~/.claude/skills/google-cloud-skills-cloud-monitoring-promql-query/SKILL.md

Setup guide →

Signing

SignedSLSA L2
Signed by
skills-hub.ai distributor
Method
Distributor-signed by skills-hub.aiCryptographically signed by the skills-hub.ai distributor key at publish time.
Signed
0Save

Instructions

Cloud Monitoring PromQL Generator

Use this skill to generate a valid PromQL query from any Cloud Monitoring metric
type. This guide applies to all Cloud Monitoring metric types by mapping Cloud
Monitoring metric and resource descriptors to PromQL structures.

Attribution

MUST READ: Before executing any gcloud, REST API, or MCP command, you
MUST read Usage Attribution. For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix gcloud with
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-monitoring-promql-query)"
and append agent-skills/1.0 (skill:cloud-monitoring-promql-query) to User-Agent headers.

Workflow

Resolve Project ID (CRITICAL & BLOCKING)

Before performing any other actions (such as searching code, reading references,
or running validation), you MUST verify whether the Google Cloud Project ID is
available:

  1. Check Prompt/Payload: Look for the Project ID in the user's prompt or
    input.
  2. Check Environment: If the Project ID is not present in the prompt, you
    MUST run gcloud config get-value project to attempt to resolve it from the
    environment.
  3. Ask for Clarification (BLOCKING): If the Project ID is not in the prompt
    AND the gcloud command fails, returns an empty string, or is unavailable,
    you MUST immediately stop. Do NOT generate a PromQL query, do not run the
    validation script, and do not use placeholders (like YOUR_PROJECT_ID). You
    must refuse to proceed and ask the user to provide the Project ID.

Inspect Metric and Resource Descriptors

  1. Use Provided Descriptors First: If the user's prompt already includes
    metric descriptor details (such as metric.type, metricKind, valueType,
    or monitoredResourceTypes) or specific resource filter values, use those
    values directly instead of calling the Cloud Monitoring API.
  2. Discover Missing Descriptors: If exact metric descriptors
    (metric.type, metricKind, valueType) are missing or underspecified,
    resolve the target metric type's descriptor using one of these paths:
    • Vague Query: If the prompt is vague (for example, "VM CPU usage"),
      use the cloud-monitoring-metric-selection skill first to identify the
      specific metric type.
    • Known Metric Type: If you already have the specific metric type name
      (for example, compute.googleapis.com/instance/cpu/utilization) but
      need its descriptor, call the
      google-cloud-monitoring:list_metric_descriptors MCP tool. If the tool
      is missing, refer to the cloud-monitoring-metric-selection skill to
      configure the Cloud Monitoring MCP server.
    • Fallback: If the MCP tool cannot be configured, fall back to making
      a direct Cloud Monitoring API call.
  3. Identify Key Fields: From the retrieved descriptor, identify four key
    schema attributes:
    • type: The Cloud Monitoring metric type string.
    • metricKind: GAUGE, DELTA, or CUMULATIVE.
    • valueType: INT64, DOUBLE, DISTRIBUTION, or BOOL.
    • monitoredResourceTypes: Compatible resource.type strings
      required for resource scoping and grouping.

Resolve Resource Filters & Discovery Protocol

To filter data by a specific resource instance, apply these resource rules and
discovery protocols:

  1. Monitored Resource Filter: Always include the
    monitored_resource="<type>" filter in your query to prevent collisions
    across services that share metric names.

    • Example: monitored_resource="gae_app"
  2. Preserve User Literals (CRITICAL): ALWAYS use the literal resource
    names, namespaces, and IDs provided in the user's prompt. Do NOT
    override or replace these values with active resource names found during
    Cloud Monitoring discovery unless the user explicitly asked you to find
    active resources. Telemetry discovery must only be used to identify metric
    type names and label keys, not to override user input.

  3. Resource Identifier Mapping:

    • Direct & Specific Keys: Use the most specific resource identifier
      available. Example: version_id, cluster_name.
    • Name-to-ID Resolution: If the user filters by a resource name
      (such as "instance-1"), but the resource schema uses numeric IDs (like
      instance_id), use PromQL string name labels instead of numeric ID
      labels. Example: instance_name, metadata_system_name.
    • Composite Identifiers: For resources with hierarchical identifiers
      (such as Cloud SQL databases), format the filter as a single composite
      key. Do NOT split them into separate project_id and sub-resource
      labels. Example: database_id="{project_id}:{instance_name}".
  4. Resource Label Discovery: The
    google-cloud-monitoring:list_metric_descriptors tool only returns
    metric-specific labels. If the label schema for a monitored resource is
    unknown, fetch the resource descriptor directly from the Cloud Monitoring v3
    REST API (projects.monitoredResourceDescriptors.get):

    TOKEN=$(gcloud auth application-default print-access-token 2>/dev/null || gcloud auth print-access-token)
    curl -s -H "Authorization: Bearer ${TOKEN}" \
    "https://monitoring.googleapis.com/v3/projects/{project_id}/monitoredResourceDescriptors/{monitored_resource_type}"
    

    An HTTP 200 OK response returns the MonitoredResourceDescriptor object
    containing the labels array with the exact resource label keys for that
    resource.

Choose Aggregation Structure & Defaults

The query structure and aggregation functions (such as rate,
histogram_quantile, sum, or avg) depend on the metric type and how it is
visualized.

  1. Consult the Reference: Consult the
    Cloud Monitoring to PromQL Basic Aggregations Reference
    as the single source of truth to map Cloud Monitoring properties (Metric
    Kind, Value Type, Aligner, Reducer) to their PromQL structures.
  2. SRE Aggregation & Visualization Rules:
    • Do NOT sum or average ratio/percentage utilization metrics (like CPU
      % or Memory limit utilization) across resource instances. Instead, keep
      them unaggregated (raw metric), group by instance, or wrap in topk(30, avg_over_time(...)).
    • State Label Filtering (CRITICAL): Only the metrics
      agent.googleapis.com/memory/percent_used and
      agent.googleapis.com/disk/percent_used require {state!="free"}. Do
      NOT filter by {state="used"}.

Format & Validate Query

Before presenting any PromQL queries, validate them using the linter:

Python Dependencies

Before executing the validation script (scripts/validate_promql.py), install
the required Python dependencies:

python3 -c "import promql_parser" || pip install promql-parser

Validation Procedure

  1. Format Constraints:
    • Metric Name Normalization: Convert Cloud Monitoring metric types to
      PromQL metric names using this recipe:
      1. Split Domain and Path: Split the Cloud Monitoring metric type by
        the first slash (/) to separate the domain from the path.
        • Example:
          storage.googleapis.com/network/received_bytes_count -> domain
          storage.googleapis.com, path network/received_bytes_count
      2. Normalize Domain: Replace all periods (.) in the domain with
        underscores (_).
        • Example: storage.googleapis.com ->
          storage_googleapis_com
      3. Normalize Path: Replace all periods (.) and slashes (/) in
        the path with underscores (_).
        • Example: network/received_bytes_count ->
          network_received_bytes_count
      4. Join with Colon: Join the normalized domain and normalized path
        with a colon (:).
        • Example:
          storage_googleapis_com:network_received_bytes_count
      5. Native Prometheus Metrics: If the metric type has no slash, keep
        it as-is.
        • Example: up -> up, http_requests_total ->
          http_requests_total
      6. Distribution Suffix: If the metric's valueType is
        DISTRIBUTION, append _bucket to the end of the normalized name.
        • Example:
          cloudfunctions.googleapis.com/function/execution_times ->
          cloudfunctions_googleapis_com:function_execution_times_bucket
    • Ensure the final query is a single line with no comments (no # or
      //). Cloud Monitoring query translation collapses whitespace and can
      cause code trailing a comment to be ignored or throw parsing errors.
    • Grouping Clause Syntax: Ensure grouping clauses (such as by (label)) only follow aggregation operators (such as sum, avg,
      min, max, or count). Never place a grouping clause directly after
      a metric selector.
      • Incorrect: metric{...} by (label)
      • Correct: sum(rate(metric{...}[5m])) by (label)
    • Fenced Output Code Block: ALWAYS wrap the final verified PromQL
      query in a fenced promql code block in your final response.
  2. Linter Verification:
    • Validate all generated queries in a single batch: python3 <path_to_skill>/scripts/validate_promql.py --query '<q1>' '<q2>'
    • If validation fails, read
      PromQL Error Recovery Guide to
      diagnose and fix common type mismatches and syntax errors before
      repeating the loop.

References

  • Cloud Monitoring PromQL Basic Aggregations Reference
  • Cloud Monitoring PromQL Error Recovery Guide
  • Cloud Monitoring PromQL Documentation
  • Cloud Monitoring Monitored Resource Types Reference
This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

Browse all →
google-cloud-storage-bucket-architectCreates Cloud Storage on Google Cloud (also known colloquially as GCS) buckets. Analyzes the workload (sensitive data, media hosting, ingestion, web hosting, archiving, backup, logging, analytics, AI/ML, or general-purpose), validates project-level security settings, and designs a secure-by-default, cost-effective configuration (location, storage class, uniform bucket-level access, public access prevention, soft delete, lifecycle) before creating it. Use whenever a user wants to create, make, set up, provision, or spin up a bucket, or needs object storage for an app, service, pipeline, or dataset — even a "simple" or "default" bucket, or when bucket creation is one step in a larger workflow. Outputs or executes the creation via gcloud, the JSON/REST API, Terraform, or SDK client libraries (C++, Java, Python, Go). Don't use for anything other than creating new buckets — for uploads, downloads, access changes, or reconfiguring existing buckets, use google-cloud-storage-basics.1 installsgke-cost-analysisAnswer natural language questions and perform analysis on GKE cluster and workload costs using BigQuery billing exports, cost allocation data, and live cluster monitoring metrics. Use when querying GKE costs across projects, namespaces, or workloads, analyzing billing reports in BigQuery (`bq`), checking cluster cost budgets (`gcloud billing`), or diagnosing cost drivers like pod requests vs. actual utilization (`kubectl top`). Don't use for applying cost optimization changes, creating rightsizing manifests (VPA/MPA), or selecting ComputeClasses (use gke-cost-optimization instead).1 installsmanaged-airflow-migrationsProvides guidance for migrating Apache Airflow DAGs in Managed Service for Apache Airflow (MSAA; formerly Cloud Composer). Covers migration to Airflow 2.11.1 (MSAA Gen 2 and 3) and Airflow 3 (MSAA Gen 3), including environment inspection, GCS download/upload and scanning patterns for breaking changes. Use when migrating the DAG code to newer Airflow version. Don't use when checking DAG run failures unrelated to code migration.1 installsfirebase-basicsProvides foundational Firebase CLI setup, CLI installation, version checks (`firebase-tools@latest --version`), CLI login (including --no-localhost), project creation, project selection (`firebase use`), and app config file downloads (`google-services.json`, `GoogleService-Info.plist`). Use ONLY for CLI login, project creation/switching, or downloading app config files. Don't use for Firebase Hosting deploy, Firestore, Auth, App Hosting, Data Connect, Crashlytics, or Remote Config.1 installsgoogle-cloud-solution-rag-enterprise-search-gke-sqldbDiscovers requirements, and generates architectural, design, and deployment guidance for a retrieval-augmented generation (RAG)-capable enterprise search system in Google Cloud. Use when users need a vector-enabled SQL database as the store and index for the embedding vectors, an open model and open-source inferencing framework, and Kubernetes containers to host all the application components. DON'T use this skill for fully-managed RAG, or SaaS search services, or when a non-SQL vector database is required.1 installsbigtable-basicsAssists in provisioning instances/tables, designing performant schemas, and querying data in Bigtable. Use when designing Bigtable row keys, configuring column families, writing SQL queries or client library code (Java, Go, Python) for Bigtable, or diagnosing performance/hotspotting issues. Also use when provisioning Bigtable clusters using gcloud or cbt CLIs. Don't use for generic Cloud SQL administration.1 installs

More from Google Cloud Skills

View source →
google-ads-api-mcp-setupGuides developers through downloading, configuring, and installing the official open-source Google Ads MCP Server. Use this skill when a user wants to connect their AI assistant (such as Gemini, Claude Code, or Cursor) to their Google Ads account to query campaigns or retrieve reporting metrics using natural language.4 installsspanner-basicsAssists in provisioning instances and databases, designing performant schemas, and querying data in Cloud Spanner on Google Cloud. Use when designing primary keys, writing SQL queries or client library code, or diagnosing performance issues.4 installsgke-workload-securityAudits, configures, and hardens workload-level security controls for Google Kubernetes Engine (GKE) applications and namespaces. Covers running security audits (`audit_cluster.sh`), enforcing Network Policies (default-deny and Dataplane V2 logging), isolating high-risk pods inside GKE Sandbox (`gVisor`), enforcing Pod Security Standards (`restricted` labeling) and pod securityContext, and mounting Secret Manager secrets via CSI (`SecretProviderClass`). Use when auditing workload security posture, isolating namespaces, applying pod security standards, or configuring network policies and secret volume mounts. Don't use for Workload Identity (use gke-workload-identity), cluster-wide control plane security, RBAC hardening, Binary Authorization, Shielded Nodes, or enabling platform-level GKE add-ons (use gke-platform-security instead).3 installsgke-manifest-generationGenerates and updates secure, production-ready Kubernetes YAML manifests optimized for GKE Autopilot and GKE Standard clusters. Use when creating or modifying GKE deployment manifests, configuring container security contexts, setting CPU/memory resource limits, defining readiness/liveness/startup probes, mounting secrets and volumes, configuring GKE Gateway API routes, targeting Spot VMs, or deploying AI model inference workloads (vLLM, TGI, Gemma). Don't use for live cluster operations, pod troubleshooting (use gke-workload-troubleshooting), or cluster infrastructure provisioning (use gke-cluster-creation).2 installsgke-upgradesPlans, executes, and validates Google Kubernetes Engine (GKE) cluster upgrades and maintenance operations for both Standard and Autopilot clusters. Produces upgrade plans, pre/post-upgrade checklists, maintenance runbooks with gcloud commands, release channel strategy, and troubleshooting guides. Handles node pool upgrade strategies (surge, blue-green), version compatibility, PDB management, and workload-specific concerns (stateful, GPU, operators). Use this skill whenever the user mentions GKE upgrades, Kubernetes version bumps, node pool maintenance, GKE patching, cluster version management, release channel selection, maintenance windows, surge upgrades, stuck upgrades, or any GKE lifecycle management task — even casual mentions like "we need to upgrade our clusters" or "plan our next GKE maintenance" or "our upgrade is stuck." Don't use for GKE cluster creation, application onboarding, general networking/routing setup, or security policy configurations (use gke-basics or relevant GK2 installsgoogle-cloud-recipe-networking-observabilityInvestigates Google Cloud networking issues by analyzing logs, metrics, and diagnostics. Use when investigating VPC Flow Logs, NAT, firewall, or threat logs, querying latency and throughput metrics, or running Connectivity Tests for path diagnostics.2 installs

More Build skills

Browse category →
senior-frontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle size. Use whenever the user wants a new component or app, a page feels slow, the bundle is too big, or asks for a frontend code review.634 installsui-design-systemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens with design_token_generator.py.534 installsfrontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.345 installssenior-backendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load tests. Use whenever the user's API is slow or broken, needs login or auth added, a schema change, or a new endpoint or service scaffolded.246 installsself-improving-agentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its topic files) for learnings worth keeping, promotes proven ones into CLAUDE.md or .claude/rules/, records a correction as a lesson that persists across sessions, prunes stale or duplicate entries, and turns a recurring fix into a reusable skill. Use whenever the user asks what you have learned or saved about the project, which memories should become permanent rules, to remember a lesson or stop repeating a mistake, or to clean up, audit or check memory health.173 installsusing-superpowersUse when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions145 installs

Frequently asked questions about cloud-monitoring-promql-query

What does the cloud-monitoring-promql-query skill do?

Generates valid PromQL queries from Cloud Monitoring metric descriptors and resource parameters. Use when asked to create, generate, write, or format PromQL queries, PromQL strings, or PromQL aggregations for Cloud Monitoring metrics and resources. Don't use for raw metric discovery or metric selection. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the cloud-monitoring-promql-query skill?

Run `npx @skills-hub-ai/cli install google-cloud-skills-cloud-monitoring-promql-query` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/google-cloud-skills-cloud-monitoring-promql-query/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does cloud-monitoring-promql-query work with?

cloud-monitoring-promql-query runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the cloud-monitoring-promql-query skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use cloud-monitoring-promql-query after installing it?

In Claude Code, type `/google-cloud-skills-cloud-monitoring-promql-query` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the cloud-monitoring-promql-query skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.