Cloud Monitoring PromQL Query

Cloud Monitoring PromQL Query

Generates valid PromQL queries for Cloud Monitoring metrics from metric descriptors and resource details, validating them and recovering from errors.

Skill files6 files

references/

scripts/

SKILL.md206 lines
1
---
2
name: cloud-monitoring-promql-query
3
metadata:
4
version: "1.0.1"
5
category: CloudObservabilityAndMonitoring
6
description: >-
7
Generates valid PromQL queries from Cloud Monitoring metric descriptors and
8
resource parameters. Use when asked to create, generate, write, or format
9
PromQL queries, PromQL strings, or PromQL aggregations for Cloud Monitoring
10
metrics and resources. Don't use for raw metric discovery or metric selection.
11
---
12
13
# Cloud Monitoring PromQL Generator
14
15
Use this skill to generate a valid PromQL query from any Cloud Monitoring metric
16
type. This guide applies to all Cloud Monitoring metric types by mapping Cloud
17
Monitoring metric and resource descriptors to PromQL structures.
18
19
## Attribution
20
21
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
22
MUST read [Usage Attribution](references/attribution.md). For commands executed
23
directly in the terminal (never in generated scripts, Terraform, or user code),
24
prefix `gcloud` with
25
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-monitoring-promql-query)"`
26
and append `agent-skills/1.0 (skill:cloud-monitoring-promql-query)` to `User-Agent` headers.
27
28
## Workflow
29
30
### Resolve Project ID (CRITICAL & BLOCKING)
31
32
Before performing any other actions (such as searching code, reading references,
33
or running validation), you MUST verify whether the Google Cloud Project ID is
34
available:
35
36
1. **Check Prompt/Payload**: Look for the Project ID in the user's prompt or
37
input.
38
2. **Check Environment**: If the Project ID is not present in the prompt, you
39
MUST run `gcloud config get-value project` to attempt to resolve it from the
40
environment.
41
3. **Ask for Clarification (BLOCKING)**: If the Project ID is not in the prompt
42
AND the `gcloud` command fails, returns an empty string, or is unavailable,
43
you MUST immediately stop. Do NOT generate a PromQL query, do not run the
44
validation script, and do not use placeholders (like `YOUR_PROJECT_ID`). You
45
must refuse to proceed and ask the user to provide the Project ID.
46
47
### Inspect Metric and Resource Descriptors
48
49
1. **Use Provided Descriptors First**: If the user's prompt already includes
50
metric descriptor details (such as `metric.type`, `metricKind`, `valueType`,
51
or `monitoredResourceTypes`) or specific resource filter values, use those
52
values directly instead of calling the Cloud Monitoring API.
53
2. **Discover Missing Descriptors**: If exact metric descriptors
54
(`metric.type`, `metricKind`, `valueType`) are missing or underspecified,
55
resolve the target metric type's descriptor using one of these paths:
56
* **Vague Query**: If the prompt is vague (for example, `"VM CPU usage"`),
57
use the `cloud-monitoring-metric-selection` skill first to identify the
58
specific metric type.
59
* **Known Metric Type**: If you already have the specific metric type name
60
(for example, `compute.googleapis.com/instance/cpu/utilization`) but
61
need its descriptor, call the
62
`google-cloud-monitoring:list_metric_descriptors` MCP tool. If the tool
63
is missing, refer to the `cloud-monitoring-metric-selection` skill to
64
configure the Cloud Monitoring MCP server.
65
* **Fallback**: If the MCP tool cannot be configured, fall back to making
66
a direct Cloud Monitoring API call.
67
3. **Identify Key Fields**: From the retrieved descriptor, identify four key
68
schema attributes:
69
* **`type`**: The Cloud Monitoring metric type string.
70
* **`metricKind`**: `GAUGE`, `DELTA`, or `CUMULATIVE`.
71
* **`valueType`**: `INT64`, `DOUBLE`, `DISTRIBUTION`, or `BOOL`.
72
* **`monitoredResourceTypes`**: Compatible `resource.type` strings
73
required for resource scoping and grouping.
74
75
### Resolve Resource Filters & Discovery Protocol
76
77
To filter data by a specific resource instance, apply these resource rules and
78
discovery protocols:
79
80
1. **Monitored Resource Filter**: Always include the
81
`monitored_resource="<type>"` filter in your query to prevent collisions
82
across services that share metric names.
83
* **Example**: `monitored_resource="gae_app"`
84
2. **Preserve User Literals (CRITICAL)**: ALWAYS use the literal resource
85
names, namespaces, and IDs provided in the user's prompt. Do **NOT**
86
override or replace these values with active resource names found during
87
Cloud Monitoring discovery unless the user explicitly asked you to find
88
active resources. Telemetry discovery must only be used to identify metric
89
type names and label keys, not to override user input.
90
3. **Resource Identifier Mapping**:
91
* **Direct & Specific Keys**: Use the most specific resource identifier
92
available. **Example**: `version_id`, `cluster_name`.
93
* **Name-to-ID Resolution**: If the user filters by a resource *name*
94
(such as `"instance-1"`), but the resource schema uses numeric IDs (like
95
`instance_id`), use PromQL string name labels instead of numeric ID
96
labels. **Example**: `instance_name`, `metadata_system_name`.
97
* **Composite Identifiers**: For resources with hierarchical identifiers
98
(such as Cloud SQL databases), format the filter as a single composite
99
key. Do NOT split them into separate `project_id` and sub-resource
100
labels. **Example**: `database_id="{project_id}:{instance_name}"`.
101
4. **Resource Label Discovery**: The
102
`google-cloud-monitoring:list_metric_descriptors` tool only returns
103
metric-specific labels. If the label schema for a monitored resource is
104
unknown, fetch the resource descriptor directly from the Cloud Monitoring v3
105
REST API (`projects.monitoredResourceDescriptors.get`):
106
107
```bash
108
TOKEN=$(gcloud auth application-default print-access-token 2>/dev/null || gcloud auth print-access-token)
109
curl -s -H "Authorization: Bearer ${TOKEN}" \
110
"https://monitoring.googleapis.com/v3/projects/{project_id}/monitoredResourceDescriptors/{monitored_resource_type}"
111
```
112
113
An HTTP 200 OK response returns the `MonitoredResourceDescriptor` object
114
containing the `labels` array with the exact resource label keys for that
115
resource.
116
117
### Choose Aggregation Structure & Defaults
118
119
The query structure and aggregation functions (such as `rate`,
120
`histogram_quantile`, `sum`, or `avg`) depend on the metric type and how it is
121
visualized.
122
123
1. **Consult the Reference**: Consult the
124
[Cloud Monitoring to PromQL Basic Aggregations Reference](references/basic_aggregations.md)
125
as the single source of truth to map Cloud Monitoring properties (Metric
126
Kind, Value Type, Aligner, Reducer) to their PromQL structures.
127
2. **SRE Aggregation & Visualization Rules**:
128
* **Do NOT sum or average ratio/percentage utilization metrics** (like CPU
129
% or Memory limit utilization) across resource instances. Instead, keep
130
them unaggregated (raw metric), group by instance, or wrap in `topk(30,
131
avg_over_time(...))`.
132
* **State Label Filtering (CRITICAL)**: Only the metrics
133
`agent.googleapis.com/memory/percent_used` and
134
`agent.googleapis.com/disk/percent_used` require `{state!="free"}`. Do
135
**NOT** filter by `{state="used"}`.
136
137
### Format & Validate Query
138
139
Before presenting any PromQL queries, validate them using the linter:
140
141
#### Python Dependencies
142
143
Before executing the validation script (`scripts/validate_promql.py`), install
144
the required Python dependencies:
145
146
```bash
147
python3 -c "import promql_parser" || pip install promql-parser
148
```
149
150
#### Validation Procedure
151
152
1. **Format Constraints**:
153
* **Metric Name Normalization**: Convert Cloud Monitoring metric types to
154
PromQL metric names using this recipe:
155
1. **Split Domain and Path**: Split the Cloud Monitoring metric type by
156
the first slash (`/`) to separate the domain from the path.
157
* **Example**:
158
`storage.googleapis.com/network/received_bytes_count` -> domain
159
`storage.googleapis.com`, path `network/received_bytes_count`
160
2. **Normalize Domain**: Replace all periods (`.`) in the domain with
161
underscores (`_`).
162
* **Example**: `storage.googleapis.com` ->
163
`storage_googleapis_com`
164
3. **Normalize Path**: Replace all periods (`.`) and slashes (`/`) in
165
the path with underscores (`_`).
166
* **Example**: `network/received_bytes_count` ->
167
`network_received_bytes_count`
168
4. **Join with Colon**: Join the normalized domain and normalized path
169
with a colon (`:`).
170
* **Example**:
171
`storage_googleapis_com:network_received_bytes_count`
172
5. **Native Prometheus Metrics**: If the metric type has no slash, keep
173
it as-is.
174
* **Example**: `up` -> `up`, `http_requests_total` ->
175
`http_requests_total`
176
6. **Distribution Suffix**: If the metric's `valueType` is
177
`DISTRIBUTION`, append `_bucket` to the end of the normalized name.
178
* **Example**:
179
`cloudfunctions.googleapis.com/function/execution_times` ->
180
`cloudfunctions_googleapis_com:function_execution_times_bucket`
181
* Ensure the final query is a **single line with no comments** (no `#` or
182
`//`). Cloud Monitoring query translation collapses whitespace and can
183
cause code trailing a comment to be ignored or throw parsing errors.
184
* **Grouping Clause Syntax**: Ensure grouping clauses (such as `by
185
(label)`) only follow aggregation operators (such as `sum`, `avg`,
186
`min`, `max`, or `count`). Never place a grouping clause directly after
187
a metric selector.
188
* **Incorrect**: `metric{...} by (label)`
189
* **Correct**: `sum(rate(metric{...}[5m])) by (label)`
190
* **Fenced Output Code Block**: ALWAYS wrap the final verified PromQL
191
query in a fenced `promql` code block in your final response.
192
2. **Linter Verification**:
193
* Validate all generated queries in a single batch: `python3
194
<path_to_skill>/scripts/validate_promql.py --query '<q1>' '<q2>'`
195
* If validation fails, read
196
[PromQL Error Recovery Guide](references/promql_error_recovery.md) to
197
diagnose and fix common type mismatches and syntax errors before
198
repeating the loop.
199
200
## References
201
202
* [Cloud Monitoring PromQL Basic Aggregations Reference](references/basic_aggregations.md)
203
* [Cloud Monitoring PromQL Error Recovery Guide](references/promql_error_recovery.md)
204
* [Cloud Monitoring PromQL Documentation](https://docs.cloud.google.com/monitoring/promql.md.txt)
205
* [Cloud Monitoring Monitored Resource Types Reference](https://docs.cloud.google.com/monitoring/api/resources.md.txt)
206

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…