{"data":{"slug":"github-google-skills-skills-cloud-gke-alert-configuration-bef92ba07c32","title":"Configure GKE Alerting Policies with Terraform","summary":"Configure alerting policies for Google Kubernetes Engine (GKE) clusters using Terraform and PromQL. Use for monitoring service latency, error rates, and cluster health with Multi-Window Multi-Burn-Rate (MWMBR) SLO alerts.","url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-gke-alert-configuration-bef92ba07c32","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-google-skills-skills-cloud-gke-alert-configuration-bef92ba07c32","markdown_url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-gke-alert-configuration-bef92ba07c32.md","download_url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-gke-alert-configuration-bef92ba07c32\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Before executing any `gcloud`, REST API, or MCP command, you must read [Usage Attribution](references\/attribution.md). For commands executed directly in the terminal, prefix `gcloud` with `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION=\"agent-skills\/1.0 (skill:gke-alert-configuration)\"` and append `agent-skills\/1.0 (skill:gke-alert-configuration)` to `User-Agent` headers. Always declare variables in `variables.tf` for `project_id`, `cluster_name`, and `namespace`.","instructions":"---\nname: gke-alert-configuration\nmetadata:\n  version: \"1.0.3\"\n  category: CloudInfrastructure\n  canonical_source: https:\/\/github.com\/google\/skills\/tree\/main\/skills\/cloud\/gke-alert-configuration\ndescription: >-\n  Configures alerting policies in Terraform for Google Kubernetes Engine (GKE)\n  clusters, workloads, and services using PromQL and Google Cloud Managed Service\n  for Prometheus. Use when writing, analyzing, validating, or deploying Terraform\n  alerting policies to monitor GKE service latency, traffic, error rates using\n  Multi-Window Multi-Burn-Rate SLO alerts, memory saturation, and cluster health\n  such as CrashLoopBackOff and Node NotReady conditions.\n  Don't use for non-GKE compute runtimes such as standalone Compute Engine VMs or\n  standalone Cloud Run services without GKE.\n---\n\n# GKE Alert Configuration\n\nThis skill provides guidelines and best practices for creating robust,\nhigh-signal alerting policies for Google Kubernetes Engine workloads using\nGoogle Cloud Managed Service for Prometheus and Terraform. It ensures\ncomprehensive coverage of the **4 Golden Signals** and key cluster health\nmetrics while minimizing alert noise.\n\n--------------------------------------------------------------------------------\n\n## Attribution\n\n**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you\nMUST read [Usage Attribution](references\/attribution.md). For commands executed\ndirectly in the terminal (never in generated scripts, Terraform, or user code),\nprefix `gcloud` with\n`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION=\"agent-skills\/1.0 (skill:gke-alert-configuration)\"`\nand append `agent-skills\/1.0 (skill:gke-alert-configuration)` to `User-Agent` headers.\n\n## Critical Rules\n\n*   **Negative Triggers and Scope Redirection for Non-GKE Standalone Runtimes**:\n    *   This skill is strictly scoped to Google Kubernetes Engine (GKE)\n        workloads, clusters, and services using PromQL and Google Cloud Managed\n        Service for Prometheus.\n    *   **Do not use for non-GKE compute runtimes**, such as standalone Compute\n        Engine virtual machines or standalone Cloud Run services without GKE.\n    *   **STOP AND RESPOND DIRECTLY (Do Not Edit Files)**: When the user\n        requests alert configuration for non-GKE compute infrastructure:\n        1.  **Do not write, create, edit, or validate any Terraform files on\n            disk**.\n        2.  **Immediately stop and respond directly to the user in chat**:\n            *   **Explicitly Clarify Out-of-Scope**: State clearly that\n                standalone Compute Engine virtual machine monitoring or\n                standalone Cloud Run monitoring is out of scope for this\n                GKE-specific PromQL alerting skill, which is designed\n                specifically for GKE workloads using Google Cloud Managed\n                Service for Prometheus and PromQL.\n            *   **Do Not Generate GKE PromQL Alerts**: Do not create or generate\n                Kubernetes PromQL alert policies or fabricate Kubernetes\n                container, pod, or node resources for non-GKE infrastructure.\n            *   **Redirect the User**: Guide and redirect the user to standard\n                Google Cloud Monitoring metrics, such as\n                `compute.googleapis.com\/instance\/cpu\/utilization` or\n                `run.googleapis.com\/request_latencies`, using standard\n                `google_monitoring_alert_policy` with `condition_threshold` or\n                MQL, or recommend the relevant specialized Cloud observability\n                skill.\n*   **Mandatory `kube-state-metrics` (KSM) Cost Guardrail**:\n    *   Deploying open-source `kube-state-metrics` in Google Cloud Managed\n        Service for Prometheus incurs billable metric ingestion costs.\n    *   **STOP AND ASK PERMISSION FIRST (Do Not Edit Files)**: When a requested\n        alert rule relies on **Tier 2 KSM metrics** (such as `kube_cronjob_*`,\n        `kube_pod_status_phase`, `kube_persistentvolume_*`, `kube_deployment_*`,\n        `kube_statefulset_*`, `kube_job_*`, or `kube_daemonset_*`), **do not\n        write, create, edit, or validate any Terraform files or generate alert\n        policies before obtaining user approval**.\n    *   Instead, you **must immediately stop and respond directly to the user**\n        to:\n        1.  **Alert the user** that the requested alert requires\n            `kube-state-metrics`.\n        2.  **Explain the cost impact**: Detail that `kube-state-metrics` incurs\n            billable sample ingestion costs in Google Cloud Managed Service for\n            Prometheus.\n        3.  **Ask for explicit permission**: Ask the user for explicit\n            permission before assuming, enabling, or generating KSM-dependent\n            alert configurations.\n        4.  **Recommend filtering or allowlisting**: Suggest and recommend\n            filtering or allowlisting only the specific required metrics, such\n            as using a `PodMonitoring` resource with `metricRelabeling`\n            (`action: keep`) or KSM `--metric-allowlist` to minimize ingestion\n            costs. Provide a concrete allowlist example.\n    *   **Always prefer Non-KSM Native Alternatives** (Tier 1 cAdvisor or native\n        GKE metrics documented in\n        [metrics_and_alerts_catalog.md](references\/metrics_and_alerts_catalog.md))\n        whenever possible, such as using `container_memory_working_set_bytes`\n        and `container_spec_memory_limit_bytes` instead of\n        `kube_pod_container_resource_limits`.\n    *   **Explicit Tier and Cost Surcharge Identification in Response**: In\n        every response where you generate or recommend an alerting policy, you\n        **must explicitly state its classification tier and cost impact**:\n        *   **Tier 1 native or standard metric** (GKE built-in metrics, cAdvisor\n            `container_*`, kubelet volume stats, kubelet node conditions, and\n            control-plane metrics; see\n            [metrics_and_alerts_catalog.md](references\/metrics_and_alerts_catalog.md)):\n            State that it is a **Tier 1 native or standard metric with zero KSM\n            cost surcharge**.\n        *   **Tier 2 KSM metric**: State that it is a **Tier 2 KSM-dependent\n            metric** and follow the permission and allowlisting guardrail above.\n            *(Tip: Generally, metrics with the `kube_` prefix that represent\n            resource state or metadata belong to Tier 2).*\n*   **Plan-Validate-Execute Loop for Approved File Edits**: When modifying,\n    adding, or merging approved Terraform files on disk in a workspace, follow\n    the three-phase workflow:\n    1.  **Plan**: Draft a structured change plan (`changes.json`) containing\n        proposed policy resource names, PromQL expressions, grouping labels, and\n        durations.\n    2.  **Validate**: Run the pre-edit validation script (`python3\n        scripts\/validate_config.py --plan changes.json`) to verify PromQL\n        grammar, lookback windows, duration rules, and ensure no duplicate\n        signals exist.\n    3.  **Execute**: After the plan passes validation, apply or merge changes\n        in-place into the target Terraform configuration (`alerts.tf`).\n    4.  *Note*: When answering questions or providing Terraform snippets\n        directly in chat where no disk modification is requested, output the\n        complete, valid Terraform HCL block in your response.\n*   **Configure the 4 Golden Signals and Cluster Health**: Always ensure the\n    target Kubernetes workload or service has the following alerting coverage:\n    1.  **Latency** (P95 response time)\n    2.  **Errors** (Multi-Window Multi-Burn-Rate SLO alerts, such as Fast Burn 1\n        hour \/ 5 minutes with factor 14.4, Slow Burn 6 hours \/ 30 minutes with\n        factor 6.0; do not use simple static ratios)\n    3.  **Traffic** (Sudden drop or complete metric disappearance using\n        `absent()` or `default 0` syntax, or overload spikes)\n    4.  **Saturation (Memory Limit Utilization Only)**: When describing or\n        configuring alert policies for a cluster or project, include ONLY\n        **Memory Saturation** (`container_memory_working_set_bytes` \/\n        `container_spec_memory_limit_bytes`). Do **NOT** include CPU saturation\n        alerts or list `container_cpu_usage_seconds_total` as an alert metric\n        because CPU is compressible and throttled by CFS quotas rather than\n        causing uncompressible fatal termination (OOM).\n    5.  **Cluster Health** (Pod CrashLooping, Node NotReady)\n*   **PromQL Only (Managed Prometheus)**: You must use\n    `condition_prometheus_query_language` with PromQL. Do **NOT** use MQL or\n    standard `condition_threshold` unless explicitly requested. Google Cloud\n    Managed Service for Prometheus is the standard telemetry ingestion path for\n    GKE.\n*   **Terraform Only**: Write the generated observability configuration ONLY as\n    Terraform (`.tf`) files, such as `alerts.tf` and `variables.tf`.\n*   **Dynamic Multi-Resource Alerting (No Hardcoding)**: You must not hardcode\n    specific pod names, node names, or service names in alerting conditions\n    unless explicitly requested. Alerting policies must be written to cover\n    resources dynamically:\n    *   Always use grouping aggregations (`by (cluster, namespace, service, pod,\n        container)`) instead of filtering to a single instance. This allows a\n        single alert policy to dynamically track each service or pod separately.\n    *   Always declare and use Terraform variables for `project_id`,\n        `cluster_name`, and `namespace` (`var.project_id`, `var.cluster_name`,\n        `var.namespace`) to make the configuration reusable across environments.\n        Always define these variables in `variables.tf` (or within the\n        configuration) and reference all three in policies or PromQL label\n        matchers.\n*   **No Redundant Duration Windows on Lookbacks**:\n    *   When PromQL expressions already use an aggregated lookback window (such\n        as `increase(...[15m]) > 3` or multi-window SLO burn rates), the query\n        time window already smooths out transient spikes.\n    *   Adding a Terraform duration on top of a PromQL lookback window increases\n        the Mean Time to Detect (MTTD) without providing additional smoothing\n        benefits.\n    *   In these cases, set Terraform `duration = \"0s\"` (or `\"60s\"`). Do not\n        enforce `duration = \"300s\"` on top of `[15m]`, which delays critical\n        crashloop alerts by up to 20 minutes total (15 minutes + 5 minutes).\n    *   Use `duration = \"300s\"` only on instantaneous gauge conditions, such as\n        `kube_node_status_condition == 0`.\n*   **Use SLO Burn Rates Instead of Simple Ratios**: For error rate alerting,\n    always generate Multi-Window Multi-Burn-Rate (MWMBR) SLO alerts (such as\n    14.4x burn rate over 1 hour and 5 minute windows for a 99% SLO) rather than\n    simple error rate ratios (`rate(5xx)\/rate(total) > 0.05`), which produce\n    excessive false alarms on low traffic.\n*   **Robust Traffic Drop Detection (`absent()` \/ `default 0`)**: When\n    monitoring for traffic drops to zero, do not use `rate(...) == 0` alone\n    because Prometheus time series disappear completely when no requests occur\n    (evaluating to an empty vector rather than 0). Use `default 0` syntax, such\n    as `sum(rate(...[5m])) default 0 == 0`, or `absent(...) == 1`.\n*   **Notification Channels**: By default, never configure any notification\n    channels without user input. If the user explicitly provides a notification\n    channel, configure the alerts to use it. Otherwise, you must prompt the user\n    in your response to ask if they would like to configure one.\n*   **Consult GKE Metrics and Open-Source Alerts Catalog**: When designing or\n    generating evaluation suites or alerting policies, consult\n    [metrics_and_alerts_catalog.md](references\/metrics_and_alerts_catalog.md)\n    for public GKE metrics (`kubernetes.io\/`) and open-source Kubernetes alerts\n    (`awesome-prometheus-alerts`).\n*   **Plain English Response**: You must include a plain English explanation for\n    what the alerts do in your response. Explain what the alert measures, what\n    the threshold represents, and what a trigger indicates.\n*   **User Labels**: Include a `user_labels` block in all\n    `google_monitoring_alert_policy` resources to track policies created by this\n    skill:\n\n    ```terraform\n    user_labels = {\n      created-with-google-skill = \"gke-alert-configuration\"\n    }\n    ```\n\n--------------------------------------------------------------------------------\n\n## Alerting Policy Structure in Terraform\n\nAlerting policies must be defined using the `google_monitoring_alert_policy`\nresource with `condition_prometheus_query_language`. Always declare variables in\n`variables.tf` for `project_id`, `cluster_name`, and `namespace`.\n\n```hcl\n# variables.tf\nvariable \"project_id\" {\n  type        = string\n  description = \"Google Cloud Project ID\"\n}\n\nvariable \"cluster_name\" {\n  type        = string\n  description = \"GKE Cluster Name\"\n}\n\nvariable \"namespace\" {\n  type        = string\n  description = \"Target Kubernetes Namespace\"\n  default     = \"default\"\n}\n\nvariable \"slo_target\" {\n  type        = number\n  description = \"SLO Target fraction (for example 0.99 for 99%)\"\n  default     = 0.99\n}\n```\n\n```hcl\n# alerts.tf\n# Example: Multi-Window Multi-Burn-Rate (MWMBR) SLO Alert (Fast Burn: 14.4x, 1h & 5m windows)\nresource \"google_monitoring_alert_policy\" \"k8s_service_error_rate_slo\" {\n  project      = var.project_id\n  display_name = \"[K8s] ${var.cluster_name} - Service Error Rate SLO Fast Burn\"\n  combiner     = \"OR\"\n\n  conditions {\n    display_name = \"Error Budget Fast Burn (14.4x over 1h and 5m)\"\n    condition_prometheus_query_language {\n      query    = <<-EOT\n        (\n          (\n            sum(\n              rate(\n                http_requests_total{\n                  cluster=\"${var.cluster_name}\",\n                  namespace=\"${var.namespace}\",\n                  status=~\"5..\"\n                }[5m]\n              )\n            ) by (service, namespace, cluster)\n            \/\n            sum(\n              rate(\n                http_requests_total{\n                  cluster=\"${var.cluster_name}\",\n                  namespace=\"${var.namespace}\"\n                }[5m]\n              )\n            ) by (service, namespace, cluster)\n          ) > (1 - ${var.slo_target}) * 14.4\n        )\n        and\n        (\n          (\n            sum(\n              rate(\n                http_requests_total{\n                  cluster=\"${var.cluster_name}\",\n                  namespace=\"${var.namespace}\",\n                  status=~\"5..\"\n                }[1h]\n              )\n            ) by (service, namespace, cluster)\n            \/\n            sum(\n              rate(\n                http_requests_total{\n                  cluster=\"${var.cluster_name}\",\n                  namespace=\"${var.namespace}\"\n                }[1h]\n              )\n            ) by (service, namespace, cluster)\n          ) > (1 - ${var.slo_target}) * 14.4\n        )\n      EOT\n      duration = \"0s\"\n    }\n  }\n}\n```\n\n--------------------------------------------------------------------------------\n\n## Telemetry Metrics and PromQL Examples\n\nFor GKE metrics (`kubernetes.io\/`), community open-source alerts\n(`awesome-prometheus-alerts`), KSM cost guardrails, and non-KSM native\nalternatives, you must read and follow:\n\n*   [metrics_and_alerts_catalog.md](references\/metrics_and_alerts_catalog.md)\n\nFor specific PromQL queries corresponding to each of the Golden Signals, you\nmust read and follow:\n\n*   [promql_queries.md](references\/promql_queries.md)\n\nFor GKE cluster prerequisites, enabling Google Cloud Managed Service for\nPrometheus collection, configuring PodMonitoring custom scraping, and enabling\ncontrol plane metrics collection (API Server, Controller Manager, Scheduler),\nyou must read and follow:\n\n*   [gke_configuration_prerequisites.md](references\/gke_configuration_prerequisites.md)\n\n--------------------------------------------------------------------------------\n\n## Tooling Scripts and Validation Loop\n\nUse the `validate_config.py` script to validate change plans and Terraform\nconfigurations when working in a repository:\n\n*   **Pre-Edit Plan Validation**: Draft a `changes.json` plan specifying the\n    proposed policies, queries, and durations, and validate it before editing:\n    *   Command: `python3 scripts\/validate_config.py --plan changes.json`\n*   **Post-Edit and Directory Validation**: Scan existing or modified Terraform\n    files in a directory to ensure no duplicates or syntax errors exist:\n    *   Command: `python3 scripts\/validate_config.py --directory [TARGET_TF_DIR]\n        --cluster-var \"${var.cluster_name}\"`\n    *   Single file validation: `python3 scripts\/validate_config.py --file\n        [PATH_TO_TF_FILE]`\n\n--------------------------------------------------------------------------------\n\n## Technical Considerations and Gotchas\n\n*   **Lookback Windows versus Duration Buffers**:\n    *   Do not add large `duration = \"300s\"` buffers to alerts that already use\n        aggregated lookback windows like `increase(...[15m])` or multi-window\n        SLO rates.\n    *   The `[15m]` window in `increase(...[15m]) > 3` already smooths spikes.\n        Adding `duration = \"300s\"` increases MTTD by forcing the restart count\n        to remain above 3 for an extra 5 continuous minutes, delaying alerts by\n        up to 20 minutes total.\n    *   Use `duration = \"0s\"` or `\"60s\"` when using lookback window functions.\n        Reserve `duration = \"300s\"` for raw instantaneous gauge conditions, such\n        as `kube_node_status_condition == 0`.\n*   **Memory Saturation Only for Cluster Alerting**:\n    *   Do not configure CPU saturation alerts for cluster or workload\n        monitoring. CPU is compressible (throttled by the CFS scheduler), while\n        memory is uncompressible (triggers OOMKills).\n    *   Configure Memory Saturation using `container_memory_working_set_bytes` \/\n        `container_spec_memory_limit_bytes`.\n*   **Missing Resource Limits Blind Spot (Mandatory Explanation)**: Saturation\n    alerts that compare usage to limits (such as\n    `container_spec_memory_limit_bytes`) will **fail to resolve** or return\n    `NaN` if workloads do not have explicit Memory limits configured in their\n    Kubernetes manifests.\n    *   **Mandatory Instruction**: Whenever you generate, discuss, or recommend\n        any memory saturation alert comparing usage against limits (including\n        non-KSM cAdvisor alternatives using\n        `container_spec_memory_limit_bytes`), you **must explicitly explain and\n        warn the user in your response** that container memory limits must be\n        explicitly configured in the Kubernetes pod specs or manifests\n        (`resources.limits.memory`) for the saturation query to resolve (and not\n        return `NaN` or fail to resolve).\n*   **Linear Disk Predictions (`predict_linear`)**: When forecasting volume\n    exhaustion using\n    `predict_linear(kubelet_volume_stats_available_bytes[6h:5m], 4 * 24 * 3600)\n    < 0`, explain that `predict_linear` uses linear regression over the recent\n    lookback window (for example, 6 hours) to project when available disk will\n    drop below 0 (for example, within 4 days). Identify\n    `kubelet_volume_stats_available_bytes` as a Tier 1 native kubelet metric\n    with zero KSM surcharge.\n*   **API Server Error and Client Metrics**:\n    *   `apiserver_request_total` and `rest_client_requests_total` are Tier 1\n        Control Plane metrics with zero KSM cost surcharge. Explain that\n        `apiserver_request_total` monitors 5xx HTTP error rates across API\n        server endpoints, while `rest_client_requests_total` monitors 4xx and\n        5xx requests sent by REST clients communicating with the API server.\n*   **Traffic Disappearance Gotcha (`absent()` \/ `default 0`)**:\n    *   When traffic drops completely to zero, Prometheus and GMP stop emitting\n        the `http_requests_total` time series.\n    *   `sum(rate(...[5m])) == 0` evaluates to an empty vector, preventing the\n        alert from triggering.\n    *   Always use `sum(rate(...[5m])) default 0 == 0` or `absent(...) == 1` to\n        reliably detect total traffic loss.\n*   **CrashLooping versus Normal Restarts**: A container restarting occasionally\n    might be normal, for example job completion or a minor rolling update. Alert\n    on **frequent** restarts (such as more than 3 restarts in 15 minutes with\n    `duration = \"0s\"`) using `kube_pod_container_status_restarts_total` rather\n    than a single restart to avoid noise.\n*   **Node Upgrades**: During GKE cluster upgrades, nodes are drained and\n    restarted, which can trigger \"Node NotReady\" alerts. Warn the user that\n    these alerts might fire during maintenance windows, or suggest configuring\n    maintenance windows if supported.\n\n--------------------------------------------------------------------------------\n\n## Additional Resources\n\n*   [Google Cloud Managed Service for Prometheus Documentation](https:\/\/docs.cloud.google.com\/stackdriver\/docs\/managed-prometheus.md.txt)\n*   [GKE Observability and Monitoring Concepts](https:\/\/docs.cloud.google.com\/kubernetes-engine\/docs\/concepts\/observability.md.txt)\n*   [Google Cloud Alerting Policies in Terraform](https:\/\/docs.cloud.google.com\/monitoring\/alerts\/terraform.md.txt)\n*   [Google Cloud Monitoring Pricing](https:\/\/cloud.google.com\/products\/observability\/pricing)\n*   [Google SRE Workbook: Alerting on SLOs](https:\/\/sre.google\/workbook\/alerting-on-slos\/)\n*   [Awesome Prometheus Alerts Repository](https:\/\/github.com\/samber\/awesome-prometheus-alerts)\n","use_cases":["Set up Multi-Window Multi-Burn-Rate (MWMBR) SLO alerts for GKE services","Monitor cluster health with Prometheus for CrashLoopBackOff and Node NotReady conditions","Track memory saturation and service traffic patterns in GKE clusters"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/google\/skills\/blob\/e3c591afe426ea585e4c21799e5199d6d47cd1be\/skills\/cloud\/gke-alert-configuration\/SKILL.md","source_commit":"e3c591afe426ea585e4c21799e5199d6d47cd1be","license":null,"version":null,"listing_approved_at":"2026-11-17","created_at":"2026-11-16T15:31:42.000000Z","updated_at":"2026-11-17T10:20:00.000000Z","seo_title":"Configure GKE Alerting Policies with Terraform","seo_description":"Configure GKE alerting policies using Terraform and PromQL to monitor service latency, error rates, and cluster health. Ideal for SLO management and infrastructure health","seo_keywords":["GKE alert configuration","Terraform alert policy","PromQL GKE monitoring","SLO alert configuration","GKE cluster health monitoring"]}}