Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install cloud-network-insights@skills-hub

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

Install with the gh extension
gh skills-hub install cloud-network-insights

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

Download and extract to your repository:

.github/skills/cloud-network-insights/

Extract the ZIP to .github/skills/ in your repo. The folder name must match cloud-network-insights for Copilot to auto-discover it.

Skill Files (5)

SKILL.md 27.8 KB
---
name: cloud-network-insights
metadata:
  category: Networking
  version: "2.0.0"
description: >-
  Guides and automates setup, onboarding, synthetic monitoring operations, and
  cleanup for Cloud Network Insights in Google Cloud and Broadcom AppNeta. Use
  when enabling Cloud Network Insights, deploying or troubleshooting Monitoring
  Points across cloud and on-premises environments, configuring Network or Web
  monitoring policies and AppNeta alarm rules, configuring alert policies,
  querying path alarms and performance metrics, verifying synthetic path
  reachability, removing specific or all Monitoring Points, monitoring
  policies, and their hosts, or turning Cloud Network Insights off (only after
  warning the user and getting an explicit yes). Don't use for generic network
  observability, VPC Flow Logs, Cloud NAT, or VPC firewall debugging.
---

# Cloud Network Insights

## Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).

## Task Router

Cloud Network Insights runs synthetic network and web tests from Monitoring
Points (MPs) that report to Broadcom AppNeta. Find the user's task, run its
check-first command, and follow only the linked steps.

