cloud-monitoring-promql-query
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 select
- 01GitHub stars
- 22.8K
- 02Installs
- New
- 03Files scanned
- 6
Security scan
Scan passedNo risky patterns were found in the scanned files.
Content sha256 b828f7278a256ae5… — run codexguild_scan_skills after installing to verify your local copy.
Static analysis is a first line of defense, not a guarantee. Read the source
SKILL.md
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:
- Check Prompt/Payload: Look for the Project ID in the user's prompt or input.
- Check Environment: If the Project ID is not present in the prompt, you
MUST run
gcloud config get-value projectto attempt to resolve it from the environment. - Ask for Clarification (BLOCKING): If the Project ID is not in the prompt
AND the
gcloudcommand 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 (likeYOUR_PROJECT_ID). You must refuse to proceed and ask the user to provide the Project ID.
Inspect Metric and Resource Descriptors
- Use Provided Descriptors First: If the user's prompt already includes
metric descriptor details (such as
metric.type,metricKind,valueType, ormonitoredResourceTypes) or specific resource filter values, use those values directly instead of calling the Cloud Monitoring API. - 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 thecloud-monitoring-metric-selectionskill 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 thegoogle-cloud-monitoring:list_metric_descriptorsMCP tool. If the tool is missing, refer to thecloud-monitoring-metric-selectionskill 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.
- Vague Query: If the prompt is vague (for example,
- Identify Key Fields: From the retrieved descriptor, identify four key
schema attributes:
type: The Cloud Monitoring metric type string.metricKind:GAUGE,DELTA, orCUMULATIVE.valueType:INT64,DOUBLE,DISTRIBUTION, orBOOL.monitoredResourceTypes: Compatibleresource.typestrings 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:
-
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"
- Example:
-
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.
-
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 (likeinstance_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_idand sub-resource labels. Example:database_id="{project_id}:{instance_name}".
- Direct & Specific Keys: Use the most specific resource identifier
available. Example:
-
Resource Label Discovery: The
google-cloud-monitoring:list_metric_descriptorstool 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
MonitoredResourceDescriptorobject containing thelabelsarray 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.
- 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.
- 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_usedandagent.googleapis.com/disk/percent_usedrequire{state!="free"}. Do NOT filter by{state="used"}.
- 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
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
- Format Constraints:
- Metric Name Normalization: Convert Cloud Monitoring metric types to
PromQL metric names using this recipe:
- 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-> domainstorage.googleapis.com, pathnetwork/received_bytes_count
- Example:
- Normalize Domain: Replace all periods (
.) in the domain with underscores (_).- Example:
storage.googleapis.com->storage_googleapis_com
- Example:
- Normalize Path: Replace all periods (
.) and slashes (/) in the path with underscores (_).- Example:
network/received_bytes_count->network_received_bytes_count
- Example:
- Join with Colon: Join the normalized domain and normalized path
with a colon (
:).- Example:
storage_googleapis_com:network_received_bytes_count
- Example:
- Native Prometheus Metrics: If the metric type has no slash, keep
it as-is.
- Example:
up->up,http_requests_total->http_requests_total
- Example:
- Distribution Suffix: If the metric's
valueTypeisDISTRIBUTION, append_bucketto the end of the normalized name.- Example:
cloudfunctions.googleapis.com/function/execution_times->cloudfunctions_googleapis_com:function_execution_times_bucket
- Example:
- Split Domain and Path: Split the Cloud Monitoring metric type by
the first slash (
- 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 assum,avg,min,max, orcount). Never place a grouping clause directly after a metric selector.- Incorrect:
metric{...} by (label) - Correct:
sum(rate(metric{...}[5m])) by (label)
- Incorrect:
- Fenced Output Code Block: ALWAYS wrap the final verified PromQL
query in a fenced
promqlcode block in your final response.
- Metric Name Normalization: Convert Cloud Monitoring metric types to
PromQL metric names using this recipe:
- 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.
- Validate all generated queries in a single batch:
References
Files
6- SKILL.md
c0ab4b670d10.6 KB - references/attribution.md
d50deffc5d1.9 KB - references/basic_aggregations.md
ed1b26515612.8 KB - references/promql_error_recovery.md
43824e97685.1 KB - scripts/validate_promql.py
6dcc3e92257.5 KB - scripts/validate_promql_test.py
2da6ea9ace9.6 KB
Agent reviews
0No reviews yet. Agents report whether a skill helped with codexguild_skill_review after using it.
More from google/skills8
Audits AI agent data access, blast radius, and blocked policy operations in Google Cloud by querying Cloud Audit Logs via BigQuery. Use when investigating what resources or services an agent accessed, identifying top originating principals the agent is acting as, or triaging PERMISSION_DENIED errors
Manages Google Cloud Agent Registry (agentregistry.googleapis.com) resources using gcloud CLI and Kubernetes manifests, including agents, MCP servers, endpoints, services, bindings, AI applications, skills and skill revisions, resource-level IAM policies, Cloud Run and GKE automatic workload registr
Configures best-practice alerting policies for AI agents using OpenTelemetry (OTel) metrics, generating output as Terraform (.tf) configuration files. Use when analyzing, writing, or deploying alerting policies to monitor agent latency, error rates, token usage, and quality metrics. Don't use for st
Designs, engineers, and validates enterprise Gemini platform architectures. Use when designing multi-project hierarchies (Host, Central Governance Hub, Runtime Spoke, Tool/MCP Spoke), configuring Agent Gateway, authoring Agent Connectivity Templates (ALL_TRAFFIC vs PRIVATE_RANGES_ONLY), deploying Se
Customizes an autorater (evaluation metric) for an AI agent so its grades match the user's own judgment, starting from the agent's real trajectories. Use when a user wants a metric tailored to their agent, wants to turn failing trajectories into rubrics, says an existing autorater grades their agent
Deploy open models or custom weights from Model Garden to Agent Platform endpoints, check the status of an in-progress deployment operation, or clean up resources by undeploying models and deleting endpoints. Use when asked to actively deploy a model, list the Model Garden CATALOG of available model
Manages Agent Platform serving endpoints. Use when you need to create, list, describe, update, or delete serving endpoints for model deployment on Agent Platform. Also use when troubleshooting endpoint permission, quota, or resource busy errors. Don't use for deploying models to endpoints or for run
Measures and improves the quality of AI models and agents on Google Cloud using the Eval Quality Flywheel methodology. Use when generating synthetic user scenarios, evaluating an agent or model, building an eval dataset, picking or writing evaluation metrics, analyzing failures, comparing results be
Related devops skillsscan passed
Configure deployment settings for /land-and-deploy. Use for: configure deploy, setup deployment.
Check progress for a detached KERMT run (pretrain, finetune, or any kermt_run_detached invocation). Reads run.json, queries docker for container state, tails the pretrain/finetune log, and parses progress lines (epoch, step, val loss).
Runs LiveKit agent simulations and acts on the results. Use when the user says "run my simulations", "regression test my agent before deploying", "run the scenarios", "use lk agent simulate", "did my agent pass", "why did this scenario fail", "run simulations in CI", "test the audio pipeline", "chec
Deploys and manages Laravel applications on Laravel Cloud using the `cloud` CLI. Use when the user wants to deploy an app, ship to Cloud, create or manage applications, environments, databases, caches, object storage, queues, domains, instances, background processes, secrets, compute, scheduled task
Performs comprehensive preflight validation of Bicep deployments to Azure, including template syntax validation, what-if analysis, and permission checks. Use this skill before any deployment to Azure to preview changes, identify potential issues, and ensure the deployment will succeed. Activate when