Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install cloud-monitoring-notification-channels-configuration@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin cloud-monitoring-notification-channels-configuration v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install cloud-monitoring-notification-channels-configuration

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/cloud-monitoring-notification-channels-configuration/

Extract the ZIP to .github/skills/ in your repo. The folder name must match cloud-monitoring-notification-channels-configuration for Copilot to auto-discover it.

Skill Files (10)

SKILL.md 15.2 KB
---
name: cloud-monitoring-notification-channels-configuration
metadata:
  version: "1.0.2"
  category: CloudObservabilityAndMonitoring
description: >-
  Generates Terraform HCL configurations for Cloud Monitoring notification
  channels (`google_monitoring_notification_channel`) and adds notification
  channels to alerting policies (`google_monitoring_alert_policy`) in Google
  Cloud projects. Use when creating or configuring email, SMS, Slack, PagerDuty,
  Pub/Sub, or webhook notification channels, verifying Pub/Sub topic
  compatibility (including cross-project topics, message storage policies, and
  in-transit enforcement) and publishing permissions for the Cloud Monitoring
  Service Agent, or adding notification channels to existing alert policies.
  Don't use for authoring or editing alerting policy conditions, selecting
  metric descriptors, or writing PromQL or Monitoring Filter queries.
---

# Cloud Monitoring Notification Channels Configuration

## Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). 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-notification-channels-configuration)"`
and append `agent-skills/1.0 (skill:cloud-monitoring-notification-channels-configuration)` to `User-Agent` headers.

## Context Provided

*   **Terraform Only**: Write the generated observability configuration ONLY as
    Terraform (`.tf`) files (e.g., `notification_channels.tf`).
    -   Install Terraform **ONLY** if you are asked to deploy the channels AND
        there is no valid Terraform installation.
    -   If you are **NOT** asked to deploy the channels, **DO NOT** install
        Terraform.
*   **Working Directory Inference**: Determine the target path for `.tf` files
    using the following order:
    1.  If the user provides a path, use that exact path for the `.tf` file.
    2.  If a path is not provided, search the workspace for existing `.tf` files
        (preferring files that already define
        `google_monitoring_notification_channel` or
        `google_monitoring_alert_policy` resources, or existing directories in
        the strict preference order: `monitoring/`, then `ops/`, then `sre/`).
        If found, write `notification_channels.tf` in that directory (or update
        the existing `.tf` file when modifying an existing resource).
    3.  If a path is not provided and no `.tf` files or target directories exist
        in the workspace, create and write to
        `monitoring/notification_channels.tf`.
*   **Google Cloud Prerequisites**: When running `gcloud` CLI discovery commands
    or deploying configurations with the `terraform` CLI against a Google Cloud
    project, ensure the following prerequisites are met in order (do not execute
    these commands if the user only asks to generate or print Terraform HCL):
    1.  **Target Project ID & Project Number**:
        *   Identify the target Google Cloud `{project_id}` from the user's
            request or via `gcloud config get-value project`. If neither is
            available, prompt the user to provide `{project_id}` before
            continuing.
        *   When the Google Cloud project number (`{project_number}`) is needed
            (such as constructing the Cloud Monitoring Service Agent identity
            for Pub/Sub channels):
            *   **Method A (Standard)**: Run `gcloud projects describe
                {project_id} --format='value(projectNumber)'`.
            *   **Method B (Ask User)**: If the command fails or you cannot
                retrieve the project number, ask the user to provide it.
    2.  **Authentication**: Authenticate the `gcloud` CLI via `gcloud auth
        login` and configure Application Default Credentials (ADC) for Terraform
        via `gcloud auth application-default login`.
    3.  **Project Configuration & Billing**: Configure the target Google Cloud
        project via `gcloud config set project {project_id}` (and ensure the
        project has an active billing account attached).
        *   **Recovery Actions**: If `gcloud config set project {project_id}` or
            `gcloud projects describe {project_id}` fails, verify active
            credentials with `gcloud auth list`, list accessible projects with
            `gcloud projects list`, or prompt the user to confirm the project ID
            and access permissions. If deployment fails due to a missing or
            inactive billing account, stop deployment and instruct the user to
            link an active billing account (via `gcloud billing projects link
            {project_id} --billing-account={account_id}` or in the Google Cloud
            console) before retrying.
    4.  **IAM Permissions**: Ensure the principal has permission to manage
        notification channels—either via the predefined Monitoring
        NotificationChannel Editor role
        (`roles/monitoring.notificationChannelEditor`, plus
        `roles/monitoring.alertPolicyEditor` when adding a channel to an
        existing alert policy) **or via a custom IAM role** containing the
        equivalent permissions (`monitoring.notificationChannels.get`,
        `monitoring.notificationChannels.list`,
        `monitoring.notificationChannels.create`,
        `monitoring.notificationChannels.update`,
        `monitoring.notificationChannels.delete`, and
        `monitoring.alertPolicies.get` / `monitoring.alertPolicies.update` when
        updating an alert policy).
        *   **Recovery Actions**: Users with a custom role granting these
            permissions do not need the predefined role name. If a `gcloud` or
            `terraform` command fails with `PERMISSION_DENIED` (HTTP 403), stop
            execution, identify the missing `monitoring.notificationChannels.*`
            or `monitoring.alertPolicies.*` permission, and instruct the user to
            ask a project administrator to grant
            `roles/monitoring.notificationChannelEditor` (or a custom role with
            the required permissions) to their principal.