| Task | Check first | Steps |
| :--- | :--- | :--- |
| Enable Cloud Network Insights or check its status | `providers list` | [1. Enable](#1-enable-cloud-network-insights) |
| Deploy a container (c50) MP or the Compute Engine appliance | `monitoring-points list` | [2. Deploy](#2-deploy-monitoring-points) |
| Deploy an MP on Kubernetes, AWS, Azure, VMware, or KVM | `monitoring-points list` | [Platform Summary](references/monitoring-point-deployment.md#2-platform-summary) |
| Create Network or Web monitoring policies | AppNeta reachability probe | [3. Policies](#3-monitoring-policies-and-alarm-rules) |
| Verify Monitoring Points and paths | `monitoring-points list` | [4. Verify](#4-verify-monitoring-points-and-paths) |
| Remove specific policies or Monitoring Points, or everything you set up | `monitoring-points list`; list and confirm first (Rule 4) | [5. Clean Up](#5-clean-up) |
| Turn Cloud Network Insights off | `providers list`; warn and ask first (Rule 4) | [Turning Off](#turning-cloud-network-insights-off) |
| Alert policies, alarm logs, and path metrics | `gcloud monitoring policies list` | [6. Alerts](#6-alert-policies-cloud-logging-and-cloud-monitoring-metrics) |
| Troubleshoot a Monitoring Point | `monitoring-points describe` | [7. Troubleshoot](#7-troubleshoot-monitoring-points) |

Check-first commands (`PROVIDER_ID` is `external` when Cloud Network Insights
was enabled in the Google Cloud console):

```bash
gcloud network-management network-monitoring-providers list --location=global --project=PROJECT_ID
gcloud network-management network-monitoring-providers monitoring-points list \
  --network-monitoring-provider=PROVIDER_ID --location=global --project=PROJECT_ID
```

## Rules

1.  **Confirm the project** and pass `--project=PROJECT_ID` to every command.
    Without a user preference, use region `us-central1` and zone
    `us-central1-a` (others:
    [Google Cloud locations](https://cloud.google.com/about/locations)).
2.  **Automate first.** Run `gcloud`, `curl`, and `ssh` yourself whenever your
    environment and the user allow them, and prefer them to console pages.
    Hand a step to the user only when it needs a browser you don't have (the
    Broadcom terms in the Google Cloud console, the AppNeta web UI) or an
    endpoint is unreachable from your environment; give the exact URL, clicks
    or commands, and success signal. Start independent long-running work
    (such as VM creation) first, and put every question and console step you
    need (names, approvals, terms) in one message.
3.  **Accept third-party terms only with the user's consent.** The first time
    Cloud Network Insights is turned on in a project, someone must accept the
    Broadcom End User Agreement in the Google Cloud console. Deploying the
    Compute Engine appliance with `gcloud` (the default) or Terraform has no
    terms step; only the Google Cloud Marketplace page shows its listing's
    terms, so use it only when the user asks for Marketplace. Unless the
    user's message explicitly pre-approved accepting all Terms of Service
    (general task instructions and CLI auto-approve flags don't count), stop
    before accepting any terms and ask: without a browser tool, give the
    console URL and clicks for the user to accept; with one, summarize the
    main points of the terms shown in the console, say that the full text
    there is what applies, and accept only after an explicit yes. Why:
    accepting terms binds the user to a legal agreement.
4.  **Delete only after an explicit yes.** Before deleting VMs, deployments,
    firewall rules, policies, or Monitoring Point records, list exactly what
    you'll delete (each name with its ID, zone, or AppNeta organization), say
    it's permanent, and wait for a yes. Skip the question only if the user
    already confirmed that list or explicitly said to delete those items
    without asking (a general "work end to end" doesn't count). Then delete
    exactly those items, each by name or ID, never by looping over search
    results. Turning Cloud Network Insights off is irreversible: it deletes
    the project's AppNeta organization and every Monitoring Point record,
    policy, path, alert policy, and their history, but not the Monitoring
    Point VMs or containers; give these warnings and the console steps first
    ([Turning Off](#turning-cloud-network-insights-off)). Never disable
    `networkmanagement.googleapis.com`: Connectivity Tests and other Network
    Intelligence Center features use it. Why: `--quiet` skips gcloud's own
    delete prompt, and an AppNeta deletion also erases its paths' history.
5.  **Keep secrets private.** Run `mktemp -d` once and use the printed path as
    `WORK_DIR` for install bundles, `mp-config` files, and tokens. Never print,
    echo, or paste tokens, device keys, bundles, or `mp-config` contents, not
    even a few lines with `head`. Monitoring Point VMs hold their device key or
    bundle in instance metadata, so describe them only with a `--format` that
    leaves out `metadata`, such as `--format="value(name,status)"`. Never use
    `curl -v`, `--verbose`, or `--trace` on AppNeta calls (they print the
    token), and run `gcloud auth print-access-token` (or its
    `application-default` form) and `generate-provider-access-token` only
    inside `$(...)`, piped, or redirected to a file, as this skill shows.
6.  **Call AppNeta directly first.** Run AppNeta API calls from your own
    environment. Only if AppNeta is unreachable from there, give the user
    their choices in one message: the AppNeta web UI steps, the filled-in
    policy script to run themselves, or a small proxy VM that you create in
    the project to run the calls from. Create the proxy VM only if the user
    picks it, send the token to it only on standard input, and ask in your
    final summary whether to delete the VM or keep it. Why: the token acts as
    the user, and anyone who can read a VM can read its metadata and disk.
7.  **Ask before** creating billable VMs or clusters, changing packages on an
    existing host, or opening inbound firewall rules (single-ended tests need
    none; never `0.0.0.0/0` or TCP 22 without explicit approval). Never create
    service accounts, impersonate accounts, change IAM, or run `gcloud auth
    login` yourself; if a permission is missing, name the role the user needs.
8.  **Report only what you verified.** Every state you report (`ACTIVE`,
    `ONLINE`, `OFFLINE`, created, deleted) must come from a command you ran in
    this session.

## Prerequisites

-   **gcloud CLI**: If `gcloud` is missing, point the user to
    [Install the gcloud CLI](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)
    instead of installing it yourself, and give console steps until it's
    installed. The AppNeta API scripts also need `curl` and `jq`.
-   **Authentication and Billing**: On authentication errors, ask the user to
    run `gcloud auth login`, or `gcloud auth application-default login` where
    a command falls back to Application Default Credentials. The project needs
    an active billing account; see
    [Network Intelligence Center pricing](https://cloud.google.com/products/network-intelligence-center/pricing).
-   **IAM Roles**: First enablement (accepting the Broadcom terms) needs
    `roles/networkmanagement.CloudNetworkInsightsAdmin` plus
    `roles/serviceusage.serviceUsageAdmin`; managing providers, bundles, and
    policies needs `roles/networkmanagement.CloudNetworkInsightsEditor`;
    read-only queries need `roles/networkmanagement.CloudNetworkInsightsViewer`.
    Monitoring Point VMs also need Compute Engine roles:
    `roles/compute.instanceAdmin.v1` for the default `gcloud` path (others:
    [Compute Engine Appliance](references/monitoring-point-deployment.md#4-compute-engine-appliance)),
    and a proxy VM's firewall rule needs `roles/compute.securityAdmin`.

## 1. Enable Cloud Network Insights

1.  Enable the API. It's idempotent, so run it even if it may be enabled:

    ```bash
    gcloud services enable networkmanagement.googleapis.com --project=PROJECT_ID
    ```

    If it fails because the Google Cloud Terms of Service aren't accepted, ask
    the user to sign in to the Google Cloud console once and accept them.
2.  Run the `providers list` check-first command. If a provider is listed,
    note its ID as `PROVIDER_ID` and go to step 5.
3.  If none is listed, try to create it. This works only if the Broadcom
    terms were accepted in this project before (for example, before someone
    turned Cloud Network Insights off), and then `PROVIDER_ID` is `external`:

    ```bash
    gcloud network-management network-monitoring-providers create external \
      --provider-type=EXTERNAL --location=global --project=PROJECT_ID
    ```

    If it fails with `Terms of Service not accepted` (code 9), go to step 4.
4.  The Broadcom End User Agreement must be accepted in the console, which
    `gcloud` can't do (Rule 3). Without a browser tool, ask the user to open
    `https://console.cloud.google.com/net-intelligence/cloud-network-insights/onboarding?project=PROJECT_ID`,
    click **Enable**, check the Broadcom agreement, click **Accept**, and
    reply when the page says it's enabled, even if they told you to accept
    all terms. With a browser tool, open that page, summarize the agreement's
    main points, say that the console's full text is what applies, and click
    **Accept** only after an explicit yes (or at once if the user told you in
    advance to accept all terms). Accepting creates the provider `external`,
    so don't run `create` afterwards; say that you'll then confirm it in
    `providers list` and wait for `ACTIVE` (step 5).
5.  Poll every 15 seconds until the state is `ACTIVE`, usually 30-60 seconds
    after the terms are accepted (`ACTIVATING` means AppNeta is provisioning).
    `providerUri` is the AppNeta host (`APPNETA_HOST`):

    ```bash
    gcloud network-management network-monitoring-providers describe PROVIDER_ID \
      --location=global --project=PROJECT_ID --format="value(state,providerUri)"
    ```

## 2. Deploy Monitoring Points

There are 7 deployment types: `container` (c50), `helm`, `gce-vm` (Compute
Engine appliance), `aws-ec2`, `azure-vm`, `vmware`, and `kvm`. Never assume a
type: each one installs differently and measures from a different place, so
ask which environment the user wants to measure from. The VM or host name
becomes the Monitoring Point name (`HOSTNAME`).

1.  Create `WORK_DIR` if needed and run the `monitoring-points list`
    check-first command. If `HOSTNAME` is already listed, even as `OFFLINE`,
    pick an unused name (ask first if the user chose it).
2.  Follow the matching path in the
    [Monitoring Point Deployment Reference](references/monitoring-point-deployment.md):

    | Situation | Path |
    | :--- | :--- |
    | Container MP on a new Compute Engine VM (default on Google Cloud; no SSH needed) | [Path B: startup script](references/monitoring-point-deployment.md#path-b-new-compute-engine-vm-no-ssh) |
    | Container MP on an existing Linux host that you can log in to | [Path A: existing host](references/monitoring-point-deployment.md#path-a-existing-host) |
    | Compute Engine appliance | [Step 1: `gcloud`](references/monitoring-point-deployment.md#step-1-gcloud); Terraform or Google Cloud Marketplace only if the user asks |
    | Kubernetes, AWS, Azure, VMware, or KVM | [Platform Summary](references/monitoring-point-deployment.md#2-platform-summary) |

    Deploy the Compute Engine appliance yourself with `gcloud`. Don't ask the
    user to open Google Cloud Marketplace or to accept its terms: this path
    has no terms step. Use the Marketplace page only when the user asks for it
    ([Step 3](references/monitoring-point-deployment.md#step-3-google-cloud-marketplace)).
3.  Wait for `connectionStatus: ONLINE` with the polling loop below:

    | After | Poll every | Usually `ONLINE` |
    | :--- | :--- | :--- |
    | Container `setup.sh install` on a host | 10 seconds | Within 30 seconds |
    | Container VM created with the startup script | 30 seconds | About 2-3 minutes |
    | Appliance VM created | 30 seconds | About 3 minutes |

### Wait for a Monitoring Point State

Run each wait as this one blocking command. It prints the list every 30
seconds and stops when `HOSTNAME` shows `STATE` (`ONLINE` after a deployment,
`OFFLINE` after a host deletion), for at most 10 minutes. For several
Monitoring Points, chain one `echo "$s" | grep -q ...` test per `HOSTNAME` with
`&&` before `break`. Don't run separate `sleep` commands or check a background
task's status while it runs; if your tool backgrounds it, wait for its
completion message.

```bash
for i in $(seq 1 20); do
  s=$(gcloud network-management network-monitoring-providers monitoring-points list \
    --network-monitoring-provider=PROVIDER_ID --location=global --project=PROJECT_ID \
    --format="value(displayName,connectionStatus)")
  echo "$s"
  echo "$s" | grep -q "^HOSTNAME[[:space:]]*STATE$" && break
  sleep 30
done
```

## 3. Monitoring Policies and Alarm Rules

Monitoring policies (`/api/v4/monitoringPolicy`, AppNeta REST API v4) define
the tests: **Network** policies measure loss, latency, and jitter to an IP or
host over TCP or UDP; **Web** policies run HTTP/HTTPS checks such as a `GET`
with a `200` assertion. Alarm rules exist only in the AppNeta web UI
(**Alarms** > **Alarm Rules**; see
[Broadcom Alarm Rules](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/alarms-set-up/alarms-rules.html)),
not the REST API v4.

1.  Probe the AppNeta API once from your environment, with a short timeout
    (`APPNETA_HOST` is the `providerUri` from [1. Enable](#1-enable-cloud-network-insights),
    step 5):

    ```bash
    curl -sS -o /dev/null -w '%{http_code}\n' --connect-timeout 10 --max-time 15 \
      "https://APPNETA_HOST/api/v4/organization"
    ```

    -   **Any HTTP code** (`401` is normal here): AppNeta is reachable. Run the
        [policy script](references/monitoring-policies.md#5-policy-script)
        yourself.
    -   **`000`, curl exit code 6, 7, or 28**: AppNeta is unreachable from your
        environment. Don't retry. Fill in the script (step 2) and give the
        user three choices in one message (Rule 6): (a) create the policies in
        the AppNeta web UI with the
        [UI steps](references/monitoring-policies.md#appneta-web-ui), filled
        in; (b) run the complete filled-in script, pasted as a Markdown code
        block (it holds no tokens or keys; never just a path to a file in your
        environment), from a machine with `gcloud`, `curl`, `jq`, and HTTPS
        access to `APPNETA_HOST`; or (c) let you create a small proxy VM in the
        project and run the script from it
        ([Proxy VM](references/monitoring-policies.md#proxy-vm)). Then
        continue with the rest of the task.
2.  Fill in the script with one `create_policy NAME TARGET MP_NAME network|web`
    line per policy. It picks this project's organization by name, skips names
    that already exist there, and scopes each policy to one Monitoring Point.
    For custom payloads, use the
    [step-by-step calls](references/monitoring-policies.md#1-set-up-appneta-api-access).
3.  On `HTTP 401`, rerun the script once; it mints a fresh token (tokens last
    about one hour). If `401` persists, stop and give the user the options:
    `gcloud auth application-default print-access-token` as the Google Cloud
    token (certificate-bound user tokens exchange into AppNeta tokens that get
    `401`), signing in again with `gcloud auth login`, or a token from a
    service account that has
    `roles/networkmanagement.CloudNetworkInsightsEditor`. Never create service
    accounts, impersonate, or change IAM yourself.
4.  Confirm the new paths with `network-paths list` and `web-paths list`
    ([4. Verify](#4-verify-monitoring-points-and-paths)).

## 4. Verify Monitoring Points and Paths

1.  **Monitoring Points**: `connectionStatus` must be `ONLINE`.
2.  **Network and Web Paths**:

    ```bash
    gcloud network-management network-monitoring-providers network-paths list \
      --network-monitoring-provider=PROVIDER_ID --location=global --project=PROJECT_ID --format=json
    gcloud network-management network-monitoring-providers web-paths list \
      --network-monitoring-provider=PROVIDER_ID --location=global --project=PROJECT_ID --format=json
    ```

3.  **Filter by Monitoring Point**: Add
    `--filter="sourceMonitoringPointId=MONITORING_POINT_ID"` (the last segment
    of the Monitoring Point's `name` in `monitoring-points list`).
4.  **Expected Extra Paths**: Each Web policy also creates a companion
    `NetworkPath` to the target host (unless one already exists), and a newly
    deployed Monitoring Point inherits paths from existing policies whose
    `monitoringPointRules` match it.

## 5. Clean Up

Match the scope to the request, and touch nothing that this setup didn't
create:

| Request | Do |
| :--- | :--- |
| Delete specific policies or Monitoring Points | [Targeted Cleanup](#targeted-cleanup) only |
| Remove everything you set up, keep Cloud Network Insights on | [Full Cleanup](#full-cleanup) |
| Turn Cloud Network Insights off | [Turning Off](#turning-cloud-network-insights-off), with no per-resource cleanup first |

### Targeted Cleanup

Inventory only the named items (Full Cleanup, step 1), confirm them (step 2),
and then:

-   **A monitoring policy**: delete it by ID (step 3), then confirm that its
    paths are gone with `network-paths list` and `web-paths list`.
-   **A Monitoring Point**: delete only its host (step 4), wait until it's
    `OFFLINE` (step 5), and delete its record (step 6). Its paths go with the
    record; policies stay unless the user asks you to delete them.

### Full Cleanup

Cloud Network Insights stays enabled. Follow this order; each step depends on
the previous one.

1.  **Inventory** before deleting anything: run `monitoring-points list`,
    `network-paths list`, `web-paths list`, `gcloud compute instances list`,
    `gcloud compute firewall-rules list`, and, if anything came from Google
    Cloud Marketplace, `gcloud infra-manager deployments list
    --location=REGION` (all with `--project=PROJECT_ID`). Then run the AppNeta
    probe ([3. Policies](#3-monitoring-policies-and-alarm-rules), step 1); if
    AppNeta is reachable, look up the IDs of this organization's policies and
    Monitoring Point records
    ([Delete by ID](references/monitoring-policies.md#4-delete-policies-and-monitoring-point-records)).
2.  **Confirm** (Rule 4): reply with what you'll delete: the policies (name
    and ID), hosts (VMs with their zone, deployments, firewall rules), and
    Monitoring Point records (name and ID), and wait for a yes. Leave out
    anything this setup didn't create, or ask about it.
3.  **Delete the monitoring policies** you listed, one `DELETE` call per ID
    ([Delete by ID](references/monitoring-policies.md#4-delete-policies-and-monitoring-point-records));
    `404` means already deleted. If AppNeta is unreachable, give the user the
    AppNeta web UI steps in the reply template below instead.
4.  **Delete the Monitoring Point hosts** you listed. Delete a Marketplace
    deployment with `gcloud infra-manager deployments delete DEPLOYMENT
    --location=REGION --project=PROJECT_ID --quiet` (it also removes its VM
    and firewall rules), and other VMs as shown below; for Terraform, Helm,
    and hosts that stay, see
    [Host Cleanup](references/monitoring-point-deployment.md#6-host-cleanup):

    ```bash
    gcloud compute instances delete HOSTNAME_1 HOSTNAME_2 --zone=ZONE --project=PROJECT_ID --quiet
    ```

5.  **Wait for `OFFLINE`**: Monitoring Points turn `OFFLINE` about 4-5 minutes
    after their host is deleted. Poll every 30 seconds with
    [the polling loop](#wait-for-a-monitoring-point-state) (`STATE` =
    `OFFLINE`). If one is still `ONLINE` after 8 minutes, tell the user it will
    turn `OFFLINE` shortly, and continue.
6.  **Delete the Monitoring Point records** you listed, one `DELETE` call per
    ID, with the AppNeta API (`gcloud` and the Google Cloud console can't
    delete them), each only once it's `OFFLINE`; keep one that isn't
    `OFFLINE` yet and delete it later. `404` means already deleted. On `401`,
    mint a new token once; on `403`, name the role the user needs (Rule 7).
    If AppNeta is unreachable, give the user the AppNeta web UI steps in the
    reply template below instead (get `PROJECT_NUMBER` with `gcloud projects
    describe PROJECT_ID --format="value(projectNumber)"`).
7.  **Verify and report**: Re-run `monitoring-points list` and `instances
    list`, then reply with this template, filled in, in this order:

```markdown
1. Monitoring policies: deleted NAME (ID), ... in AppNeta organization ORG_ID.
   [If AppNeta was unreachable instead: open
   https://APPNETA_HOST/pvc/monitoringPolicies.html?project=PROJECT_NUMBER and
   delete NAME_1 and NAME_2 there.]
2. Hosts: deleted VM_NAMES / DEPLOYMENT / FIREWALL_RULES.
3. Monitoring Point records: deleted HOSTNAME_1 (ID), ... with the AppNeta API
   [; kept HOSTNAME (not OFFLINE yet)].
   [If AppNeta was unreachable instead: open
   https://APPNETA_HOST/pvc/monitoringPoints.html?project=PROJECT_NUMBER, open
   the menu next to each OFFLINE Monitoring Point (HOSTNAME_1, HOSTNAME_2),
   click Delete, and confirm.] Check that they're gone with:
   gcloud network-management network-monitoring-providers monitoring-points list --network-monitoring-provider=PROVIDER_ID --location=global --project=PROJECT_ID
4. Cloud Network Insights is still enabled. Turning it off is irreversible (it
   deletes the AppNeta organization and every Monitoring Point record, policy,
   path, alert policy, and their history). I can do it after you confirm, or
   you can: in the Google Cloud console, open Network Intelligence Center >
   Cloud Network Insights > Settings, click Disable product, type disable, and
   click Confirm.
```

### Turning Cloud Network Insights Off

Turning it off deletes every policy, path, and Monitoring Point record by
itself, so don't delete policies, wait for `OFFLINE`, or delete records first.

1.  Unless the user's request already acknowledged these points, reply with
    them and wait for an explicit yes (Rule 4):
    -   It's irreversible. It deprovisions the project's AppNeta organization
        and deletes every Monitoring Point record, network path, web path,
        monitoring policy, Cloud Network Insights alert policy, and their
        history. Turning it back on needs new Monitoring Points and policies.
    -   It doesn't delete Monitoring Point VMs or containers; that's a
        separate next step, and they're billed until deleted.
    -   To do it yourself: in the Google Cloud console, open
        **Network Intelligence Center** > **Cloud Network Insights** >
        **Settings**, click **Disable product**, type `disable`, and click
        **Confirm**. If the project has a Cloud Network Insights subscription,
        this doesn't cancel it.

    Ask whether you should turn it off now and then delete the Monitoring
    Point hosts you created, naming them.
2.  After an explicit yes, run this (the console does the same; `--force` also
    deletes the Monitoring Point records and paths), then confirm that
    `providers list` is empty:

    ```bash
    gcloud network-management network-monitoring-providers delete PROVIDER_ID \
      --location=global --project=PROJECT_ID --force --quiet
    ```

3.  Then delete the Monitoring Point hosts and firewall rules you named (Full
    Cleanup, step 4) if the user agreed; otherwise list them as still billed.

## 6. Alert Policies, Cloud Logging, and Cloud Monitoring Metrics

Follow [Alerts, Logs, and Metrics](references/alerts-logs-metrics.md) for the
alert policy file, path scoping, log queries, and metric queries. Always:

-   Set `"userLabels": {"cloud-network-insights": "true"}` in alert policies so
    they appear in the Cloud Network Insights alert policies view.
-   Add `AND NOT jsonPayload.noise_conditions:*` to `insights_alarm` alert
    policy filters unless the user asks to include noisy alarms.
-   Treat an alarm as active only if the latest entry for its
    `jsonPayload.alarm_id` isn't `CLEARED`.

## 7. Troubleshoot Monitoring Points

1.  **Google Cloud Registration**: Check that `connectionStatus` is `ONLINE` in
    `monitoring-points list` (or `describe`).
2.  **Workload, Host, and Appliance Health**: Inspect the Monitoring Point
    runtime, container or Kubernetes workload, startup-script log (serial port
    output), or v35 Web Admin status (log in to its Web Admin UI) with the
    model-specific guides in
    [Monitoring Point Deployment Reference](references/monitoring-point-deployment.md),
    [Broadcom Troubleshooting Monitoring Points](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/troubleshooting-section/troubleshooting.html), and
    [Troubleshooting Cloud Network Insights](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/troubleshooting.md.txt).
3.  **Network, Proxy, and Firewall Rules**: Verify the target environment's
    firewall, Web Proxy, custom CA certificate, and gRPC/SSL inspection bypass
    settings (`data.na1.cni.appneta.com`, `content.na1.cni.appneta.com`,
    `comms.na1.cni.appneta.com`, or `.p.` endpoints for Private Service Connect)
    against [Broadcom Firewall Configuration](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-firewall.html) and
    [Add Monitoring Points](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/add-monitoring-points.md.txt).

## 8. Before Reporting

1.  Send one summary, after the last step. Re-run `monitoring-points list`
    (and `providers describe` or `instances list`), and report only its states.
2.  List what you created or deleted (VMs, firewall rules, policies, and
    Monitoring Point records, with names, IDs, and `ORG_ID`; a `404` confirmed
    absent) and what the user still has to do, each with its exact script,
    commands, or click path.
3.  Note that Monitoring Point VMs, disks, and external IPs are billed by
    Compute Engine until deleted, and delete `WORK_DIR` when you're done.
4.  If you created a proxy VM for AppNeta calls, ask whether to delete it (and
    its firewall rule) or keep it for later policy changes.

## Reference Documentation

-   [Google Cloud Network Insights Documentation](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/overview.md.txt)
-   [Broadcom AppNeta for Cloud Network Insights Documentation](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA.html)
references/
alerts-logs-metrics.md 10.6 KB
# Alert Policies, Cloud Logging, and Cloud Monitoring Metrics

Use this reference for Cloud Network Insights alert policies, alarm and event
logs, and path performance metrics. Follow the rules in
[Usage Attribution](attribution.md) for every command.

## Contents

-   [1. Alarm and Event Logs](#1-alarm-and-event-logs): Lines 14-41
-   [2. Alert Policy File](#2-alert-policy-file): Lines 43-96
-   [3. Scope to One Path or Target](#3-scope-to-one-path-or-target): Lines 98-120
-   [4. Path Metrics in Cloud Monitoring](#4-path-metrics-in-cloud-monitoring): Lines 122-176

## 1. Alarm and Event Logs

Path and Monitoring Point alarms and events reach Cloud Logging as two logs on
`resource.type` `networkmanagement.googleapis.com/NetworkPath`, `.../WebPath`,
or `.../MonitoringPoint` (fields:
[Set up logging](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/set-up-logging.md.txt)).

-   **`insights_alarm`**: `jsonPayload` has `alarm_id`, `state` (`RAISED`,
    `UPDATED`, `CLEARED`), `alarm_severity` (`CRITICAL`, `MAJOR`, `MINOR`,
    `WARNING`), `alarm_type` (`QUALITY_OF_SERVICE`), `rule` (alarm rule name),
    and `noise_conditions`. Filter on `jsonPayload.alarm_severity`, not the
    LogEntry `severity` (mapped to `CRITICAL`, `ERROR`, `WARNING`, `NOTICE`).
-   **`insights_event`**: `jsonPayload.event_type` is
    `MONITORING_POINT_OFFLINE`, `MONITORING_POINT_ONLINE`, `ROUTE_CHANGE`,
    `MTU_CHANGE`, `QOS_CHANGE`, or `FORWARDING_LOSS_CLEAR`.
-   **Active alarms**: each state change is a separate entry with the same
    `jsonPayload.alarm_id`; an alarm is active only if its latest entry isn't
    `CLEARED`. `gcloud logging read` lists newest entries first and looks back
    1 day unless you set `--freshness`; an alarm raised before that window can
    still be active, so widen it and print only the fields you need. Without a
    `path_id` filter, also cap the output (for example, `--limit=500`); if it
    returns that many entries, raise the limit or filter by path:

    ```bash
    gcloud logging read 'logName =~ "insights_alarm" AND resource.labels.path_id = "PATH_ID"' \
      --project=PROJECT_ID --freshness=7d \
      --format="table(timestamp,resource.labels.path_id,jsonPayload.alarm_id,jsonPayload.state,jsonPayload.alarm_severity,jsonPayload.rule)"
    ```

## 2. Alert Policy File

Save this log-match policy as `POLICY_FILE`, fill in the placeholders (for
`FILTER`, a console template filter below, scoped as in section 3 if needed),
and run `gcloud monitoring policies create --project=PROJECT_ID
--policy-from-file=POLICY_FILE` (to delete it, follow `SKILL.md` Rule 4 and run
`gcloud monitoring policies delete POLICY_ID --project=PROJECT_ID --quiet`). It
opens an incident when a new entry matches the filter (see
[Set up alerts and notifications](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/set-up-alerts.md.txt)):

```json
{
  "displayName": "DISPLAY_NAME",
  "documentation": {"content": "NOTES_FOR_RESPONDERS", "mimeType": "text/markdown"},
  "userLabels": {"cloud-network-insights": "true"},
  "conditions": [{
    "displayName": "Log match condition",
    "conditionMatchedLog": {"filter": "FILTER"}
  }],
  "combiner": "OR",
  "alertStrategy": {"notificationRateLimit": {"period": "300s"}, "autoClose": "1800s"},
  "notificationChannels": []
}
```

-   **`userLabels`**: `"cloud-network-insights": "true"` lists the policy in
    the Cloud Network Insights alert policies view; set it on every policy.
-   **Noise**: `AND NOT jsonPayload.noise_conditions:*` skips alarms flagged
    `frequent-detection` (default: 5 alarms on the same item in 24 hours) or
    `burst-detection` (default: more than 1 per 60 minutes). Keep it unless
    the user wants noisy alarms too; event logs don't have this field.
-   **Fixed rules**: one condition, `combiner` `"OR"`, and `autoClose` of at
    least `1800s`; `notificationRateLimit.period` is the minimum time between
    notifications. Escape each `"` in `filter` as `\"`, and list channels as
    `projects/PROJECT_ID/notificationChannels/CHANNEL_ID`.
-   **Roles**: creating the policy needs
    `roles/networkmanagement.CloudNetworkInsightsViewer`,
    `roles/logging.configWriter`, `roles/monitoring.alertPolicyEditor`, and
    `roles/monitoring.notificationChannelViewer`; adding a notification channel
    also needs `roles/monitoring.notificationChannelEditor`.

Console alert template filters, starting with network path outage:

```text
resource.type = "networkmanagement.googleapis.com/NetworkPath" AND logName =~ "insights_alarm" AND (jsonPayload.alarm_severity = "MAJOR" OR jsonPayload.alarm_severity = "CRITICAL") AND jsonPayload.state = "RAISED" AND jsonPayload.alarm_type =~ "QUALITY_OF_SERVICE" AND jsonPayload.rule =~ "Outage" AND NOT jsonPayload.noise_conditions:*
```

| Template | Change to the outage filter |
| :--- | :--- |
| Network path extended loss | `jsonPayload.alarm_severity = "MAJOR"` and `jsonPayload.rule =~ "Extended loss"` |
| Network path DNS errors | `jsonPayload.alarm_severity = "MINOR"` and `jsonPayload.rule =~ "Multiple DNS errors"` |
| Web path web errors | `resource.type = "networkmanagement.googleapis.com/WebPath"`, `jsonPayload.alarm_severity = "MAJOR"`, and `jsonPayload.rule =~ "Multiple Web errors"` |
| Monitoring Point offline | Whole filter: `resource.type = "networkmanagement.googleapis.com/MonitoringPoint" AND logName =~ "insights_event" AND jsonPayload.event_type = "MONITORING_POINT_OFFLINE"` |
| Network path MTU change | Whole filter: `resource.type = "networkmanagement.googleapis.com/NetworkPath" AND logName =~ "insights_event" AND jsonPayload.event_type = "MTU_CHANGE"` |

## 3. Scope to One Path or Target

Path alarms, path events, and path metrics carry the resource label `path_id`;
add `AND resource.labels.path_id = "PATH_ID"` to scope a log query, alert
filter, or metric query to one network or web path.

1.  `PATH_ID` is the last segment of the path's `name`. List the paths to a
    target (`destination`: IP address, hostname, or URL) with this command or
    `web-paths list`; add `AND sourceMonitoringPointId=MONITORING_POINT_ID` to
    the filter to keep one source Monitoring Point:

    ```bash
    gcloud network-management network-monitoring-providers network-paths list \
      --network-monitoring-provider=PROVIDER_ID --location=global --project=PROJECT_ID \
      --filter='destination="TARGET"' --format="table(name.basename(),displayName,sourceMonitoringPointId,dualEnded)"
    ```

2.  A target can have several paths (one per source Monitoring Point, plus the
    companion `NetworkPath` of each Web policy). OR their IDs to cover all:
    `(resource.labels.path_id = "ID_1" OR resource.labels.path_id = "ID_2")`.
    Paths created later aren't covered until you add their IDs.
3.  For a Monitoring Point event, use `resource.labels.monitoring_point_id`
    with the last segment of the Monitoring Point's `name`.

## 4. Path Metrics in Cloud Monitoring

All metric types start with `networkmanagement.googleapis.com/insights/`,
followed by `network/` for network paths (resource type
`networkmanagement.googleapis.com/NetworkPath`) or `web/` for web paths
(`networkmanagement.googleapis.com/WebPath`). Both resource types have the
labels `resource_container`, `location`, `network_monitoring_provider_id`, and
`path_id`. Single-ended paths report `total/` metrics; dual-ended paths
(`dualEnded: true`) report `in/` and `out/` metrics instead.

| Suffix | Kind, unit | Meaning |
| :--- | :--- | :--- |
| `network/rtt_avg`, `network/rtt_min`, `network/rtt_max` | GAUGE, ms | Round-trip time of data and voice probes |
| `network/total/loss_percent` (or `in/`, `out/`) | GAUGE, % | Packet loss |
| `network/total/jitter` (or `in/`, `out/`) | GAUGE, ms | Packet delay variation |
| `network/test_error` | GAUGE, 0 or 1 | 1 if errors stopped the test (100% loss is a `Connect` error); labels `error_type`, `error_detail` |
| `network/data/total/packets_sent_count`, `network/data/total/packets_received_count` | DELTA, count | Data probes sent and received |
| `network/voice/total/mos` (or `in/`, `out/`) | GAUGE, score | Estimated call quality from voice probes |
| `web/http/response_time/total` (or `dns_lookup`, `tcp_connect`, `ssl_connect`, `request_wait`, `request_receive`, `redirect`) | GAUGE, ms | Total or per-phase time of the first request |
| `web/http/test_error`, `web/browser/test_error` | GAUGE, 0 or 1 | 1 if the HTTP or browser test failed; labels `error_type`, `error_detail`, `response_code` |
| `web/total_transaction_time` | GAUGE, ms | Time to run the whole workflow |

Metric labels include `destination`, `source_monitoring_point_display_name`,
and `monitoring_policy_display_name`; `metric.labels.destination = "TARGET"`
selects every path to a target without ID lookups. Full lists and charts:
[Monitoring metrics](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/monitoring-metrics.md.txt),
[networkmanagement metrics](https://docs.cloud.google.com/monitoring/api/metrics_gcp_i_o.md.txt#networkmanagement),
[View dashboards](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/view-dashboards.md.txt).

Query one metric type per `projects.timeSeries.list` call (GNU `date`; `-K`
keeps the access token out of the process list, and the token falls back to
`gcloud auth print-access-token` if Application Default Credentials aren't set
up):

```bash
GCP_TOKEN=$(gcloud auth application-default print-access-token 2>/dev/null || gcloud auth print-access-token) &&
curl -sS -G --connect-timeout 10 --max-time 30 \
  "https://monitoring.googleapis.com/v3/projects/PROJECT_ID/timeSeries" \
  -K <(printf 'header = "Authorization: Bearer %s"\n' "$GCP_TOKEN") \
  --data-urlencode 'filter=metric.type = "networkmanagement.googleapis.com/insights/network/total/loss_percent" AND resource.labels.path_id = "PATH_ID"' \
  --data-urlencode "interval.startTime=$(date -u -Iseconds -d '-6 hours')" \
  --data-urlencode "interval.endTime=$(date -u -Iseconds)" \
  --data-urlencode "aggregation.alignmentPeriod=300s" \
  --data-urlencode "aggregation.perSeriesAligner=ALIGN_MEAN" \
  --data-urlencode "view=FULL"
```

The interval is `(startTime, endTime]` in RFC 3339. `ALIGN_MEAN` suits the
GAUGE metrics; the DELTA counts (`packets_sent_count`,
`packets_received_count`) need `ALIGN_SUM` or `ALIGN_RATE`. For one value over
the whole window, set `aggregation.alignmentPeriod` to the window (`3600s` for
the past hour). Drop the `aggregation.*` lines for raw points, or add
`aggregation.crossSeriesReducer=REDUCE_MEAN` to merge paths. Each
`timeSeries[]` item has `points[]`, newest first, with `value.doubleValue` (or
`value.int64Value`, a string, for INT64 metrics).
attribution.md 1.9 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-network-insights)" \
    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-network-insights)` 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-network-insights)
    ```

-   **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.
monitoring-point-deployment.md 27.7 KB
# Monitoring Point Deployment and Troubleshooting Reference

Cloud Network Insights supports 7 distinct Monitoring Point deployment types
across container, Kubernetes, cloud virtual appliances, and on-premises
hypervisors (`container`, `helm`, `gce-vm`, `aws-ec2`, `azure-vm`, `vmware`, and
`kvm`).

## Contents

-   [1. Download the Bundle](#1-download-the-bundle): Lines 24-51
-   [2. Platform Summary](#2-platform-summary): Lines 55-65
-   [3. Container (c50) Monitoring Point](#3-container-c50-monitoring-point): Lines 69-202
    -   [Path A: Existing Host](#path-a-existing-host): Lines 78-105
    -   [Path B: New Compute Engine VM, No SSH](#path-b-new-compute-engine-vm-no-ssh): Lines 107-177
    -   [Container Notes](#container-notes): Lines 179-202
-   [4. Compute Engine Appliance](#4-compute-engine-appliance): Lines 206-340
    -   [Step 1: gcloud](#step-1-gcloud): Lines 225-277
    -   [Step 2: Terraform Bundle](#step-2-terraform-bundle): Lines 279-287
    -   [Step 3: Google Cloud Marketplace](#step-3-google-cloud-marketplace): Lines 289-318
    -   [Appliance Notes](#appliance-notes): Lines 320-340
-   [5. Registration and Status](#5-registration-and-status): Lines 344-360
-   [6. Host Cleanup](#6-host-cleanup): Lines 364-383

## 1. Download the Bundle

1.  **Inspect Download CLI Flags**: Run `--help` to check required and optional
    flags for the target platform:

    ```bash
    gcloud network-management network-monitoring-providers monitoring-points download-install-script --help
    ```

    -   All types require `--network-monitoring-provider=PROVIDER_ID` (where
        `PROVIDER_ID` is `external` when enabled via the Google Cloud console,
        or a custom provider ID), `--location=global`,
        `--monitoring-point-type=MONITORING_POINT_TYPE`,
        `--hostname=HOSTNAME`, `--output-file=OUTPUT_FILE`, and
        `--project=PROJECT_ID`.
    -   On-premises hypervisors (`vmware`, `kvm`) additionally require
        `--password`, `--time-zone`, and either `--use-dhcp` or static IP flags
        (`--static-ip-address`, `--netmask`, `--gateway-address`,
        `--dns-server-address`).

2.  **Keep the Bundle Private**: Save it in `WORK_DIR` (a private directory from
    `mktemp -d`). It contains the Monitoring Point's keys, so never print it or
    paste it into a command.

3.  **Inspect Extracted Bundle and Official Documentation**: After extracting
    the archive (`.tar.gz` or `.zip`), read the files inside it (`README.md`,
    `./setup.sh --help`, `template.yaml`, `main.bicep`, or Terraform variables)
    and the setup guide for the type in Section 2.

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

## 2. Platform Summary

| `--monitoring-point-type` | Target Platform | Bundle Contents and Deployment | Official Setup and Troubleshooting Documentation |
| :--- | :--- | :--- | :--- |
| `container` | Docker / Podman (`c50-Docker/Podman`) | `compose.HOSTNAME.tar.gz` (extracts to `HOSTNAME/`) → `cd HOSTNAME && ./setup.sh install -y -z -n host`, or a startup script on a new Compute Engine VM (see [Container (c50) Monitoring Point](#3-container-c50-monitoring-point)); check status via `./setup.sh status` or `docker ps` / `sudo podman ps` | • [Google Cloud: Deploy Container MPs](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/deploy-container-monitoring-points.md.txt)<br>• [Broadcom: c50-Docker/Podman Setup](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/docker-mp-intro/docker-setup/docker-mp-setup-cmp.html)<br>• [Broadcom: c50-Docker/Podman Troubleshooting](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/docker-mp-intro/docker-setup/docker-mp-troubleshooting-connectivity-to-appneta.html)<br>• [Broadcom: c50-Docker/Podman View Status](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/docker-mp-intro/docker-access/docker-mp-view-monitoring-point-status.html) |
| `helm` | Kubernetes / GKE / EKS / AKS (`c50-Kubernetes (Helm)`) | `helm.HOSTNAME.tar.gz` → `helm upgrade --install appneta-mp ./chart --namespace NAMESPACE --create-namespace`; locate namespace/workload via `kubectl get statefulsets -A -l app=c50` and inspect `statefulsets` / `pods` | • [Google Cloud: Deploy Container MPs](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/deploy-container-monitoring-points.md.txt)<br>• [Broadcom: c50-Kubernetes (Helm) Setup](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/kubernetes-mp-intro/kubernetes-setup/kubernetes-mp-setup-cmp.html)<br>• [Broadcom: c50-Kubernetes (Helm) Troubleshooting](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/kubernetes-mp-intro/kubernetes-setup/kubernetes-mp-troubleshooting-connectivity-to-appneta.html)<br>• [Broadcom: c50-Kubernetes (Helm) View Status](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/kubernetes-mp-intro/kubernetes-access/kubernetes-mp-view-monitoring-point-status.html) |
| `gce-vm` | Compute Engine Appliance (`Google CE`) | `gcloud` with the appliance image and a generated `mp-config` (default); `terraform.HOSTNAME.zip` → `terraform init && terraform apply -var="project_id=PROJECT_ID" -var="zone=ZONE" -var='networks=["NETWORK"]' -var='subnets=["SUBNET"]' -var='external_ipv4_addresses=["EPHEMERAL"]'`; or Google Cloud Marketplace, only on request (see [Compute Engine Appliance](#4-compute-engine-appliance)) | • [Google Cloud: Deploy GCE MPs](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/deploy-gce-monitoring-points.md.txt)<br>• [Broadcom: GCE Terraform Setup](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/gce-mp-intro/gce-setup/gce-mp-setup-cloud-mp.html#mp-setup-cmp_deploy-terraform)<br>• [Broadcom: GCE Marketplace Setup](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/gce-mp-intro/gce-setup/gce-mp-setup-cloud-mp.html#mp-setup-cmp_deploy-marketplace)<br>• [Broadcom: Google CE Troubleshooting](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/gce-mp-intro/gce-setup/gce-mp-troubleshooting-connectivity-to-appneta.html) |
| `aws-ec2` | AWS EC2 CloudFormation (`AWS EC2`) | `cloudformation.HOSTNAME.zip` (`template.yaml` + `appneta-parameters.json`) → `aws cloudformation create-stack --region REGION --stack-name STACK_NAME --template-body file://template.yaml --parameters file://appneta-parameters.json --capabilities CAPABILITY_IAM` (or AWS Quick-Create Link) | • [Google Cloud: Deploy AWS MPs](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/deploy-aws-monitoring-points.md.txt)<br>• [Broadcom: AWS EC2 Setup](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/aws-ec2-mp-intro/aws-ec2-setup/aws-ec2-mp-setup-cloud-mp.html)<br>• [Broadcom: AWS EC2 Troubleshooting](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/aws-ec2-mp-intro/aws-ec2-setup/aws-ec2-mp-troubleshooting-connectivity-to-appneta.html) |
| `azure-vm` | Microsoft Azure Bicep / ARM (`Azure VM`) | `bicep.HOSTNAME.zip` (`main.bicep` + `appneta.bicepparam`) → `az deployment group create --resource-group RESOURCE_GROUP --template-file main.bicep --parameters appneta.bicepparam` (verify NSG outbound TCP `443`, UDP `123`, DNS `53` if provisioning times out) | • [Google Cloud: Deploy Azure MPs](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/deploy-azure-monitoring-points.md.txt)<br>• [Broadcom: Azure Setup](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/azure-vm-mp-intro/azure-vm-setup/azure-vm-mp-setup-cloud-mp.html)<br>• [Broadcom: Azure VM Troubleshooting](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/azure-vm-mp-intro/azure-vm-setup/azure-vm-mp-troubleshooting-connectivity-to-appneta.html) |
| `vmware` | VMware vSphere / ESXi OVA (`v35-VMware`) | `vmware.HOSTNAME.zip` (`parameters.json` / `ovf-env.xml`) → Deploy Broadcom v35 OVA template in vSphere Client; log in to its Web Admin UI and check (in **General** > **Monitoring Point Connected**, **System Status** > **System Time** and **NTP Synchronized**, **Network State** > **eth0**, and **Monitoring Point Health** > **Server Reachability**) | • [Google Cloud: Deploy VMware and KVM MPs](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/deploy-vms-monitoring-points.md.txt)<br>• [Broadcom: vSphere OVA Setup](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/v35-vmware-mp-intro/v35-vmware-setup/v35-vmware-mp-setup-v35-vmware.html)<br>• [Broadcom: v35-VMware Troubleshooting](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/v35-vmware-mp-intro/v35-vmware-setup/v35-vmware-mp-troubleshooting-connectivity-to-appneta.html)<br>• [Broadcom: v35-VMware Server Reachability Test](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/v35-vmware-mp-intro/v35-vmware-management/v35-vmware-mp-check-server-reachability.html) |
| `kvm` | Linux KVM / QEMU QCOW2 (`v35-KVM`) | `kvm.HOSTNAME.zip` (`config.iso`) → Import Broadcom QCOW2 disk image into KVM/libvirt with `config.iso` attached; log in to its Web Admin UI and check (in **General** > **Monitoring Point Connected**, **System Status** > **System Time** and **NTP Synchronized**, **Network State** > **eth0**, and **Monitoring Point Health** > **Server Reachability**) | • [Google Cloud: Deploy VMware and KVM MPs](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/deploy-vms-monitoring-points.md.txt)<br>• [Broadcom: KVM QCOW2 Setup](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/v35-kvm-mp-intro/v35-kvm-setup/v35-kvm-mp-setup-v35-kvm.html)<br>• [Broadcom: v35-KVM Troubleshooting](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/v35-kvm-mp-intro/v35-kvm-setup/v35-kvm-mp-troubleshooting-connectivity-to-appneta.html)<br>• [Broadcom: v35-KVM Server Reachability Test](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-overview/v35-kvm-mp-intro/v35-kvm-management/v35-kvm-mp-check-server-reachability.html) |

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

## 3. Container (c50) Monitoring Point

The container Monitoring Point runs two containers (`sequencer` and `talos`) on
a Linux host with Docker or Podman. It authenticates to AppNeta with the keys in
its bundle, so its host needs outbound internet access but no service account.
On Google Cloud without a suitable host, confirm with the user before creating a
small VM (for example `e2-medium` with Debian 12, in the zone they want to
measure from), and use Path B.

### Path A: Existing Host

Use this path for a host that already exists and that you can reach over SSH;
if you can't, give these commands to the user to run on the host. Ask before
installing packages on it.

1.  Download the `container` bundle for the host's name (Section 1) as
    `WORK_DIR/compose.HOSTNAME.tar.gz` and copy it to the host, for example
    with `gcloud compute scp WORK_DIR/compose.HOSTNAME.tar.gz HOSTNAME:~
    --zone=ZONE --project=PROJECT_ID --ssh-flag="-o ConnectTimeout=10"
    --quiet`.
2.  If the host has neither Docker nor Podman, install `docker.io` (Compose v2
    isn't required) and add the SSH user to the `docker` group:

    ```bash
    sudo apt-get update && sudo apt-get install -y docker.io && sudo usermod -aG docker "$USER"
    ```

3.  Reconnect (so the group change applies and `setup.sh` runs without `sudo`),
    then extract the bundle and install from inside its directory:

    ```bash
    tar -xzf compose.HOSTNAME.tar.gz && cd HOSTNAME && ./setup.sh install -y -z -n host
    ./setup.sh status
    ```

If SSH times out or is refused, don't retry it and don't open TCP 22: give the
user these commands, or use Path B with a new VM.

### Path B: New Compute Engine VM, No SSH

The VM installs the Monitoring Point on its first boot with a startup script,
and the bundle travels in instance metadata, so this path needs no SSH access,
no firewall rule, and no service account. The Monitoring Point is usually
`ONLINE` about 2-3 minutes after the VM is created. The bundle holds only this
Monitoring Point's registration keys (the Compute Engine appliance keeps the
same kind of keys in its `mp-config` metadata), and step 5 removes it. Never
put AppNeta API calls or tokens in a startup script or metadata: anyone with
read access to the VM can read its metadata.

1.  Download the `container` bundle for the VM name you will create (Section 1)
    as `WORK_DIR/compose.HOSTNAME.tar.gz`, and encode it into a file (about
    30 KB; never print it):

    ```bash
    base64 < WORK_DIR/compose.HOSTNAME.tar.gz > WORK_DIR/compose.HOSTNAME.b64
    ```

2.  Save this startup script unchanged as `WORK_DIR/c50-startup.sh`, for example
    with a file-writing tool. It installs Docker, unpacks the bundle from
    metadata, runs `setup.sh install` from inside the bundle directory, and
    retries once if the installer exits with code 5 after updating itself:

```bash
#!/bin/bash
# Installs the c50 Monitoring Point from instance metadata on first boot.
set -o pipefail
[ -f /opt/cni/.installed ] && exit 0
export DEBIAN_FRONTEND=noninteractive
apt-get update && apt-get -o DPkg::Lock::Timeout=300 install -y docker.io || exit 1
mkdir -p /opt/cni && cd /opt/cni || exit 1
curl -sf --max-time 30 -H "Metadata-Flavor: Google" \
  "http://metadata.google.internal/computeMetadata/v1/instance/attributes/c50-bundle-b64" \
  | base64 -d | tar -xz || exit 1
cd /opt/cni/*/ || exit 1
./setup.sh install -y -z -n host
rc=$?
if [ "$rc" -eq 5 ]; then ./setup.sh install -y -z -n host; rc=$?; fi
[ "$rc" -eq 0 ] && touch /opt/cni/.installed
exit "$rc"
```

3.  Create the VM. It gets an ephemeral external IP for outbound access (add a
    Cloud NAT subnet instead if the user forbids external IPs):

    ```bash
    gcloud services enable compute.googleapis.com --project=PROJECT_ID
    gcloud compute instances create HOSTNAME --project=PROJECT_ID --zone=ZONE \
      --machine-type=e2-medium --image-family=debian-12 --image-project=debian-cloud \
      --network=NETWORK --subnet=SUBNET \
      --metadata-from-file=c50-bundle-b64=WORK_DIR/compose.HOSTNAME.b64,startup-script=WORK_DIR/c50-startup.sh \
      --no-service-account --no-scopes
    ```

4.  Poll `monitoring-points list` every 30 seconds until `HOSTNAME` is `ONLINE`
    (Section 5). If it isn't after 5 minutes, read the startup log from the
    serial port (read-only; no SSH):

    ```bash
    gcloud compute instances get-serial-port-output HOSTNAME --zone=ZONE \
      --project=PROJECT_ID | grep startup-script | tail -n 30
    ```

5.  Once it's `ONLINE`, remove the bundle from metadata (the startup script
    skips installed hosts on later boots):

    ```bash
    gcloud compute instances remove-metadata HOSTNAME --keys=c50-bundle-b64 \
      --zone=ZONE --project=PROJECT_ID
    ```

### Container Notes

-   **Working Directory**: The archive extracts into a `HOSTNAME/`
    subdirectory, and `setup.sh` sources `.util.sh` from the current directory,
    so `cd HOSTNAME` before running it. From any other directory it fails with
    `.util.sh: No such file or directory` and `PULL_LOG_PREFIX: unbound
    variable`. `./setup.sh --help` exits with `Could not find a compatible
    container engine` until Docker or Podman is installed.
-   **`setup.sh install` flags**: `-y` runs non-interactively, `-z` uses the
    default timezone, `-n host` uses host networking (use `-n bridge` only if
    host networking isn't possible on the host), and `-w overwrite` replaces an
    existing configuration.
-   **Status**: Run `./setup.sh status`, which lists the `sequencer` and `talos`
    containers. Don't wrap it in `sudo /bin/bash`: `docker` group members don't
    need root, and security policies that block root shells reject that form.
-   **Private Service Connect**: Pass `-e .private.env` immediately after the
    subcommand; otherwise `setup.sh` ignores it and uses the public `.env`:
    `./setup.sh install -e .private.env -y -z -n host -w overwrite`, then
    `./setup.sh status -e .private.env`.
-   **Docker Compose**: `setup.sh` doesn't work with legacy `docker-compose` v1.
    If v1 is installed (such as from Debian apt), `setup.sh` prompts and fails
    with `invalid reference format`; ask the user before removing v1 or
    installing `docker-compose-plugin`, because either changes the host. With no
    Compose installed, `setup.sh` uses its built-in `compose-in-docker` runner.

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

## 4. Compute Engine Appliance

The `gce-vm` Monitoring Point is a Broadcom appliance image that Google Cloud
Marketplace also lists. The VM name becomes the Monitoring Point name. Ask the
user which zone to deploy in, because the appliance is the source of its paths;
default to `us-central1-a` (see
[Regions and zones](https://docs.cloud.google.com/compute/docs/regions-zones.md.txt)).

Deploy it yourself with `gcloud` (Step 1): it needs no browser, no service
account, and no terms step. Only the Marketplace page shows its listing's
terms, so don't send the user there or ask about those terms unless the user
asks for Marketplace.

| Order | Path | Use when | Requires |
| :--- | :--- | :--- | :--- |
| 1 | `gcloud` with the appliance image | Default | `roles/compute.instanceAdmin.v1` |
| 2 | Terraform bundle | The user wants Terraform | Terraform 1.5.7 or later (ask before installing it); `roles/compute.admin` on the project and `roles/iam.serviceAccountUser` on the VM's service account |
| 3 | Google Cloud Marketplace | The user asks for Marketplace | Browser; `roles/config.admin` and `roles/consumerprocurement.entitlementManager` on the project; a deployment service account with `roles/config.agent`, `roles/compute.admin`, and `roles/iam.serviceAccountUser` |

### Step 1: gcloud

The appliance authenticates to AppNeta with the device key in its `mp-config`
metadata, so its VM needs no service account.

1.  Get `SOURCE_IMAGE` from the `gce-vm` bundle. Print only that line, because
    the file also holds the device key:

    ```bash
    gcloud network-management network-monitoring-providers monitoring-points download-install-script \
      --network-monitoring-provider=PROVIDER_ID --location=global --project=PROJECT_ID \
      --monitoring-point-type=gce-vm --hostname=HOSTNAME --output-file=WORK_DIR/terraform.HOSTNAME.zip
    unzip -p WORK_DIR/terraform.HOSTNAME.zip terraform.tfvars | grep '^source_image'
    ```

    Use `source_image` from `terraform.tfvars`, not the `variables.tf` default,
    which can be older. The listing's **Command-Line Deployment** tab shows the
    same image.
2.  Create `WORK_DIR/mp-config.yaml`. If the user saved the console snippet, use
    that file unchanged. Otherwise generate the configuration; the appliance
    reads a top-level `configurations:` list, so unwrap the `config` key:

    ```bash
    gcloud network-management network-monitoring-providers generate-monitoring-point-config \
      PROVIDER_ID --location=global --project=PROJECT_ID --format=json \
      | python3 -c 'import json,sys,yaml; sys.stdout.write(yaml.safe_dump(json.load(sys.stdin)["config"], default_flow_style=False, sort_keys=False))' \
      > WORK_DIR/mp-config.yaml
    ```

    If Python's `yaml` module is missing, replace `--format=json | python3 ...`
    with `--format="yaml(config)" | sed '1d; s/^  //'`. Never print any part of
    the file, because it holds the device key; to check it, run
    `grep -c '^configurations:' WORK_DIR/mp-config.yaml` (expect `1`). To add
    another appliance, reuse this file or generate it again; don't read it back
    from an existing VM's metadata.
3.  Create the VM:

    ```bash
    gcloud services enable compute.googleapis.com --project=PROJECT_ID
    gcloud compute instances create HOSTNAME --project=PROJECT_ID --zone=ZONE \
      --machine-type=e2-standard-2 --image=SOURCE_IMAGE \
      --boot-disk-size=24GB --boot-disk-type=pd-balanced \
      --network-interface=network=NETWORK,subnet=SUBNET,nic-type=GVNIC \
      --metadata-from-file=mp-config=WORK_DIR/mp-config.yaml \
      --no-service-account --no-scopes
    ```

    `--no-service-account --no-scopes` also avoids `iam.serviceAccounts.actAs`
    errors on the default service account; the trade-off is no Ops Agent logs or
    metrics.
4.  Poll `monitoring-points list` every 30 seconds (Section 5). The appliance is
    usually `ONLINE` (`type: Google CE`) about 3 minutes after the VM is
    created.

### Step 2: Terraform Bundle

Extract `terraform.HOSTNAME.zip` (Step 1, item 1) and run `terraform init &&
terraform apply` with `-var="project_id=PROJECT_ID" -var="zone=ZONE"
-var='networks=["NETWORK"]' -var='subnets=["SUBNET"]'
-var='external_ipv4_addresses=["EPHEMERAL"]'`. The module assigns no external IP
by default, so keep `external_ipv4_addresses` unless the subnet has Cloud NAT.
It uses the Compute Engine default service account unless
`service_account_email` is set. Remove it with `terraform destroy`.

### Step 3: Google Cloud Marketplace

Use this path only when the user asks for Marketplace. With a browser tool, do
these steps yourself; otherwise send them to the user and ask for the result or
the exact error:

1.  In the Google Cloud console, open **Network Intelligence Center** > **Cloud
    Network Insights** > **Monitoring Points**, click **Add Monitoring Point**,
    set **Platform Type** to **Google Cloud**, click **Continue**, enter
    `HOSTNAME` as the **Hostname**, click **Continue**, select **Google Cloud
    Marketplace** and the project, copy the **Monitoring point configuration**
    snippet with its copy button, and click **Open through Google Cloud
    Marketplace**.
2.  Click **Get Started**. If the listing asks you to accept its terms, follow
    `SKILL.md` Rule 3: with a browser tool, summarize their main points (who
    provides the product, pricing, and license), say that the listing's full
    terms are what apply, and accept them only after an explicit yes or the
    user's explicit prior approval of all terms. Then click **Deploy**, and
    enable the Infrastructure Manager API (`config.googleapis.com`) if
    prompted.
3.  Select a deployment service account and an instance service account. Under
    **Network interfaces**, assign an external IP unless the subnet has Cloud
    NAT, paste the snippet into **Monitoring Point configuration**, and click
    **Deploy**. Choosing **New account** grants IAM roles, so confirm that with
    the user first.

Success signal: the deployment finishes and `HOSTNAME` appears in
`monitoring-points list`. If the form can't detect the default service account,
reports missing `config.deployments.*` permissions, or the user can't continue,
offer Step 1 instead of retrying.

### Appliance Notes

-   **Configuration Handling**: Pass the configuration file unchanged with
    `--metadata-from-file` (or paste it into the Marketplace field). Shells can
    rewrite `$` and `!` sequences in device keys, so never inline the
    configuration in a command, and keep the snippet's `device_key: >-` block:
    flattened onto one line, the leading `!` becomes a YAML tag and parsing
    fails. Don't hand-copy `mp_config` out of `terraform.tfvars` either; it's
    HCL (unicode escapes such as `\u003d`, no commas between some keys).
-   **Networking**: The appliance needs outbound internet access to AppNeta
    (see [Broadcom Firewall Configuration](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/appliance-firewall.html)).
    `gcloud compute instances create` assigns an ephemeral external IP unless
    you add `no-address`.
-   **Firewall**: Single-ended tests need only outbound access, so create no
    inbound rule by default. Marketplace and Terraform deployments also create
    an ingress rule from `0.0.0.0/0` for the dual-ended test ports and an
    allow-all egress rule. Open inbound ports only for dual-ended tests, only
    with the user's approval, and only from the peers' ranges.
-   **Pricing**: Check the listing's **Pricing** tab; the VM, disk, and
    external IP are billed as Compute Engine resources (see
    [Compute Engine pricing](https://cloud.google.com/products/compute/pricing)).

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

## 5. Registration and Status

Verify that deployed Monitoring Points across any platform have registered with
Cloud Network Insights (`ONLINE` vs `OFFLINE`):

```bash
gcloud network-management network-monitoring-providers monitoring-points list \
  --network-monitoring-provider=PROVIDER_ID \
  --location=global \
  --project=PROJECT_ID
```

| Deployment | Poll every | Usually `ONLINE` | If still missing |
| :--- | :--- | :--- | :--- |
| Container after `setup.sh install` on a host | 10 seconds | Within 30 seconds (`type: c50 Container`) | Run `./setup.sh status` on the host |
| Container VM with the Path B startup script | 30 seconds | About 2-3 minutes | After 5 minutes, read the serial port output (Path B, step 4) |
| Compute Engine appliance VM | 30 seconds | About 3 minutes (`type: Google CE`) | After 10 minutes, run `gcloud compute instances get-serial-port-output HOSTNAME --zone=ZONE --project=PROJECT_ID` |

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

## 6. Host Cleanup

Monitoring Point hosts are billed until you delete them. Remove only hosts and
rules created for Cloud Network Insights, only after the user confirms them
(`SKILL.md` Rule 4), and in the order of the cleanup scope in `SKILL.md` (after
the policies, or after turning Cloud Network Insights off):

-   **Compute Engine VMs** (container hosts and `gcloud` appliances): `gcloud
    compute instances delete HOSTNAME --zone=ZONE --project=PROJECT_ID --quiet`
-   **Marketplace deployment**: find it with `gcloud infra-manager deployments
    list --location=REGION --project=PROJECT_ID`, then run `gcloud
    infra-manager deployments delete DEPLOYMENT --location=REGION
    --project=PROJECT_ID --quiet`, which also deletes the VM and the firewall
    rules that the deployment created. Don't delete its VM separately.
-   **Terraform**: `terraform destroy`. **Helm**: `helm uninstall appneta-mp
    --namespace NAMESPACE`. **Container on a host that stays**: `./setup.sh
    uninstall` in the bundle directory. **AWS or Azure**: delete the
    CloudFormation stack or the Azure deployment.
-   **Firewall rules**: delete only rules you created, such as `gcloud compute
    firewall-rules delete RULE_NAME --project=PROJECT_ID --quiet`.
monitoring-policies.md 20.3 KB
# Monitoring Policy Configuration Reference (AppNeta API)

This guide covers creating and deleting Network and Web Monitoring Policies
(`/api/v4/monitoringPolicy`), and deleting Monitoring Point records
(`/api/v4/monitoringPoint`), with the Broadcom AppNeta REST API v4.

## Contents

-   [1. Set Up AppNeta API Access](#1-set-up-appneta-api-access): Lines 18-95
-   [2. Network Monitoring Policies](#2-network-monitoring-policies): Lines 99-164
-   [3. Web Monitoring Policies](#3-web-monitoring-policies): Lines 168-222
-   [4. Delete Policies and Monitoring Point Records](#4-delete-policies-and-monitoring-point-records): Lines 226-261
-   [5. Policy Script](#5-policy-script): Lines 265-438
    -   [AppNeta Web UI](#appneta-web-ui): Lines 372-385
    -   [Proxy VM](#proxy-vm): Lines 387-438
-   [6. Troubleshooting](#6-troubleshooting): Lines 442-461

## 1. Set Up AppNeta API Access

Run these steps in order. `WORK_DIR` is a private directory created with
`mktemp -d`, and `PROVIDER_ID` is `external` when Cloud Network Insights was
enabled in the Google Cloud console.

1.  **AppNeta host** (`APPNETA_HOST`, such as `google.na1.cni.appneta.com`). It
    isn't a secret, so reuse the literal value in later commands:

    ```bash
    gcloud network-management network-monitoring-providers describe PROVIDER_ID \
      --location=global --project=PROJECT_ID --format="value(providerUri)"
    ```

2.  **Reachability probe**, once and without a token:

    ```bash
    curl -sS -o /dev/null -w '%{http_code}\n' --connect-timeout 10 --max-time 15 \
      "https://APPNETA_HOST/api/v4/organization"
    ```

    -   Any HTTP code, including `401`, means AppNeta is reachable: run the
        [policy script](#5-policy-script) yourself
        (or the steps below one at a time).
    -   `000` with curl exit code 6, 7, or 28 (DNS failure, connection refused,
        or timeout) means your environment can't reach AppNeta. Stop the
        AppNeta work here and don't retry. Give the user three choices in one
        message: the [AppNeta web UI](#appneta-web-ui) steps, the filled-in
        [policy script](#5-policy-script) to run themselves, or a
        [proxy VM](#proxy-vm) that you create and run the script from. Then
        continue with the rest of the task.

3.  **Provider access token** in a private curl config file. The token wraps
    your Google Cloud access token and expires with it (about one hour; see
    [Exchange tokens](https://docs.cloud.google.com/network-intelligence-center/docs/cloud-network-insights/access-appneta-api.md.txt#exchange-tokens));
    without a signed-in `gcloud` account, the command falls back to
    Application Default Credentials. This form keeps the token out of command
    lines and output; never run the token commands without the redirect, and
    never print the file:

    ```bash
    gcloud network-management network-monitoring-providers generate-provider-access-token \
      PROVIDER_ID --location=global --project=PROJECT_ID \
      --gcp-access-token="$(gcloud auth print-access-token 2>/dev/null || gcloud auth application-default print-access-token)" \
      --format="value(providerAccessToken)" \
      | sed 's/.*/header = "Authorization: Bearer &"/' > WORK_DIR/appneta-auth
    test -s WORK_DIR/appneta-auth || echo "No provider access token; see the gcloud error above."
    ```

4.  **Organization ID** (`ORG_ID`). The response is an array of every
    organization the token can access (one per Cloud Network Insights project),
    so select this project's organization by `name` (or match
    `externalAccountId` to the project number) instead of taking the first
    `id`:

    ```bash
    curl -sS --connect-timeout 10 --max-time 30 -K WORK_DIR/appneta-auth \
      "https://APPNETA_HOST/api/v4/organization" \
      | jq '.[] | select(.name == "PROJECT_ID") | {id, name, externalAccountId}'
    ```

    If `jq` fails with an error such as `Cannot index number`, the response is
    an error object: rerun the call without `jq` to read it (for `401`, see
    [Troubleshooting](#6-troubleshooting)).

Every later call starts with the same
`curl -sS --connect-timeout 10 --max-time 30 -K WORK_DIR/appneta-auth` options;
add `-H "Content-Type: application/json"` when you send a body. Never add `-v`,
`--verbose`, or `--trace`: they print the `Authorization` header. Without `jq`,
filter the JSON with any JSON tool, such as `python3 -c`, the same way.

-   **Reference Documentation**:
    -   [Broadcom AppNeta REST API v4 Documentation](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/api/api-v4.html):
        Authentication headers, organization/policy/Monitoring Point ID lookup,
        and valid `APPNETA_MP_TYPE` values.
    -   **OpenAPI 3.0 Spec**:
        `https://APPNETA_HOST/api/openapi.json?version=v4` (or Swagger UI at
        `https://APPNETA_HOST/api/swagger/index.html#/`).

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

## 2. Network Monitoring Policies

1.  **Check Existing Policies**: Query `GET /api/v4/monitoringPolicy` first to
    verify whether a policy with the target `name` already exists. The list
    includes policies from every organization the token can access, so look
    only at your `ORG_ID`, and pipe the response straight into the filter
    rather than pasting it into a script, where quoting errors can silently
    skip the check:

    ```bash
    curl -sS --connect-timeout 10 --max-time 30 -K WORK_DIR/appneta-auth \
      "https://APPNETA_HOST/api/v4/monitoringPolicy" \
      | jq --argjson org ORG_ID '[.[] | select(.orgId == $org) | {id, name, target}]'
    ```

2.  **Create Network Monitoring Policy**: If the name isn't listed, save the
    payload below as `WORK_DIR/POLICY_NAME.json` and send it:

    ```bash
    curl -sS --connect-timeout 10 --max-time 30 -K WORK_DIR/appneta-auth \
      -X POST -H "Content-Type: application/json" --data @WORK_DIR/POLICY_NAME.json \
      "https://APPNETA_HOST/api/v4/monitoringPolicy"
    ```

```json
{
  "orgId": ORG_ID,
  "name": "POLICY_NAME",
  "description": "DESCRIPTION",
  "monitoringEnabled": true,
  "target": "TARGET_IP",
  "networkMonitoring": {
    "dualEnded": false,
    "networkProtocol": "TCP",
    "networkPathGroupName": "Default"
  },
  "webHttpMonitoring": null,
  "monitoringPointRules": [
    {
      "filterRule": {
        "type": {
          "values": ["APPNETA_MP_TYPE"],
          "exclude": false
        }
      }
    }
  ]
}
```

-   `target`: An IP address or hostname without a scheme (for example,
    `8.8.8.8`).
-   `dualEnded`: `false` (single-ended against a target IP) or `true`
    (dual-ended between two AppNeta Monitoring Points).
-   `networkProtocol`: `"TCP"` (default) or `"UDP"`.
-   `APPNETA_MP_TYPE`: Must match the AppNeta Monitoring Point type string
    (such as `"c50 Container"`, `"Google CE"`, or `"v35 Virtual"`; the `type`
    field in `monitoring-points list` shows it — see
    [Monitoring Point Types](https://techdocs.broadcom.com/us/en/ca-enterprise-software/it-operations-management/appneta-for-google-cloud-network-insights/GA/api/api-v4.html#title-appneta-api_monitoring-point-types)).
-   `monitoringPointRules`: A `type` filter applies the policy to every
    Monitoring Point of that type in the organization. To scope the policy to
    specific Monitoring Points, such as the one the user named, filter by
    Monitoring Point name instead:
    `"filterRule": {"name": {"values": ["MP_NAME"], "exclude": false}}`, where
    `MP_NAME` is the `displayName` of the Monitoring Point in `monitoring-points
    list`.

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

## 3. Web Monitoring Policies

After checking `GET /api/v4/monitoringPolicy` (Section 2, step 1), create an
HTTP/HTTPS synthetic web policy with the Section 2 `POST` command and the
following JSON payload:

```json
{
  "orgId": ORG_ID,
  "name": "POLICY_NAME",
  "description": "DESCRIPTION",
  "monitoringEnabled": true,
  "target": "TARGET_URL",
  "networkMonitoring": {
    "dualEnded": false,
    "networkProtocol": "TCP",
    "networkPathGroupName": "Default"
  },
  "webHttpMonitoring": {
    "method": "GET",
    "intervalMinutes": 5,
    "timeoutSeconds": 60,
    "ignoreSslValidation": false,
    "followRedirects": true,
    "assertions": [
      {
        "type": "statuscode",
        "value": "200"
      }
    ]
  },
  "monitoringPointRules": [
    {
      "filterRule": {
        "type": {
          "values": ["APPNETA_MP_TYPE"],
          "exclude": false
        }
      }
    }
  ]
}
```

-   `target`: The full URL including the scheme (for example,
    `https://1.1.1.1`); the companion `NetworkPath` probes its host. Before
    relying on a `200` assertion, confirm the URL returns it (for example,
    `curl -sL --connect-timeout 10 --max-time 15 -o /dev/null
    -w '%{http_code}' -- "TARGET_URL"` from a host with internet access).
-   `networkMonitoring`: Required on Web Monitoring Policies (`null` returns
    `HTTP 400: Network Monitoring must be specified.`). The policy creates a
    `WebPath` plus a companion `NetworkPath` to the target host
    (`relatedNetworkPathId`) unless one already exists.
-   `monitoringPointRules`: To limit the policy to specific Monitoring Points,
    use the `name` filter from Section 2.

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

## 4. Delete Policies and Monitoring Point Records

Deletions are permanent: deleting a policy removes its paths, and deleting a
Monitoring Point record also deletes the paths it sources and their history.
Look up the IDs, show the user exactly what you'll delete, and send the
`DELETE` calls only after an explicit yes (`SKILL.md` Rule 4), one call per
ID. Never reuse IDs from memory or from another organization: the token also
sees other projects' organizations, whose policies and records can share
names.

1.  **Policies**: list this organization's policies and their IDs (Section 2,
    step 1).
2.  **Monitoring Point records**: list this organization's records with their
    IDs and status (each `id` is also the last segment of the Monitoring
    Point's `name` in `monitoring-points list`):

    ```bash
    curl -sS --connect-timeout 10 --max-time 30 -K WORK_DIR/appneta-auth \
      "https://APPNETA_HOST/api/v4/monitoringPoint?orgId=ORG_ID&limit=1000" \
      | jq --argjson org ORG_ID '[.[] | select(.orgId == $org) | {id, name, connectionStatus}]'
    ```

3.  **Delete** each confirmed policy or record by its ID, and a record only
    after its host is gone and it shows `OFFLINE`:

    ```bash
    curl -sS --connect-timeout 10 --max-time 30 -K WORK_DIR/appneta-auth -X DELETE \
      -o /dev/null -w '%{http_code}\n' "https://APPNETA_HOST/api/v4/monitoringPolicy/POLICY_ID"
    curl -sS --connect-timeout 10 --max-time 30 -K WORK_DIR/appneta-auth -X DELETE \
      -o /dev/null -w '%{http_code}\n' "https://APPNETA_HOST/api/v4/monitoringPoint/MP_ID"
    ```

    A `2xx` code means deleted, and `404` means already gone. On `401`, repeat
    Section 1, step 3 once and retry.
4.  **Verify** with a fresh list, and with `network-paths list`, `web-paths
    list`, or `monitoring-points list`.

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

## 5. Policy Script

This script creates policies, or lists them, by name in this project's
organization; it never deletes anything (deletions follow Section 4). It checks
for existing policies before creating, mints its own token (or reads it from
standard input with `--auth-stdin`), keeps the token in memory, and never
prints it or writes it to a file. Use it in one of three ways:

-   **AppNeta reachable**: save it as `WORK_DIR/cni-policies.sh` and run
    `bash WORK_DIR/cni-policies.sh` yourself.
-   **AppNeta unreachable, the user runs it**: paste the complete filled-in
    script into your reply as a code block, for the user to run from a machine
    that has a signed-in `gcloud`, `curl`, `jq`, and HTTPS access to
    `APPNETA_HOST`. A path to a file in your environment doesn't help: the user
    runs it elsewhere. The script contains no tokens or keys.
-   **AppNeta unreachable, the user picks a proxy VM**: see
    [Proxy VM](#proxy-vm).

Replace `PROJECT_ID`, `PROVIDER_ID`, and `APPNETA_HOST` at the top, then edit
only the last lines: one `create_policy NAME TARGET MP_NAME network|web` line
per policy (network targets are bare IPs or hostnames, web targets are full
URLs, and `MP_NAME` is the Monitoring Point's `displayName`), or
`list_policies` to show this organization's policies.

```bash
#!/bin/bash
# Creates Cloud Network Insights monitoring policies in AppNeta, or lists this
# project's policies. It never deletes anything.
# Usage: bash cni-policies.sh [--auth-stdin]
set -euo pipefail
PROJECT_ID="PROJECT_ID"
PROVIDER_ID="PROVIDER_ID"
API="https://APPNETA_HOST/api/v4"

# Provider access token, kept in memory and never printed. With --auth-stdin
# (on a proxy VM), it's read from standard input instead of minted here.
TOKEN=""
if [ "${1:-}" = "--auth-stdin" ]; then
  IFS= read -r TOKEN || true
else
  GCP_TOKEN=$(gcloud auth print-access-token 2>/dev/null \
    || gcloud auth application-default print-access-token)
  TOKEN=$(gcloud network-management network-monitoring-providers \
    generate-provider-access-token "$PROVIDER_ID" --location=global \
    --project="$PROJECT_ID" --gcp-access-token="$GCP_TOKEN" \
    --format="value(providerAccessToken)")
fi
[ -n "$TOKEN" ] || { echo "No provider access token." >&2; exit 1; }
auth() { printf 'header = "Authorization: Bearer %s"\n' "$TOKEN"; }

api() {  # api [CURL_OPTIONS...] URL: prints the response body; fails on HTTP errors
  local out code
  out=$(curl -sS --connect-timeout 10 --max-time 30 -K <(auth) \
    -H "Content-Type: application/json" -w '\n%{http_code}' "$@") || true
  code=${out##*$'\n'}
  out=${out%$'\n'*}
  case "$code" in
    2??) printf '%s\n' "$out" ;;
    *) echo "HTTP ${code:-error}: $out" >&2; return 1 ;;
  esac
}

# This project's organization; the token can see one organization per project.
ORG_ID=$(api "$API/organization" \
  | jq -e --arg p "$PROJECT_ID" 'first(.[] | select(.name == $p) | .id)') \
  || { echo "Could not find the AppNeta organization for $PROJECT_ID." >&2; exit 1; }
echo "AppNeta organization for $PROJECT_ID: $ORG_ID"

list_policies() {  # list_policies: this organization's policies (id, name, target)
  api "$API/monitoringPolicy" \
    | jq -c --argjson org "$ORG_ID" '.[] | select(.orgId == $org) | {id, name, target}'
}

policy_ids() {  # policy_ids NAME: IDs of the policies with that name in this organization
  api "$API/monitoringPolicy" \
    | jq -r --argjson org "$ORG_ID" --arg n "$1" \
        '.[] | select(.orgId == $org and .name == $n) | .id'
}

create_policy() {  # create_policy NAME TARGET MP_NAME network|web
  case "${4:-}" in
    network|web) ;;
    *) echo "Usage: create_policy NAME TARGET MP_NAME network|web" >&2; return 1 ;;
  esac
  local existing
  existing=$(policy_ids "$1")  # set -e stops here on API errors
  if [ -n "$existing" ]; then echo "exists: $1"; return 0; fi
  jq -n --argjson org "$ORG_ID" --arg name "$1" --arg target "$2" \
      --arg mp "$3" --arg kind "$4" '{
    orgId: $org, name: $name, description: "Cloud Network Insights policy",
    monitoringEnabled: true, target: $target,
    networkMonitoring: {dualEnded: false, networkProtocol: "TCP",
                        networkPathGroupName: "Default"},
    webHttpMonitoring: (if $kind == "web" then {method: "GET",
      intervalMinutes: 5, timeoutSeconds: 60, ignoreSslValidation: false,
      followRedirects: true, assertions: [{type: "statuscode", value: "200"}]}
      else null end),
    monitoringPointRules: [{filterRule: {name: {values: [$mp], exclude: false}}}]
  }' | api -X POST --data @- "$API/monitoringPolicy" | jq -c '{id, name, target}'
  echo "created: $1"
}

# Edit below: one line per policy.
create_policy "POLICY_NAME" "TARGET" "MP_NAME" network
# list_policies
```

### AppNeta Web UI

Give these steps, filled in, when the user creates or deletes policies in the
AppNeta web UI (get `PROJECT_NUMBER` with `gcloud projects describe PROJECT_ID
--format="value(projectNumber)"`):

1.  Open the monitoring policies page that the Google Cloud console links to:
    `https://APPNETA_HOST/pvc/monitoringPolicies.html?project=PROJECT_NUMBER`.
2.  Add one policy per request: a **Network** policy with the target IP or
    host (such as `8.8.8.8`), or a **Web** policy with the full URL (such as
    `https://1.1.1.1`) and a `200` status check. Name it `POLICY_NAME` and
    choose only the Monitoring Point `MP_NAME` as its source. To delete a
    policy, delete it on the same page.
3.  Check the result with `network-paths list` and `web-paths list`.

### Proxy VM

Use this only after the user picks it (`SKILL.md` Rule 6). Their choice
approves a small billable VM and a firewall rule that allows SSH only from
Identity-Aware Proxy. The token is minted in your environment and reaches the
VM only on standard input, so never put it in a command argument, file,
startup script, metadata, or the serial console.

1.  Create the VM with outbound internet access, no service account, and `jq`,
    plus the IAP-only SSH rule:

    ```bash
    gcloud compute instances create cni-proxy --project=PROJECT_ID --zone=ZONE \
      --machine-type=e2-small --image-family=debian-12 \
      --image-project=debian-cloud --network=NETWORK --subnet=SUBNET \
      --tags=cni-proxy --no-service-account --no-scopes \
      --metadata=startup-script='export DEBIAN_FRONTEND=noninteractive; apt-get update && apt-get -o DPkg::Lock::Timeout=300 install -y jq'
    gcloud compute firewall-rules create cni-proxy-iap-ssh --project=PROJECT_ID \
      --network=NETWORK --direction=INGRESS --allow=tcp:22 \
      --source-ranges=35.235.240.0/20 --target-tags=cni-proxy
    ```

2.  Copy the filled-in script (it holds no tokens), wait up to 3 minutes for
    the startup script to install `jq` (if it's still missing, read the VM's
    serial port output and tell the user), then run the script with the token
    on standard input:

    ```bash
    gcloud compute scp WORK_DIR/cni-policies.sh cni-proxy:~ --zone=ZONE \
      --project=PROJECT_ID --tunnel-through-iap --quiet
    gcloud compute ssh cni-proxy --zone=ZONE --project=PROJECT_ID \
      --tunnel-through-iap --quiet \
      --command='for i in $(seq 1 36); do command -v jq && break; sleep 5; done; command -v jq'
    gcloud network-management network-monitoring-providers \
      generate-provider-access-token PROVIDER_ID --location=global \
      --project=PROJECT_ID \
      --gcp-access-token="$(gcloud auth print-access-token 2>/dev/null || gcloud auth application-default print-access-token)" \
      --format="value(providerAccessToken)" \
      | gcloud compute ssh cni-proxy --zone=ZONE --project=PROJECT_ID \
          --tunnel-through-iap --quiet --command='bash cni-policies.sh --auth-stdin'
    ```

3.  In your final summary, ask whether to delete the VM and its firewall rule
    or keep them for later policy changes, and delete them only after the user
    answers:

    ```bash
    gcloud compute instances delete cni-proxy --zone=ZONE --project=PROJECT_ID \
      --quiet
    gcloud compute firewall-rules delete cni-proxy-iap-ssh --project=PROJECT_ID \
      --quiet
    ```

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

## 6. Troubleshooting

-   **`401 Unauthorized`**: The provider token expired, or it was minted from a
    stale Google Cloud token. Repeat Section 1, step 3 (or rerun the script)
    once, then retry. If AppNeta still returns `401`, stop and tell the user
    their options: mint the Google Cloud token with
    `gcloud auth application-default print-access-token` instead (on hosts with
    certificate-based access, `gcloud auth print-access-token` returns a
    certificate-bound token, which exchanges into an AppNeta token that gets
    `401`), sign in again with `gcloud auth login`, or mint the Google Cloud
    token as a service account that has
    `roles/networkmanagement.CloudNetworkInsightsEditor` on the project (which
    requires `roles/iam.serviceAccountTokenCreator` on that service account).
    Never create service accounts, grant roles, or impersonate an account
    yourself.
-   **`400 Network Monitoring must be specified.`**: A Web policy needs a
    non-null `networkMonitoring` block (Section 3).
-   **Timeouts (curl exit code 28), DNS errors (6), or refused connections
    (7)**: Your environment can't reach AppNeta. Don't retry; give the user
    the three choices in Section 1, step 2.

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