Generated banner for Cloud Monitoring Alert Configuration
Generated logo for Cloud Monitoring Alert Configuration

Cloud Monitoring Alert Configuration

GoogleOfficialPublished by Google

  • Skill
  • Workflow
  • Cloud and DevOps
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Configures Cloud Monitoring alerting policies using Terraform and PromQL across Cloud Run, Google Kubernetes Engine (GKE), Compute Engine, AI Hypercomputer reservations, Vertex AI Agent Engine, and generic Google Cloud resources. Use when creating, reviewing, migrating, or deduplicating Terraform alerting policies for latency, traffic, error rates, saturation, host or reservation maintenance, GPU XID insights, or AI agent telemetry. Don't use for standalone PromQL query authoring without alerting, log querying, or billing cost audits.
— the description by Google

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured workflow for defining, reviewing, and managing Cloud Monitoring alerting policies. It leverages Terraform for infrastructure-as-code and PromQL for metric conditions, ensuring consistent observability across Google Cloud resources including Cloud Run, GKE, Compute Engine, and AI Agent platforms. The skill enforces best practices like the Four Golden Signals, dynamic grouping, and proper labeling, while providing clear paths for delegating SLO-specific configurations and notification channel management.

What it does

  • Generates parameterized Terraform configurations for Cloud Monitoring alert policies.
  • Implements PromQL-based conditions for high-signal monitoring.
  • Provides resource-specific guidance for GKE, Cloud Run, Compute Engine, and AI agents.
  • Enforces standardized labeling for all generated alerting resources.
  • Integrates with specialized scripts to analyze traffic patterns for AI agent telemetry.
  • Delegates SLO and notification channel configuration to dedicated skills.

When to use it

  • When creating or migrating Terraform-based alerting policies for Google Cloud infrastructure.
  • When setting up monitoring for AI agent reliability, quality, and cost telemetry.
  • When deduplicating existing alert policies to improve signal-to-noise ratios.
  • When configuring alerts for latency, traffic, error rates, or saturation across cloud services.

Advantages

  • Ensures consistent observability standards across diverse cloud environments.
  • Reduces manual configuration errors through structured Terraform templates.
  • Promotes best practices like dynamic grouping and the Four Golden Signals.
  • Maintains clear separation of concerns by delegating SLO and notification tasks.
  • Provides data-driven traffic analysis for accurate AI agent alert thresholds.

Usage examples

“Create a Terraform alerting policy for high latency on my GKE service.”
The agent will guide you through selecting the appropriate GKE PromQL queries, generate the google_monitoring_alert_policy Terraform resource, and prompt you to attach notification channels.
“Configure a cost alert for my Vertex AI Agent based on token usage.”
The agent will run the traffic analysis script to determine your workload pattern and generate a PromQL-based alert policy tailored to your agent's historical token consumption.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/google/cloud-monitoring-alert-configuration/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip cloud-monitoring-alert-configuration.zip -d .agents/skills

Documentation by Google

Configure Cloud Monitoring Alerts

Configure high-signal alerting policies in Cloud Monitoring using Terraform (google_monitoring_alert_policy) and PromQL (condition_prometheus_query_language).

Usage Attribution

For all gcloud CLI, REST API, and MCP attribution requirements when executing commands with this skill, follow the instructions in Usage Attribution.

Enforce Core Alerting Rules

  1. Apply the Four Golden Signals: Cover latency, traffic, errors, and saturation for the target workload.

  2. Use Dynamic Grouping: Aggregate metrics by resource labels and parameterize thresholds with Terraform variables. Never hardcode ephemeral pod or instance identifiers.

  3. Default to PromQL: Use Prometheus Query Language (PromQL) for metric conditions, and use log-based alerts (condition_matched_log or google_logging_metric) for lifecycle and audit events.

  4. Attach Skill Attribution Labels: Always include user_labels with created-with-google-skill = "cloud-monitoring-alert-configuration" on every generated google_monitoring_alert_policy resource.

  5. Require User Confirmation Before Mutating Resources: Never execute commands that modify infrastructure, enable telemetry, create online monitors, or apply Terraform without waiting for explicit user confirmation.

  6. Prompt for Notification Channels: Alerting policies without notification channels incur charges without notifying anyone during an incident. Whenever notification channels are not specified in the user prompt across any workflow, explicitly inform the user that no notification channels are attached to the alerting policies, advise them to configure and attach notification channels before deploying, and ask at the end of your response if they want to configure notification channels.

Route by Target Resource Type

Identify the target resource type and read only the matching reference file directly. Never run directory listings or workspace file searches to look for queries or .tf files unless the prompt explicitly provides a file path. If a user asks to fix or validate a PromQL query without providing the query text or a file path, construct a representative broken-and-corrected query example directly.