*   **Discovery Tips**:
    *   **Listing Notification Channels**: You MUST use `gcloud beta monitoring
        channels list --project={project_id}` to list notification channels. Do
        **NOT** use any other `gcloud` commands to list notification channels.
    *   **Verifying Pub/Sub Topics**: When configuring a Pub/Sub notification
        channel, run
        [`scripts/verify_pubsub_topic.sh`](scripts/verify_pubsub_topic.sh)
        `{monitoring_project_id} {topic_name_or_path}` to verify that:
        1.  The Pub/Sub API (`pubsub.googleapis.com`) is enabled in the topic's
            project (supporting both same-project topics and cross-project
            topics specified as
            `projects/{topic_project_id}/topics/{topic_name}`).
        2.  The topic exists and the monitoring project's Cloud Monitoring
            Service Agent
            (`service-{monitoring_project_number}@gcp-sa-monitoring-notification.iam.gserviceaccount.com`)
            holds `roles/pubsub.publisher` on the topic or topic project.
        3.  The topic does **not** define a message storage policy
            (`messageStoragePolicy` / `message_storage_policy`) and does **not**
            have in-transit enforcement (`enforceInTransit` /
            `enforce_in_transit`) enabled. **DO NOT** use a Pub/Sub topic that
            defines a message storage policy or enforces in-transit restrictions
            as a notification channel, because Cloud Monitoring cannot deliver
            messages to such topics.
*   **Attribution**: You MUST tag EVERY applicable command and Terraform
    resource below that you create, modify, or suggest to the user.

    *   **Terraform HCL (`user_labels`)**:
        *   Every `google_monitoring_notification_channel` resource that you
            create MUST include the `created-with-google-skill` label in its
            `user_labels` block:

            ```terraform
            user_labels = {
              created-with-google-skill = "cloud-monitoring-notification-channels-configuration"
            }
            ```

        *   When modifying an existing `google_monitoring_alert_policy` resource
            solely to add a notification channel, do **not** use
            `created-with-google-skill` (since this skill did not create the
            alerting policy). Instead, include the
            `added-channel-with-google-skill` label in its `user_labels` block
            (preserving any existing `user_labels` on the policy):

            ```terraform
            user_labels = {
              added-channel-with-google-skill = "cloud-monitoring-notification-channels-configuration"
            }
            ```

    *   Follow the instructions below based on the CLI tool being used:

        *   **gcloud:** Prefix every `gcloud` invocation with the metrics
            environment variables. Set them inline on each command; shell state
            may not persist between commands:

            ```bash
            CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-monitoring-notification-channels-configuration)" \
                gcloud <command> [flags]
            ```

        *   **Direct HTTP calls:** For direct HTTP calls (e.g. `curl`), you MUST
            pass the explicit `-H "User-Agent: ..."` header in the shell command
            syntax exactly like this:

            ```bash
            curl -H "User-Agent: agent-skills/1.0 (skill:cloud-monitoring-notification-channels-configuration)" ...
            ```

        *   **Terraform:** Prefix every Terraform `plan` and `apply` invocation
            with the metrics environment variables. Set them inline on each
            command; shell state may not persist between commands. For example:

            ```bash
            GOOGLE_TERRAFORM_USERAGENT_EXTENSION="agent-skills/1.0 (skill:cloud-monitoring-notification-channels-configuration)" \
                terraform plan [flags]
            ```

    *   If the skill instructions provide an additional skill script name,
        include that script name in the attribution label. Using a `gcloud`
        command inside
        [`scripts/verify_pubsub_topic.sh`](scripts/verify_pubsub_topic.sh) as an
        example:

        ```bash
        CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-monitoring-notification-channels-configuration; script:verify_pubsub_topic)" \
            gcloud <command> [flags]
        ```

*   **Execution Note (State Refresh Timeout Recovery)**: When running `terraform
    plan` or `terraform apply`, set a command timeout of **120 seconds**. If the
    command does not complete within 120 seconds (indicating Terraform is
    stalling on a full state refresh across a large state file rather than
    normal execution), cancel the command and retry **at most once** by running
    `terraform plan` and `terraform apply` with `-target` scoped to the specific
    resources being created or updated (for example,
    `-target=google_monitoring_notification_channel.<resource_name>` and, if
    updating an alert policy,
    `-target=google_monitoring_alert_policy.<policy_name>`). If the targeted
    retry also times out after 120 seconds or fails, **DO NOT** retry again;
    stop execution and report the timeout or error to the user.

## Generation

### Input Assumptions (checklist)

*   **Notification Channel Type**: When creating a new notification channel, the
    user MUST provide the notification channel type to configure.
    -   If no type is provided (and the user is not attaching an existing
        notification channel to an alert policy), you MUST prompt the user to
        ask for a type before continuing.
*   **Sensitive Credentials File**: Some notification channels require the use
    of sensitive credentials in their configuration. You MUST verify that the
    user has a `secret.tfvars` file in the working directory. If the file does
    not exist, create one using the template provided in
    [`assets/secret.tfvars`](assets/secret.tfvars) and notify the user that
    credentials should be stored there.

### Execution Steps

1.  Open the reference file corresponding to the notification channel the user
    wants to configure:

    Notification Channel Type | Reference File
    :------------------------ | :----------------------------------------
    **email**                 | [email.md](references/email.md)
    **sms**                   | [sms.md](references/sms.md)
    **slack**                 | [slack.md](references/slack.md)
    **pubsub**                | [pubsub.md](references/pubsub.md)
    **pagerduty**             | [pagerduty.md](references/pagerduty.md)
    **webhook**               | [webhook.md](references/webhook.md)

2.  Follow the guidelines in the `Prerequisites` section (if any) to complete
    all requirements for the channel configuration.

3.  If the reference file contains a `Required Credentials` section under
    `Specification`, you MUST confirm that the listed required credentials are
    configured in the `secret.tfvars` file.

    -   If any of the credentials are set to empty or not found in the file, you
        MUST prompt the user to provide them before proceeding.

4.  Use the template provided in the `Terraform HCL` section under
    `Specification` inside the reference file replacing the specified variables
    as needed to write the new configuration into the output file. If the user
    explicitly specifies a `display_name` for the notification channel, set
    `display_name` to that exact string instead of the default
    `"<Type> Notification Channel (...)"` template string.

5.  **Adding a Channel to an Existing Alert Policy**: When modifying an existing
    `google_monitoring_alert_policy` resource to use an existing
    `google_monitoring_notification_channel` resource (without creating a new
    channel), set `notification_channels` on the
    `google_monitoring_alert_policy` block and set the
    `added-channel-with-google-skill` label to
    `"cloud-monitoring-notification-channels-configuration"` in its
    `user_labels` block (preserving any existing `user_labels`):

    ```terraform
    notification_channels = [
      google_monitoring_notification_channel.<channel_resource_name>.name,
    ]
    user_labels = {
      added-channel-with-google-skill = "cloud-monitoring-notification-channels-configuration"
    }
    ```

### Outputs & Formats

Write all channel configurations into a `notification_channels.tf` file under
the directory chosen in the #context-provided section (or update the target
`.tf` file when adding notification channels to an existing
`google_monitoring_alert_policy`). Ensure every generated
`google_monitoring_notification_channel` resource sets
`created-with-google-skill` to
`"cloud-monitoring-notification-channels-configuration"` in `user_labels`, and
every modified `google_monitoring_alert_policy` resource sets
`added-channel-with-google-skill` to
`"cloud-monitoring-notification-channels-configuration"` in `user_labels`.

--------------------------------------------------------------------------------

## Supporting Links

*   [Create and manage notification channels](https://docs.cloud.google.com/monitoring/support/notification-options.md.txt)
assets/
secret.tfvars 0.2 KB
# Fill in with your Slack token.
slack_token = ""

# Fill in with your PagerDuty service key (must be 32 characters).
pagerduty_service_key = ""

# Fill in with your webhook password.
webhook_password = ""
references/
attribution.md 2.0 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand, with the metrics environment variable. Set it inline on each
    command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-monitoring-notification-channels-configuration)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage.

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
    server, include
    `agent-skills/1.0 (skill:cloud-monitoring-notification-channels-configuration)`
    in the `User-Agent` header. If a `User-Agent` header is already specified,
    append this string to the end of it rather than overwriting existing
    `User-Agent` data — the collection pipeline parses the
    `agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
    attribution:

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:cloud-monitoring-notification-channels-configuration)
    ```

-   **Constraint for Generated Code**: The tracking prefix is strictly for
    commands you execute directly in the terminal. Do NOT include this tracking
    prefix in generated scripts, Terraform templates, or code provided to the
    user for their own repositories.

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
email.md 0.9 KB
# Email Notification Channels

## Prerequisites

### Target Email Address

Email notification channels require an email address to send alert notifications
to. If it has not been provided already, you MUST prompt the user to ask which
email address you need to use to configure the notification channel.

## Specification

### Terraform HCL

```terraform
resource "google_monitoring_notification_channel" "email_notification_channel" {
  project      = {gcp_project}
  display_name = "Email Notification Channel ({target_email_address})"
  type         = "email"
  labels = {
    email_address = {target_email_address}
  }
  user_labels = {
    created-with-google-skill = "cloud-monitoring-notification-channels-configuration"
  }
}
```