Configure Cloud Run Alerts
Configure Google Kubernetes Engine Alerts
Configure AI Agent Alerts
Configure Compute Engine and AI Hypercomputer Alerts
  • Compute Engine VMs, MIGs, GPU XID Insights, Host or Reservation Maintenance (type=scheduled, unscheduled, or multiple), and Machine or Domain Health: compute_engine_alerts.md

Configure Generic Resource Alerts
Delegate Service Level Objective Alerts

Delegate to the google-cloud-slo-alert-configuration skill. That skill owns the SLO setup wizard, the burn-rate PromQL templates (references/promql_templates.md), the SLI metric mapping (references/service_metrics.md), and the App Hub scoping labels (references/app_hub_labels.md). Do NOT duplicate those templates here or claim that this skill owns its own SLO PromQL template library.

Delegate whenever the user asks for an availability or latency SLO, an error budget or burn-rate alert, or a Service Level Objective on any resource. When SLOs are only one part of a broader request (for example, a full production alerting suite for a Cloud Run service), delegate the SLO policies and continue generating the remaining golden-signal policies from the resource-specific reference in the same response.

Every resource reference carries a Context to hand off list naming the SLI metric, its good or bad filter, and the grouping labels — under a ## Delegate Service Level Objective Alerts heading for Cloud Run and generic resources, and inside the SLO section itself for GKE and Agent Platform. Read it and pass that context on, so the SLO skill does not repeat discovery you have already done. When delegating, you MUST also:

  1. State the SLO target and window explicitly if the user gave them, or let the SLO skill apply its SRE defaults (99.9% over a rolling 28 days) if they did not.

  2. Require the returned policies to carry user_labels with created-with-google-skill = "cloud-monitoring-alert-configuration" so attribution stays consistent with the rest of the generated suite. This literal value does NOT change when you delegate: the label records the entry-point skill, not whichever skill supplied the template. Do NOT set created-with-google-skill = "google-cloud-slo-alert-configuration" on policies generated through this delegation.

  3. Preserve the burn-rate duration contract, which google-cloud-slo-alert-configuration does not specify: Fast Burn (1h and 5m windows, factor 14.4) carries duration = "300s", and Slow Burn ([3d] and [6h] lookback, factor 1.0) omits the duration field entirely — do not emit duration = "0s" in its place. Cloud Monitoring rejects a non-zero retest buffer when the lookback window exceeds 25 hours.

  4. When no notification channels are provided, inform the user that no notification channels are attached to the alerting policies, advise them to configure and attach notification channels, and ask if they want to configure notification channels.

[!IMPORTANT] Always tell the user about the referral, even on the fallback path. Some reference files in this skill include standalone burn-rate templates to use when the google-cloud-slo-alert-configuration skill is not installed. If you emit policies from those fallback templates, your response MUST still tell the user that google-cloud-slo-alert-configuration owns SLO configuration, state that the emitted policies use the local fallback templates, and list the handoff context. Never silently present SLO policies as if this skill owned them.

[!NOTE] Exception: Agent Platform (OpenTelemetry-instrumented AI agents on any runtime, including Vertex AI Agent Engine and Cloud Run) is the one resource whose Fast and Slow burn policies live in this skill and remain authoritative. Delegate only for SLO customization — see Reliability.

  • Notification Channels: Delegate to cloud-monitoring-notification-channels-configuration to configure email, PagerDuty, Pub/Sub, or Slack channels. When an alerting policy has no notification channels attached, inform the user that no notification channels are attached and that they should configure notification channels and attach them to the alerting policy.

  • PromQL Authoring: Delegate to cloud-monitoring-promql-query for standalone PromQL query authoring or metric exploration.

Follow the Alert Configuration Workflow

  1. Discover: Identify target resources, metric schemas, and scoping projects using the lookup commands in the matching reference file (such as discover_metric_schema.py for Compute Engine metrics and other Google Cloud resource metrics, or gather_agent_info.py, check_telemetry.py, analyze_traffic.py, create_online_monitor.py, list_trace_scope_table_names.py, and list_log_scope_table_names.py for AI agents).

  2. Route: Load the reference file for the target resource type or delegate SLOs to google-cloud-slo-alert-configuration.

  3. Generate: Produce parameterized Terraform HCL configurations with required user_labels.

  4. Validate: When the loaded reference file requires a validation script (such as lint_promql.py, validate_config.py, lint_syntax.py, or scan_duplicates.py), run or print that exact script command. Do not list or search the scripts/ directory.

  5. Explain and Prompt: Explain each alert policy in plain English. When no notification channels are provided, tell the user that no notification channels are attached to the alerting policy, advise them to configure and attach notification channels, and ask if they want to configure notification channels.

Files

scripts/agent_platform/config_utils.py

#!/usr/bin/env python3
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Shared utility functions for alert configuration validation."""

import re

def check_balanced_chars(
    query: str, open_char: str, close_char: str
) -> str | None:
  """Checks if parenthesis or braces are balanced."""
  count = 0
  for i, char in enumerate(query):
    if char == open_char:
      count += 1
    elif char == close_char:
      count -= 1
      if count < 0:
        return f"Unbalanced '{close_char}' at position {i}"
  if count != 0:
    return f"Unbalanced '{open_char}' (net count: {count})"
  return None


def parse_promql_duration(duration_str: str) -> float | None:
  """Converts PromQL duration string to hours."""
  match = re.match(r"^(\d+)([smhdw])$", duration_str)
  if not match:
    return None
  val, unit = match.groups()
  val = int(val)
  if unit == "s":
    return val / 3600
  if unit == "m":
    return val / 60
  if unit == "h":
    return val
  if unit == "d":
    return val * 24
  if unit == "w":
    return val * 24 * 7
  return None


def get_max_lookback_hours(query: str) -> float:
  """Calculates the maximum lookback in hours from windows and offsets."""
  max_hours = 0

  # Check windows and subqueries
  window_matches = re.finditer(r"\[([^\]]+)\]", query)
  for match in window_matches:
    window_str = match.group(1)
    range_str = window_str.split(":")[0]
    hours = parse_promql_duration(range_str)
    if hours and hours > max_hours:
      max_hours = hours

  # Check offsets
  offset_matches = re.finditer(r"\boffset\s+(\S+)", query)
  for match in offset_matches:
    offset_str = match.group(1)
    hours = parse_promql_duration(offset_str)
    if hours and hours > max_hours:
      max_hours = hours

  return max_hours


def validate_policy_duration(policy: dict) -> list[str]:
  """Validates duration based on lookback window."""
  errors = []
  max_lookback = 0
  for query in policy["queries"]:
    lookback = get_max_lookback_hours(query)
    if lookback > max_lookback:
      max_lookback = lookback

  quality_metrics = [
      "final_response_quality_v1",
      "tool_use_quality_v1",
      "hallucination_v1",
  ]

  if policy["signal_type"] in quality_metrics:
    if policy["duration"] != "300s":
      errors.append(
          "Duration Error: Quality alerts MUST set duration='300s'."
          f" Found duration='{policy['duration']}'."
      )
  elif max_lookback > 25:
    if policy["duration"] is not None:
      errors.append(
          "Duration Error: Long-lookback alerts (>25h) must NOT set a"
          f" duration. Found duration='{policy['duration']}' for lookback of"
          f" {max_lookback}h."
      )
  elif max_lookback > 0:  # It's a short-lookback PromQL alert
    if policy["duration"] != "300s":
      errors.append(
          "Duration Error: Short-lookback alerts (<=25h) MUST set"
          f" duration='300s'. Found duration='{policy['duration']}'."
      )
  return errors


def lint_query(query: str) -> list[str]:
  """Runs a suite of sanity lint checks on a PromQL query."""
  errors = []

  # 1. Balanced parentheses
  paren_err = check_balanced_chars(query, "(", ")")
  if paren_err:
    errors.append(f"Parentheses error: {paren_err}")

  # 2. Balanced curly braces
  brace_err = check_balanced_chars(query, "{", "}")
  if brace_err:
    errors.append(f"Curly braces error: {brace_err}")

  # 3. Time window validations (e.g., [5m], [1w:5m], [3d], [1h])
  window_matches = re.finditer(r"\[([^\]]+)\]", query)
  for match in window_matches:
    window_str = match.group(1)
    if not re.match(r"^\d+[smhdw](:(\d+[smhdw])?)?$", window_str):
      errors.append(
          "Invalid Prometheus time window/subquery interval:"
          f" '[{window_str}]' at position {match.start()}"
      )

  # 4. Lookback offset range validation (e.g. offset 1w, offset 1d)
  offset_matches = re.finditer(r"\boffset\s+(\S+)", query)
  for match in offset_matches:
    offset_str = match.group(1)
    if not re.match(r"^\d+[smhdw]$", offset_str):
      errors.append(
          f"Invalid lookback offset format: 'offset {offset_str}' at position"
          f" {match.start()}"
      )

  # 5. Ensure the query references a supported group in a label filter
  # or grouping aggregation.
  supported_groups = ["namespace", "gen_ai_agent_name"]
  search_regex = (
      r"\b(by|without)\s*\([^)]*\b("
      + "|".join(supported_groups)
      + r")\b[^)]*\)"
  )
  has_group = bool(re.search(search_regex, query))

  has_filter = False
  brace_matches = re.finditer(r"\{([^}]+)\}", query)
  for match in brace_matches:
    for group in supported_groups:
      if group in match.group(1):
        has_filter = True
        break
    if has_filter:
      break

  if not (has_group or has_filter):
    errors.append(
        "Query is missing agent identifier reference. It must either group"
        " by it using aggregations (e.g., 'by (gen_ai_agent_name)') or filter"
        " on it (e.g., '{gen_ai_agent_name=\"...\"}')."
    )

  return errors


def extract_alert_policies(hcl_content: str) -> list[dict]:
  """Extracts resource 'google_monitoring_alert_policy' blocks and metadata."""
  policies = []
  pattern = re.compile(
      r'resource\s+"google_monitoring_alert_policy"\s+"([^"]+)"\s*\{'
  )

  for match in pattern.finditer(hcl_content):
    resource_name = match.group(1)
    start_pos = match.start()

    brace_count = 0
    end_pos = -1
    in_string = False
    escape = False

    for i in range(match.end() - 1, len(hcl_content)):
      char = hcl_content[i]
      if escape:
        escape = False
        continue
      if char == "\\":
        escape = True
        continue
      if char == '"':
        in_string = not in_string
        continue
      if not in_string:
        if char == "{":
          brace_count += 1
        elif char == "}":
          brace_count -= 1
          if brace_count == 0:
            end_pos = i + 1
            break

    if end_pos == -1:
      continue

    block_content = hcl_content[start_pos:end_pos]

    # Extract display_name
    display_name_match = re.search(
        r'display_name\s*=\s*"([^"]+)"', block_content
    )
    display_name = display_name_match.group(1) if display_name_match else ""

    # Extract duration
    duration_match = re.search(r'duration\s*=\s*"([^"]+)"', block_content)
    duration = duration_match.group(1) if duration_match else None

    # Extract PromQL queries
    queries = [
        q.group(1)
        for q in re.finditer(
            r"query\s*=\s*<<-?EOT\n(.*?)\n\s*EOT",
            block_content,
            re.DOTALL,
        )
    ]
    if not queries:
      for match in re.finditer(
          r"query\s*=\s*\"((?:[^\"\\]|\\[\s\S])*)\"", block_content
      ):
        raw_query = match.group(1)
        clean_query = re.sub(r"\\+\"", '"', raw_query).replace("\\\\", "\\")
        queries.append(clean_query)

    # Extract threshold filters
    filters = []
    filter_matches = re.finditer(
        r'filter\s*=\s*"((?:[^"\\]|\\.)*)"', block_content
    )
    for f_match in filter_matches:
      filters.append(f_match.group(1))

    # Infer signal type
    signal_type = "unknown"
    res_lower, disp_lower = resource_name.lower(), display_name.lower()
    rules = [
        ("latency", "latency", "latency"),
        ("slo_burn_rate_fast", "fast", "slo_fast"),
        ("slo_burn_rate_slow", "slow", "slo_slow"),
    ]
    for res_pat, disp_pat, sig in rules:
      if res_pat in res_lower or disp_pat in disp_lower:
        signal_type = sig
        break
    else:
      # Check threshold filters for quality metric name
      for flt in filters:
        metric_match = re.search(
            r"metric\.labels\.evaluation_metric_name"
            r"\s*=\s*\\*\"([^\"\\]+)\\*\"",
            flt,
        )
        if metric_match:
          signal_type = metric_match.group(1)
          break

    engine_ids = []
    for query in queries:
      for engine_id in re.findall(
          r'(?:reasoning_engine_id|gen_ai_agent_name|namespace)'
          r'\s*=\s*"([^"]+)"',
          query,
      ):
        if engine_id not in engine_ids:
          engine_ids.append(engine_id)
    for flt in filters:
      id_matches = re.findall(
          r'(?:reasoning_engine_id|gen_ai_agent_name|namespace)'
          r'\s*=\s*\\*"([^"\\]+)\\*"',
          flt,
      )
      for engine_id in id_matches:
        if engine_id not in engine_ids:
          engine_ids.append(engine_id)
      resource_matches = re.findall(r"reasoningEngines/([0-9]+)", flt)
      for engine_id in resource_matches:
        if engine_id not in engine_ids:
          engine_ids.append(engine_id)

    policies.append({
        "resource_name": resource_name,
        "display_name": display_name,
        "signal_type": signal_type,
        "engine_ids": engine_ids,
        "queries": queries,
        "filters": filters,
        "duration": duration,
        "is_sql": "condition_sql" in block_content,
        "start_pos": start_pos,
        "end_pos": end_pos,
        "block_content": block_content,
    })

  return policies

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Google
Publisher
Google (Official)
Source
google/skills · skills/cloud/cloud-monitoring-alert-configuration · commit 2194d3b
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download cloud-monitoring-alert-configuration.zip