Where:

*   `{gcp_project}`: The GCP project ID to deploy the notification channel to.
*   `{target_email_address}`: The target email address to send notifications to
    through the channel.
pagerduty.md 3.4 KB
# PagerDuty Notification Channels

## Prerequisites

### PagerDuty Integration / Service Key

PagerDuty notification channels require a **32-character** PagerDuty integration
key (Events API v1 service/access key) to route alert notifications to the
target PagerDuty service.

*   **Key Length Validation (32 Characters)**: The PagerDuty service/access key
    (`service_key`) **MUST** be exactly **32 characters** long. If a key
    provided directly by the user or configured in `secret.tfvars` is not
    exactly 32 characters long, you **MUST** inform the user that the PagerDuty
    access/service key must be 32 characters and prompt them to provide a valid
    32-character key before proceeding.
*   **Directly Provided Key**: If the user explicitly provides a valid
    32-character PagerDuty integration key or service key in their request, use
    that value directly for `service_key` in the `sensitive_labels` block (no
    `secret.tfvars` file is required).
*   **Credentials File (`secret.tfvars`)**: If the user does not provide the
    integration key directly (or asks to use `secret.tfvars`), configure
    `service_key = var.pagerduty_service_key` using the `pagerduty_service_key`
    credential from `secret.tfvars` (verifying that it is a 32-character key).
    If neither a valid 32-character direct key nor a valid 32-character
    `pagerduty_service_key` in `secret.tfvars` is available, you MUST prompt the
    user to provide it.

## Specification

### Required Credentials (When Not Provided Directly)

*   `pagerduty_service_key` (Must be 32 characters. ONLY required in
    `secret.tfvars` when the user has not directly provided a valid 32-character
    PagerDuty integration/service key in their request)

### Terraform HCL

#### Using a Directly Provided Integration / Service Key

```terraform
resource "google_monitoring_notification_channel" "pagerduty_notification_channel" {
  project      = {gcp_project}
  display_name = "PagerDuty Notification Channel ({target_pagerduty_service})"
  type         = "pagerduty"
  sensitive_labels {
    service_key = {target_pagerduty_service_key}
  }
  user_labels = {
    created-with-google-skill = "cloud-monitoring-notification-channels-configuration"
  }
}
```

#### Using `secret.tfvars`

```terraform
variable "pagerduty_service_key" {
  type      = string
  sensitive = true
}

resource "google_monitoring_notification_channel" "pagerduty_notification_channel" {
  project      = {gcp_project}
  display_name = "PagerDuty Notification Channel ({target_pagerduty_service})"
  type         = "pagerduty"
  sensitive_labels {
    service_key = var.pagerduty_service_key
  }
  user_labels = {
    created-with-google-skill = "cloud-monitoring-notification-channels-configuration"
  }
}
```

Where:

*   `{gcp_project}`: The GCP project ID to deploy the notification channel to.
*   `{target_pagerduty_service}`: The target PagerDuty service name (used in the
    default `display_name` when the user does not specify one). If the user
    explicitly specifies a display name (e.g., `"Tier 1: PagerDuty"`), set
    `display_name` directly to that exact string instead of wrapping it in
    `"PagerDuty Notification Channel (...)"`.
*   `{target_pagerduty_service_key}`: The 32-character PagerDuty integration key
    (service/access key) to route notifications to.

---

## Supporting Links

*   [PagerDuty Notification Channel Options](https://docs.cloud.google.com/monitoring/support/notification-options.md.txt#pagerduty)
pubsub.md 6.1 KB
# Pub/Sub Notification Channels

## Prerequisites

### Target Pub/Sub Topic

Pub/Sub notification channels require a target Pub/Sub topic to publish
notifications to. You MUST verify:

1.  Whether the user wants to use an existing topic or create a new one.
2.  Whether the topic resides in the **same project** as the notification
    channel (`{gcp_project}`) or in a **different project**
    (`{topic_project_id}`).

### Topic Compatibility Restrictions (MUST Check Before Creating Channel)

Cloud Monitoring publishes notifications from globally distributed backend
servers and cannot deliver messages to Pub/Sub topics with regional storage or
in-transit restrictions (`FAILED_PRECONDITION`).

*   **No Message Storage Policy (`message_storage_policy` /
    `messageStoragePolicy`)**: A Pub/Sub topic that defines a
    `message_storage_policy` (such as `allowed_persistence_regions` /
    `allowedPersistenceRegions`) **MUST NOT** be used as a Cloud Monitoring
    notification channel.
*   **No In-Transit Enforcement (`enforce_in_transit` / `enforceInTransit`)**: A
    Pub/Sub topic with `enforce_in_transit = true` (`enforceInTransit: true`)
    **MUST NOT** be used as a Cloud Monitoring notification channel.
*   **Required Agent Action**:
    *   If an existing Pub/Sub topic has a `message_storage_policy`
        (`allowed_persistence_regions`) or `enforce_in_transit` enabled, or if
        the user asks to configure a Pub/Sub topic or notification channel with
        a message storage policy or in-transit enforcement, **DO NOT** create or
        output the `google_monitoring_notification_channel` resource. Instead,
        stop and inform the user that Cloud Monitoring cannot deliver
        notifications to Pub/Sub topics that define a message storage policy or
        enforce in-transit restrictions.
    *   When creating a new `google_pubsub_topic` for a notification channel,
        **NEVER** include a `message_storage_policy` block.

### Permissions

The Cloud Monitoring Service Agent for the **monitoring project** (where the
notification channel is configured) requires permission to publish to the target
Pub/Sub topic:

*   Service Agent identity format:
    `service-{gcp_project_number}@gcp-sa-monitoring-notification.iam.gserviceaccount.com`
    (or `service-{gcp_project_number}@gcp-sa-monitoring.iam.gserviceaccount.com`),
    where `{gcp_project_number}` is ALWAYS the project number of the
    **monitoring project** (`{gcp_project}`), even when the topic is in a
    different project (`{topic_project_id}`).
*   It requires the **Pub/Sub Publisher** role (`roles/pubsub.publisher`) on the
    target topic in `{topic_project_id}`.

### Verification Helper

Use the helper script included in this skill to verify the status of a topic
(including cross-project topics, message storage policies, in-transit
enforcement, and IAM permissions) before generating Terraform configuration:

```bash
./scripts/verify_pubsub_topic.sh {gcp_project} {target_pubsub_topic_name_or_path}
```

Pass either a short topic name (for a topic in `{gcp_project}`) or a full topic
resource path (`projects/{topic_project_id}/topics/{topic_name}`). The script
verifies that the Pub/Sub API is enabled in the topic project, the topic exists,
no message storage policy or in-transit enforcement is configured on the topic,
and the monitoring project's Service Agent has `roles/pubsub.publisher`.

## Specification

### Terraform HCL

#### Using an existing topic (same project or cross-project)

```terraform
resource "google_monitoring_notification_channel" "pubsub_notification_channel" {
  project      = {gcp_project}
  display_name = "Pub/Sub Notification Channel ({target_pubsub_topic_id})"
  type         = "pubsub"
  enabled      = true

  labels = {
    topic = {target_pubsub_topic_id}
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-notification-channels-configuration"
  }
}
```

If the existing topic is in a **different project** (`{topic_project_id}`) and
IAM permissions must also be granted in Terraform, bind `roles/pubsub.publisher`
on the topic in `{topic_project_id}` for the monitoring project's Service Agent
(`{gcp_project_number}`):

```terraform
resource "google_pubsub_topic_iam_member" "monitoring_publisher" {
  project = {topic_project_id}
  topic   = {target_pubsub_topic_name}
  role    = "roles/pubsub.publisher"
  member  = "serviceAccount:service-{gcp_project_number}@gcp-sa-monitoring-notification.iam.gserviceaccount.com"
}
```

#### Creating a new topic and channel

```terraform
resource "google_pubsub_topic" "notification_topic" {
  project = {topic_project_id}
  name    = {target_pubsub_topic_name}
}

resource "google_pubsub_topic_iam_member" "monitoring_publisher" {
  project = {topic_project_id}
  topic   = google_pubsub_topic.notification_topic.name
  role    = "roles/pubsub.publisher"
  member  = "serviceAccount:service-{gcp_project_number}@gcp-sa-monitoring-notification.iam.gserviceaccount.com"
}

resource "google_monitoring_notification_channel" "pubsub_notification_channel" {
  project      = {gcp_project}
  display_name = "Pub/Sub Notification Channel ({target_pubsub_topic_name})"
  type         = "pubsub"
  enabled      = true

  labels = {
    topic = google_pubsub_topic.notification_topic.id
  }

  user_labels = {
    created-with-google-skill = "cloud-monitoring-notification-channels-configuration"
  }

  depends_on = [google_pubsub_topic_iam_member.monitoring_publisher]
}
```

Where:

*   `{gcp_project}`: The Google Cloud project ID where the notification channel
    is deployed.
*   `{gcp_project_number}`: The Google Cloud project number corresponding to the
    monitoring project `{gcp_project}`.
*   `{topic_project_id}`: The Google Cloud project ID where the Pub/Sub topic
    resides (defaults to `{gcp_project}` when the topic is in the same project).
*   `{target_pubsub_topic_id}`: The full resource ID of the existing topic
    (`projects/{topic_project_id}/topics/{target_pubsub_topic_name}`).
*   `{target_pubsub_topic_name}`: The short name of the Pub/Sub topic.

---

## Supporting Links

*   [Pub/Sub Notification Channel Options](https://docs.cloud.google.com/monitoring/support/notification-options.md.txt#pubsub)
slack.md 1.0 KB
# Slack Notification Channels

## Prerequisites

### Slack Channel Name

Slack notification channels require a Slack channel name to send alert
notifications. If it has not been provided already, you MUST prompt the user to
ask which channel name you need to use to configure the notification channel.

## Specification

### Required Credentials

*   `slack_token`

### Terraform HCL

```terraform
variable "slack_token" {
  type      = string
  sensitive = true
}

resource "google_monitoring_notification_channel" "slack_notification_channel" {
  project      = {gcp_project}
  display_name = "Slack Notification Channel ({target_slack_channel})"
  type         = "slack"
  labels = {
    channel_name = {target_slack_channel}
  }
  sensitive_labels {
    auth_token = var.slack_token
  }
  user_labels = {
    created-with-google-skill = "cloud-monitoring-notification-channels-configuration"
  }
}
```

Where:

*   `{gcp_project}`: The GCP project ID that owns the notification channel.
*   `{target_slack_channel}`: The provided Slack channel to send notifications.
sms.md 0.9 KB
# SMS Notification Channels

## Prerequisites

### Target Phone Number

SMS notification channels require a phone number to send alert notifications to.
If it has not been provided already, you MUST prompt the user to ask which phone
number you need to use to configure the notification channel.

## Specification

### Terraform HCL

```terraform
resource "google_monitoring_notification_channel" "sms_notification_channel" {
  project      = {gcp_project}
  display_name = "SMS Notification Channel ({target_phone_number})"
  type         = "sms"
  labels = {
    number = {target_phone_number}
  }
  user_labels = {
    created-with-google-skill = "cloud-monitoring-notification-channels-configuration"
  }
}
```

Where:

*   `{gcp_project}`: The GCP project ID to deploy the notification channel to.
*   `{target_phone_number}`: The target phone number to send notifications to
    through the channel.
webhook.md 3.8 KB
# Webhook Notification Channels

## Prerequisites

### Target Webhook Endpoint URL

Webhook notification channels require a publicly accessible endpoint URL (HTTP
or HTTPS) to send alert notifications to. If it has not been provided already,
you MUST prompt the user to ask which webhook URL you need to use to configure
the notification channel.

### Authentication (Optional)

By default, webhook notification channels use `type = "webhook_tokenauth"`,
which only requires the target `url` label (any shared secret token is passed as
a query parameter in the URL) and does not require `secret.tfvars`.

Only use `type = "webhook_basicauth"` if the user explicitly requests HTTP Basic
Authentication (username and password).

*   **Directly Provided Password**: If the user explicitly provides the basic
    authentication password in their request, set `password` directly in the
    `sensitive_labels` block (no `secret.tfvars` file is required).
*   **Credentials File (`secret.tfvars`)**: If the user does not provide the
    password directly (or asks to use `secret.tfvars`), configure
    `password = var.webhook_password` using the `webhook_password` credential
    from `secret.tfvars` and declare the corresponding `variable
    "webhook_password"` block in the Terraform configuration.

## Specification

### Required Credentials (Basic Authentication via `secret.tfvars` Only)

*   `webhook_password` (ONLY required in `secret.tfvars` when configuring HTTP
    Basic Authentication with `type = "webhook_basicauth"` and the password is
    not provided directly in the user's request; not required for standard
    `type = "webhook_tokenauth"` webhooks)

### Terraform HCL

#### Standard / Token Authentication Webhook (Default)

```terraform
resource "google_monitoring_notification_channel" "webhook_notification_channel" {
  project      = {gcp_project}
  display_name = "Webhook Notification Channel ({target_webhook_url})"
  type         = "webhook_tokenauth"
  labels = {
    url = {target_webhook_url}
  }
  user_labels = {
    created-with-google-skill = "cloud-monitoring-notification-channels-configuration"
  }
}
```

#### HTTP Basic Authentication Webhook (Directly Provided Password)

```terraform
resource "google_monitoring_notification_channel" "webhook_notification_channel" {
  project      = {gcp_project}
  display_name = "Webhook Notification Channel ({target_webhook_url})"
  type         = "webhook_basicauth"
  labels = {
    url      = {target_webhook_url}
    username = {webhook_username}
  }
  sensitive_labels {
    password = {webhook_password}
  }
  user_labels = {
    created-with-google-skill = "cloud-monitoring-notification-channels-configuration"
  }
}
```

#### HTTP Basic Authentication Webhook (Using `secret.tfvars`)

```terraform
variable "webhook_password" {
  type      = string
  sensitive = true
}

resource "google_monitoring_notification_channel" "webhook_notification_channel" {
  project      = {gcp_project}
  display_name = "Webhook Notification Channel ({target_webhook_url})"
  type         = "webhook_basicauth"
  labels = {
    url      = {target_webhook_url}
    username = {webhook_username}
  }
  sensitive_labels {
    password = var.webhook_password
  }
  user_labels = {
    created-with-google-skill = "cloud-monitoring-notification-channels-configuration"
  }
}
```

Where:

*   `{gcp_project}`: The GCP project ID to deploy the notification channel to.
*   `{target_webhook_url}`: The target public webhook URL to send notifications
    to through the channel.
*   `{webhook_username}`: The basic authentication username (only when using
    `webhook_basicauth`).
*   `{webhook_password}`: The basic authentication password when directly
    provided by the user (only when using `webhook_basicauth`).

---

## Supporting Links

*   [Webhook Notification Channel Options](https://docs.cloud.google.com/monitoring/support/notification-options.md.txt#webhooks)
scripts/
verify_pubsub_topic.sh 8.8 KB
#!/bin/bash

# Script to verify if a Pub/Sub topic is fully set up for Cloud Monitoring Notification Channels.

set -euo pipefail

# Allow overriding gcloud for testing
: "${GCLOUD:=gcloud}"

export CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-monitoring-notification-channels-configuration; script:verify_pubsub_topic)"

# Function to show help
show_help() {
    echo "Usage: $0 <monitoring_project_id> <topic_name_or_path>"
    echo ""
    echo "Arguments:"
    echo "  monitoring_project_id: The ID of the GCP project where the Notification Channel is being configured."
    echo "                         This project's number determines the service account name."
    echo "  topic_name_or_path:   The name of the Pub/Sub topic (assumes same project as monitoring_project_id)"
    echo "                         OR the full resource path (e.g., projects/another-project/topics/another-topic)."
    echo ""
    echo "Options:"
    echo "  -h, --help            Show this help message and exit."
}

# Function to get project number
get_project_number() {
    local project_id=$1
    local project_number
    project_number=$("$GCLOUD" projects describe "$project_id" --format="value(projectNumber)" || true)
    echo "$project_number"
}

# Function to check API enablement
check_api_enabled() {
    local project_id=$1
    local api_name=$2
    local enabled
    # We use --project to ensure we check the target project
    enabled=$("$GCLOUD" services list --enabled --project="$project_id" --filter="config.name=$api_name" --format="value(config.name)" || true)
    if [[ "$enabled" == *"$api_name" ]]; then
        echo "true"
    else
        echo "false"
    fi
}

# Function to check topic existence
check_topic_existence() {
    local project_id=$1
    local topic_name=$2
    if "$GCLOUD" pubsub topics describe "projects/$project_id/topics/$topic_name" > /dev/null 2>&1; then
        echo "true"
    else
        echo "false"
    fi
}

# Function to check if topic defines a messageStoragePolicy or enforceInTransit
check_topic_storage_policy() {
    local project_id=$1
    local topic_name=$2
    local describe_output
    describe_output=$("$GCLOUD" pubsub topics describe "projects/$project_id/topics/$topic_name" 2>/dev/null || true)

    local has_storage_policy="false"
    local enforce_in_transit="false"

    if echo "$describe_output" | grep -qE 'messageStoragePolicy|allowedPersistenceRegions'; then
        has_storage_policy="true"
    fi
    if echo "$describe_output" | grep -qE 'enforceInTransit:[[:space:]]*true'; then
        enforce_in_transit="true"
        has_storage_policy="true"
    fi

    echo "${has_storage_policy}:${enforce_in_transit}"
}

# Function to check permissions on topic
check_topic_permissions() {
    local project_id=$1
    local topic_name=$2
    local service_account=$3
    local service_account_alt=$4
    local topic_role
    topic_role=$("$GCLOUD" pubsub topics get-iam-policy "projects/$project_id/topics/$topic_name" \
        --flatten="bindings[].members" \
        --format="value(bindings.role)" \
        --filter="bindings.members:($service_account, $service_account_alt) AND bindings.role=roles/pubsub.publisher" || true)

    if [[ -n "$topic_role" ]]; then
        echo "true"
    else
        echo "false"
    fi
}

# Function to check permissions on project
check_project_permissions() {
    local project_id=$1
    local service_account=$2
    local service_account_alt=$3
    local project_role
    project_role=$("$GCLOUD" projects get-iam-policy "$project_id" \
        --flatten="bindings[].members" \
        --format="value(bindings.role)" \
        --filter="bindings.members:($service_account, $service_account_alt) AND bindings.role=roles/pubsub.publisher" || true)

    if [[ -n "$project_role" ]]; then
        echo "true"
    else
        echo "false"
    fi
}

main() {
    if [[ "${1:-}" == "-h" ]] || [[ "${1:-}" == "--help" ]]; then
        show_help
        exit 0
    fi

    if [[ "$#" -ne 2 ]]; then
        show_help >&2
        exit 1
    fi

    local monitoring_project_id=$1
    local topic_arg=$2

    # Parse topic argument
    local topic_project_id="$monitoring_project_id"
    local topic_short_name="$topic_arg"

    if [[ "$topic_arg" =~ ^projects/([^/]+)/topics/(.+) ]]; then
        topic_project_id="${BASH_REMATCH[1]}"
        topic_short_name="${BASH_REMATCH[2]}"
        echo "Detected full topic path. Topic Project: $topic_project_id, Topic Name: $topic_short_name" >&2
    fi

    echo "Checking status for Monitoring Project: $monitoring_project_id" >&2
    echo "Target Topic: projects/$topic_project_id/topics/$topic_short_name" >&2

    # 1. Get Monitoring Project Number (needed for Service Account)
    local monitoring_project_number
    monitoring_project_number=$(get_project_number "$monitoring_project_id")
    if [[ -z "$monitoring_project_number" ]]; then
        echo "Error: Could not retrieve project number for monitoring project $monitoring_project_id. Verify project ID and permissions." >&2
        exit 1
    fi
    echo "Monitoring Project Number: $monitoring_project_number" >&2

    local service_account="service-$monitoring_project_number@gcp-sa-monitoring-notification.iam.gserviceaccount.com"
    local service_account_alt="service-$monitoring_project_number@gcp-sa-monitoring.iam.gserviceaccount.com"

    # 2. Check API Enablement in Topic Project
    echo "Checking Pub/Sub API enablement in $topic_project_id..." >&2
    local api_enabled
    api_enabled=$(check_api_enabled "$topic_project_id" "pubsub.googleapis.com")
    if [[ "$api_enabled" == "true" ]]; then
        echo "  [OK] Pub/Sub API is enabled." >&2
    else
        echo "  [WARNING] Pub/Sub API (pubsub.googleapis.com) does not appear to be enabled in $topic_project_id." >&2
    fi

    # 3. Check Topic Existence & Storage Policy Restrictions
    echo "Checking topic existence..." >&2
    local topic_exists
    topic_exists=$(check_topic_existence "$topic_project_id" "$topic_short_name")
    local has_message_storage_policy="false"
    local enforce_in_transit="false"
    if [[ "$topic_exists" == "true" ]]; then
        echo "  [OK] Topic exists." >&2
        echo "Checking topic message storage policy and in-transit enforcement..." >&2
        local policy_status
        policy_status=$(check_topic_storage_policy "$topic_project_id" "$topic_short_name")
        has_message_storage_policy="${policy_status%%:*}"
        enforce_in_transit="${policy_status##*:}"
        if [[ "$enforce_in_transit" == "true" ]]; then
            echo "  [ERROR] Topic has enforceInTransit enabled. Cloud Monitoring cannot deliver notifications to topics with in-transit enforcement." >&2
        elif [[ "$has_message_storage_policy" == "true" ]]; then
            echo "  [ERROR] Topic defines a messageStoragePolicy. Cloud Monitoring cannot deliver notifications to topics with a message storage policy." >&2
        else
            echo "  [OK] Topic has no unsupported message storage policy or in-transit enforcement." >&2
        fi
    else
        echo "  [WARNING] Topic does not exist or you don't have permission to view it." >&2
    fi

    # 4. Check Permissions
    echo "Checking permissions..." >&2
    local can_publish=false
    local permission_level="none"

    if [[ "$topic_exists" == "true" ]]; then
        echo "  Checking topic-level IAM policy on projects/$topic_project_id/topics/$topic_short_name..." >&2
        if [[ $(check_topic_permissions "$topic_project_id" "$topic_short_name" "$service_account" "$service_account_alt") == "true" ]]; then
            echo "    [OK] Service account has publisher permissions on the topic." >&2
            can_publish=true
            permission_level="topic"
        fi
    fi

    if [[ "$can_publish" == "false" ]]; then
        echo "  Checking project-level IAM policy on $topic_project_id..." >&2
        if [[ $(check_project_permissions "$topic_project_id" "$service_account" "$service_account_alt") == "true" ]]; then
            echo "    [OK] Service account has publisher permissions at the project level." >&2
            can_publish=true
            permission_level="project"
        fi
    fi

    if [[ "$can_publish" == "false" ]]; then
        echo "  [WARNING] No Pub/Sub Publisher role found for Monitoring Service Agent ($service_account) in target project." >&2
    fi

    echo "----------------------------------------" >&2
    echo "Summary:" >&2
    echo "TOPIC_EXISTS=$topic_exists"
    echo "HAS_MESSAGE_STORAGE_POLICY=$has_message_storage_policy"
    echo "ENFORCE_IN_TRANSIT=$enforce_in_transit"
    echo "CAN_PUBLISH=$can_publish"
    echo "PERMISSION_LEVEL=$permission_level"

    # Return 0 if fully set up and compatible, 1 otherwise
    if [[ "$topic_exists" == "true" ]] && [[ "$can_publish" == "true" ]] && [[ "$has_message_storage_policy" == "false" ]] && [[ "$enforce_in_transit" == "false" ]]; then
        exit 0
    else
        exit 1
    fi
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE