Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cloud-networking-observability@skills-hub

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

Install with the gh extension
gh skills-hub install google-cloud-networking-observability

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

Download and extract to your repository:

.github/skills/google-cloud-networking-observability/

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

Skill Files (10)

SKILL.md 5.4 KB
---
name: google-cloud-networking-observability
metadata:
  version: "1.0.8"
  category: Compute
description: >-
  Investigates Google Cloud networking issues by analyzing GCP logs, metrics, and diagnostics. Use when investigating dropped network traffic, packet drops, drop reasons, VPC Flow Logs (including Private Service Connect / PSC, serverless / App Engine Direct VPC, and cost estimation), Cloud NAT, firewall or threat logs, VPN metrics/tunnels, or Connectivity Tests for path diagnostics. Don't use for generic VM management or non-observability tasks.
---

# Google Cloud Networking Observability Expert

## 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).

## 🛑 Core Directive: Results First

1. **Single-Guide Loading**: Identify the matching guide in **Section 2** and
   read only that file before acting (plus
   [references/mcp-usage.md](references/mcp-usage.md) when MCP tools are
   available in your environment).
2. **Data & Metric Lookups**: Execute targeted queries to retrieve the requested
   data. Once obtained (including `0`, `null`, or `"No traffic"`), present it
   and stop immediately. Never query a second source (e.g., comparing BigQuery
   and Monitoring) to double-check a conclusive answer.
3. **Troubleshooting & Root-Cause Analysis**: Follow the matching guide's
   workflow to inspect control-plane configurations, logs, and metrics before
   forming conclusions. Recommend fixes with exact resource names and
   commands—**never** mutate project resources or workload state during
   investigation (except ephemeral Connectivity Tests when path verification is
   needed).

## Procedures

### 1. Environment & Source Rules

- **Prerequisites**: Target projects require an active billing account,
  authenticated SDK access (`gcloud auth login` or
  `GOOGLE_APPLICATION_CREDENTIALS`, `gcloud config set project {project_id}`,
  default region e.g. `us-central1` via
  `gcloud config set compute/region {region}`; see
  [Google Cloud CLI installation](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)
  and [locations](https://docs.cloud.google.com/about/locations) — never install
  tools without explicit user approval), enabled APIs (`compute.googleapis.com`,
  `logging.googleapis.com`, `monitoring.googleapis.com`,
  `bigquery.googleapis.com`, `networkmanagement.googleapis.com`), and read roles
  (`roles/compute.networkViewer`, `roles/logging.viewer`,
  `roles/monitoring.viewer`, `roles/bigquery.jobUser`,
  `roles/bigquery.dataViewer`, or `roles/networkmanagement.admin` for
  Connectivity Tests).
- **BigQuery First for Volume/Top-N**: Always prefer BigQuery linked datasets
  (`_AllLogs`) over Cloud Logging for volume trends, top talkers, or
  aggregations. Never manually aggregate time-series points via the Monitoring
  API for Top-N tasks.
- **Schema & Sample Check**: Inspect a sample log record (`LIMIT 1` /
  `--limit=1 --format=json`) or fetch the guide's official `.md.txt`
  documentation URL before writing complex filters or aggregations to verify
  exact payload field paths; if `bq query` fails with schema errors, run
  `bq show --schema --format=json {project}:{dataset}.{table}` and
  `bq query --use_legacy_sql=false --dry_run`.
- **Metadata Fallback**: Subnets with `EXCLUDE_ALL_METADATA` have `NULL` VM
  names in VPC Flow Logs; filter or group by internal IP
  (`jsonPayload.connection.src_ip`) instead.
- **Tool Priority**: Prefer MCP servers
  ([references/mcp-usage.md](references/mcp-usage.md)) when declared in your
  tools; otherwise use `gcloud`/`bq`. Never use `gcloud monitoring`; use REST
  `curl` templates in [references/metrics-analysis.md](references/metrics-analysis.md).

### 2. Analysis Guides (Read Only the Single Matching Guide)

| Symptom or Task | Reference Guide |
| :--- | :--- |
| **VPC Flow Logs**: traffic volume, top talkers, latency, packet drops and loss rates, Private Service Connect (PSC / PSC-I), serverless workloads | [references/vpc-flow-analysis.md](references/vpc-flow-analysis.md) |
| **VPC Flow Logs Cost Estimation** | [references/vpc-flow-logs-cost-estimation.md](references/vpc-flow-logs-cost-estimation.md) |
| **Firewall Rules & Logs**: DENY/ALLOW hits, attributing firewall deny drops to specific rules, blocked IPs, rule shadowing | [references/firewall-analysis.md](references/firewall-analysis.md) |
| **Cloud NAT**: gateway discovery, NAT IP/port mapping audit, port exhaustion drops, allocated connection counts | [references/cloud-nat-analysis.md](references/cloud-nat-analysis.md) |
| **Threat Logs**: Cloud IDS / Firewall Plus high-severity alerts and top attackers | [references/threat-analysis.md](references/threat-analysis.md) |
| **Metrics & VPN**: internal/external RTT, VM throughput, packet loss, or Cloud VPN (`vpn_gateway` health, traffic, drops) | [references/metrics-analysis.md](references/metrics-analysis.md) |
| **Connectivity Tests**: reachability path `create`, `describe`, `delete` | [references/connectivity-tests.md](references/connectivity-tests.md) |

## Boundaries (CRITICAL)

- **Print SQL**: Always print generated SQL in the response.
- **Flow Analyzer Link**: For VPC Flow Log tasks, include
  [Google Cloud Console Flow Analyzer](https://console.cloud.google.com/net-intelligence/flow-analyzer).
- **First-Turn Time Math**: Compute relative time ranges (e.g., "12 hours ago")
  in the first turn.
references/
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:google-cloud-networking-observability)" \
    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:google-cloud-networking-observability)` 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:google-cloud-networking-observability)
    ```

-   **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.
cloud-nat-analysis.md 4.1 KB
# Cloud NAT Analysis Reference

Use Cloud Router control-plane inspection, Cloud NAT logs
(`compute.googleapis.com/nat_flows`), and Cloud Monitoring metrics to discover
NAT gateways, audit internal-to-external IP/port mappings, count allocated
connections, or troubleshoot port exhaustion.

## 1. Gateway Discovery & Live Control-Plane Mappings

Because Cloud NAT configurations (`nats[]`) live on the Compute `Router`
resource, discover all NAT gateways, routers, regions, and logging settings
across the project in **one command**:

```bash
gcloud compute routers list --project={project_id} --filter="nats:*" \
  --format="json(name,region.basename(),network.basename(),nats)"
```

Inspect runtime NAT status or currently allocated VM IP:port ranges directly
from the router control plane (works even when Cloud NAT logging is disabled):

```bash
gcloud compute routers get-status {router_name} --region={region} --project={project_id} --format=json
gcloud compute routers get-nat-mapping-info {router_name} --region={region} --project={project_id} --format=json
```

*Note*: `get-nat-mapping-info` shows active VM-level port-range allocations;
historical per-connection 7-tuples (`dest_ip`, exact `nat_port`, and
`allocation_status`) require `compute.googleapis.com/nat_flows` logs. (Egress
VPC Flow Logs only record `nat_gateway_details.{gateway_name,router_name,type}`,
not the external `nat_ip`/`nat_port`.)

## 2. Cloud NAT Logs (`compute.googleapis.com/nat_flows`)

-   **Resource**: `resource.type="nat_gateway"`,
    `resource.labels.{gateway_name, router_id, region, project_id}`.
-   **JSON Fields** (`jsonPayload` in Cloud Logging / `json_payload` in BigQuery
    `_AllLogs`):
    -   `connection`: `src_ip`, `src_port` (internal VM IP/port), `nat_ip`,
        `nat_port` (allocated external NAT IP/port), `dest_ip`, `dest_port`,
        `protocol`.
    -   `allocation_status`: `"OK"` (allocated) or `"DROPPED"` (port exhaustion).
    -   `endpoint`: `vm_name`, `project_id`, `region`, `zone`.
    -   `gateway_identifiers`: `gateway_name`, `router_name`, `region`.

**Cloud Logging (`list_log_entries` MCP or `gcloud logging read`)** — latest
mapping entry (append `AND jsonPayload.allocation_status="DROPPED"` for drops):

```bash
gcloud logging read 'resource.type="nat_gateway" AND logName="projects/{project_id}/logs/compute.googleapis.com%2Fnat_flows" AND timestamp>="{start_time}"' \
  --project={project_id} --limit=1 --order=desc --format=json --quiet
```

**BigQuery (`execute_sql_readonly` MCP or `bq query`)** — connection counts:

```bash
bq query --use_legacy_sql=false --format=json --project_id={project_id} '
SELECT
  JSON_VALUE(json_payload.endpoint.vm_name) AS vm_name,
  JSON_VALUE(json_payload.connection.src_ip) AS internal_ip,
  JSON_VALUE(json_payload.connection.nat_ip) AS external_nat_ip,
  JSON_VALUE(json_payload.allocation_status) AS allocation_status,
  COUNT(*) AS connection_count
FROM `{project_id}.{dataset_id}._AllLogs`
WHERE
  log_name LIKE "%/logs/compute.googleapis.com%2Fnat_flows"
  AND timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 24 HOUR)
GROUP BY 1, 2, 3, 4
ORDER BY connection_count DESC
LIMIT 20
'
```

## 3. Cloud NAT Monitoring Metrics (`list_timeseries` MCP or REST `curl`)

-   **Allocated New Connections**:
    `compute.googleapis.com/nat/new_connections_count` (`gce_instance`, `DELTA`
    INT64; labels: `nat_gateway_name`, `router_id`) or
    `router.googleapis.com/nat/new_connections_count` (`nat_gateway`, `DELTA`
    INT64). Sum over window with `ALIGN_SUM` + `REDUCE_SUM`.
-   **Dropped Packets & Allocation Failures**:
    `router.googleapis.com/nat/dropped_sent_packets_count` (`nat_gateway`,
    `DELTA` INT64, `metric.labels.reason`: `OUT_OF_RESOURCES`,
    `ENDPOINT_INDEPENDENCE_CONFLICT`),
    `compute.googleapis.com/nat/dropped_sent_packets_count` (`gce_instance`), and
    `router.googleapis.com/nat/nat_allocation_failed` (`nat_gateway`, `GAUGE`
    BOOL).
-   **Active Connections & Port Usage**:
    `compute.googleapis.com/nat/open_connections` and
    `compute.googleapis.com/nat/port_usage` (`gce_instance`, `GAUGE` INT64).

## Reference Documentation

-   [Cloud NAT logs and metrics](https://docs.cloud.google.com/nat/docs/monitoring.md.txt)
connectivity-tests.md 2.1 KB
# Connectivity Tests Reference

Use Network Intelligence Center Connectivity Tests to verify reachability and
identify firewall or routing blocks along a network path.

## Critical Verification & Cleanup Rules

1.  **Instance State Verification**: Always check whether the source and
    destination VM instances are `RUNNING` (a static `REACHABLE` configuration
    trace does not mean live traffic will succeed if a VM is `TERMINATED` or
    `STOPPED`). Also resolve the source VM's `{zone}` if not provided:
    ```bash
    gcloud compute instances list --project={project_id} \
      --filter="name=({src_vm})" --format="table(name,zone.basename(),status,networkInterfaces[0].networkIP)"
    ```
2.  **Mandatory Test Deletion**: When creating a temporary Connectivity Test,
    you **MUST** delete the test resource as your final step after retrieving
    results.

## Execution Workflow

-   **MCP Tools** (when declared): `create_connectivity_test` →
    `get_connectivity_test` → `delete_connectivity_test`.
-   **CLI (`gcloud`)**:

```bash
# 1. Create and run reachability analysis (blocks until initial analysis completes unless --async is set)
gcloud network-management connectivity-tests create {test_name} \
  --source-instance=projects/{project_id}/zones/{zone}/instances/{src_vm} \
  --destination-ip-address={dest_ip} \
  --destination-port={port} \
  --protocol=TCP \
  --project={project_id}

# 2. Inspect reachabilityDetails.result (REACHABLE, UNREACHABLE, AMBIGUOUS, UNDETERMINED) and trace steps
gcloud network-management connectivity-tests describe {test_name} \
  --project={project_id} --format=json

# 3. Clean up the temporary test resource
gcloud network-management connectivity-tests delete {test_name} \
  --project={project_id} --quiet
```

*(For VM-to-VM destination by name rather than IP, replace
`--destination-ip-address={dest_ip}` with
`--destination-instance=projects/{project_id}/zones/{dest_zone}/instances/{dest_vm}`.)*

## Reference Documentation

-   [Running Connectivity Tests](https://docs.cloud.google.com/network-intelligence-center/docs/connectivity-tests/how-to/running-connectivity-tests.md.txt)
firewall-analysis.md 3.0 KB
# Firewall Rule Logging Analysis Reference

Use Firewall Rules Logging (`compute.googleapis.com/firewall`) to rank active
firewall rules, attribute firewall deny drops to specific rules, and identify
blocked source/destination IPs.

## 1. Key Fields

-   **Monitored Resource**: `resource.type="gce_subnetwork"` (or
    `gce_network`/`gce_firewall_policy` for hierarchical/network policies).
-   **JSON Payload Fields** (`jsonPayload` in Cloud Logging / `json_payload` in
    BigQuery `_AllLogs`):
    -   `disposition`: `"ALLOWED"` or `"DENIED"`.
    -   `rule_details.reference`: Firewall rule identifier (e.g.,
        `network:{vpc}/firewall:{rule_name}`).
    -   `rule_details.action`: `"ALLOW"` or `"DENY"`.
    -   `rule_details.direction`: `"INGRESS"` or `"EGRESS"`.
    -   `rule_details.priority`: Rule priority integer.
    -   `connection`: `src_ip`, `src_port`, `dest_ip`, `dest_port`, `protocol`.
    -   `instance`: `vm_name`, `project_id`, `region`, `zone`.

## 2. Aggregate Rule Activity & Denied Traffic (BigQuery)

Prefer BigQuery (`execute_sql_readonly` MCP or `bq query`) for hit counts, top
active rules, and firewall deny attribution:

```bash
bq query --use_legacy_sql=false --format=json --project_id={project_id} '
SELECT
  JSON_VALUE(json_payload.rule_details.reference) AS rule_reference,
  JSON_VALUE(json_payload.rule_details.action) AS action,
  COUNT(*) AS hit_count,
  COUNTIF(
    JSON_VALUE(json_payload.rule_details.action) = "DENY"
    OR JSON_VALUE(json_payload.disposition) = "DENIED"
  ) AS deny_count,
  ARRAY_AGG(
    DISTINCT IF(
      JSON_VALUE(json_payload.rule_details.action) = "DENY"
      OR JSON_VALUE(json_payload.disposition) = "DENIED",
      JSON_VALUE(json_payload.connection.src_ip),
      NULL
    ) IGNORE NULLS LIMIT 10
  ) AS blocked_src_ips
FROM `{project_id}.{dataset_id}._AllLogs`
WHERE
  log_name LIKE "%/logs/compute.googleapis.com%2Ffirewall"
  AND timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR)
GROUP BY 1, 2
ORDER BY hit_count DESC
LIMIT 10
'
```

*(Add `AND (JSON_VALUE(json_payload.rule_details.action) = "DENY"`
`OR JSON_VALUE(json_payload.disposition) = "DENIED")` to `WHERE` when querying
exclusively for blocking rules.)*

## 3. Exploratory Log Lookup (Cloud Logging)

Use `list_log_entries` MCP or `gcloud logging read` for recent samples or when
BigQuery log sinks are not linked:

```text
logName="projects/{project_id}/logs/compute.googleapis.com%2Ffirewall"
jsonPayload.rule_details.action="DENY"
```

```bash
gcloud logging read 'logName="projects/{project_id}/logs/compute.googleapis.com%2Ffirewall" AND jsonPayload.rule_details.action="DENY" AND timestamp>="{start_time}"' \
  --project={project_id} --limit=20 --format=json --quiet
```

## Reference Documentation

-   [VPC Firewall Rules Logging overview](https://docs.cloud.google.com/firewall/docs/vpc-firewall-rules-logging-overview.md.txt)
-   [Use VPC Firewall Rules Logging](https://docs.cloud.google.com/firewall/docs/manage-vpc-firewall-rules-logging.md.txt)
mcp-usage.md 2.6 KB
# MCP Server Usage Reference

This document describes the Model Context Protocol (MCP) servers used for GCP
networking observability.

## BigQuery MCP

BigQuery is supported by a remote MCP server that provides tools for automated
data management and analysis.

### Key Tools

-   **list_dataset_ids**: List BigQuery dataset IDs in a project.
-   **list_table_ids**: List table IDs in a BigQuery dataset.
-   **get_table_info**: Get schema and metadata for a specific table.
-   **execute_sql_readonly**: Run `SELECT` queries to analyze logs (such as, VPC Flow,
    Firewall) stored in BigQuery. This is the preferred tool for high-volume
    aggregations and trend analysis.

### Usage Pattern

1.  Use `list_dataset_ids` to find the logging dataset (for example,
    `_AllLogs`).
2.  Use `list_table_ids` to find the relevant log table.
3.  Use `get_table_info` to verify field names (for example, `jsonPayload`
    versus `json_payload`).
4.  Use `execute_sql_readonly` for the final analysis.

## Cloud Logging MCP

The Cloud Logging MCP server provides access to log entries across various
Google Cloud resources.

### Key Tools

-   **list_log_entries**: Search and retrieve log entries using advanced
    filters.
-   **list_log_names**: Discover available logs in a project.

### Usage Pattern

-   Use for quick, real-time identification of recent events or exploratory
    analysis where BigQuery datasets are not linked.
-   Use specific filters for `resource.type` and `logName` to narrow down
    results.

## NetworkManagement MCP

The Network Management MCP server allows for reachability analysis and path
diagnostics.

### Key Tools

-   **create_connectivity_test**: Start a simulated packet path analysis between
    two endpoints.
-   **get_connectivity_test**: Poll for the results of a running test.
-   **delete_connectivity_test**: Cleanup the test resource after analysis is
    complete.

### Usage Pattern

-   Use when static path analysis is needed to identify firewall or routing
    blocks.
-   **CRITICAL**: Always delete the test resource after retrieving the result.

## Cloud Monitoring MCP

The Cloud Monitoring MCP server provides access to Cloud Monitoring metrics and
time-series data.

### Key Tools

-   **list_metric_descriptors**: Discover available metrics using filters.
-   **list_timeseries**: Retrieve aggregated data points for performance
    analysis (such as RTT or throughput).

### Usage Pattern

-   Use for analyzing performance trends, packet loss, and latency.
-   Prefer `ALIGN_MEAN` or `ALIGN_PERCENTILE_50` for distribution metrics like
    RTT to simplify parsing.
metrics-analysis.md 4.4 KB
# Networking Metrics Reference

Use Cloud Monitoring (`list_timeseries` MCP or the v3 REST API via `curl`) to
analyze network latency (RTT), VM throughput, packet drops, and Cloud VPN
gateway health.

## 1. Standard Networking & Cloud VPN Metrics

Use these monitored resource types, metric kinds, labels, and aligners directly
without querying `metricDescriptors` first:

-   **Internal & External VM Latency (`resource.type="gce_instance"`)**:
    -   `networking.googleapis.com/vm_flow/rtt` (VM-to-VM within Google Cloud)
        and `networking.googleapis.com/vm_flow/external_rtt` (internet traffic)
        — `DELTA` `DISTRIBUTION`.
    -   **Region Scoping & Peer Labels**: Local VM zone is
        `resource.labels.zone` (filter a region with
        `resource.labels.zone = starts_with("{region}-")`); peer location is
        `metric.labels.remote_region` and `metric.labels.remote_zone`.
    -   **Alignment**: Always align `DISTRIBUTION` RTT metrics with
        `perSeriesAligner=ALIGN_PERCENTILE_50` (and optional
        `crossSeriesReducer=REDUCE_MEAN` or `REDUCE_PERCENTILE_50` when
        aggregating across VMs in a region) to obtain a scalar numeric latency.
-   **Cross-Zone Baseline Latency & Active Probing (`networking.googleapis.com`)**:
    -   `networking.googleapis.com/all_gcp/vm_traffic/zone_pair_median_rtt`
        (`resource.type="networking.googleapis.com/Location"`, `GAUGE` `DOUBLE`
        in `ns`, `ALIGN_MEAN`; labels `remote_region`, `remote_zone`,
        `protocol`) — Google Cloud baseline VM-to-VM median RTT per zone pair.
    -   `networking.googleapis.com/cloud_netslo/active_probing/probe_count`
        (`resource.type="gce_zone_network_health"`, `DELTA` `INT64`,
        `ALIGN_SUM`; labels `remote_zone`, `remote_region`,
        `remote_location_type`, `protocol`, `result`).
-   **VM Throughput & Packets (`resource.type="gce_instance"`)**:
    -   `compute.googleapis.com/instance/network/sent_bytes_count`,
        `received_bytes_count`, `sent_packets_count`, `received_packets_count`
        — `DELTA` `INT64` (`ALIGN_SUM` or `ALIGN_RATE`).
-   **Cloud VPN Gateways & Tunnels (`resource.type="vpn_gateway"`)**:
    -   **Gateway Discovery**:
        ```bash
        gcloud compute vpn-gateways list --project={project_id}
        gcloud compute target-vpn-gateways list --project={project_id}
        gcloud compute vpn-tunnels list --project={project_id}
        ```
    -   **Labels**: `resource.labels.{gateway_id, region, project_id}`,
        `metric.labels.{gateway_name, tunnel_name}`.
    -   **Tunnel Health**: `vpn.googleapis.com/tunnel_established` (`GAUGE`
        `DOUBLE`, `ALIGN_MEAN`; values `> 0` indicate an established tunnel).
    -   **Traffic Volume**: `vpn.googleapis.com/network/sent_bytes_count` and
        `vpn.googleapis.com/network/received_bytes_count` (`DELTA` `INT64`,
        `ALIGN_SUM` + `REDUCE_SUM` grouped by `metric.labels.gateway_name` or
        `metric.labels.tunnel_name`).
    -   **Packet Drops**:
        `vpn.googleapis.com/network/dropped_sent_packets_count` and
        `vpn.googleapis.com/network/dropped_received_packets_count` (`DELTA`
        `INT64`, `ALIGN_SUM` + `REDUCE_SUM`).

## 2. REST API Query Pattern (`curl`)

When Cloud Monitoring MCP (`list_timeseries`) is unavailable, query the v3 REST
API directly (never use `gcloud monitoring`):

```bash
curl -s -G \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  "https://monitoring.googleapis.com/v3/projects/{project_id}/timeSeries" \
  --data-urlencode 'filter=metric.type="{metric_type}" AND resource.type="{resource_type}"' \
  --data-urlencode "interval.startTime={start_time}" \
  --data-urlencode "interval.endTime={end_time}" \
  --data-urlencode "aggregation.alignmentPeriod=3600s" \
  --data-urlencode "aggregation.perSeriesAligner=ALIGN_PERCENTILE_50"
```

## 3. Dynamic Metric Discovery (Unlisted Metrics Only)

Only query `metricDescriptors` (`list_metric_descriptors` MCP or REST `curl`)
when investigating a metric not listed above:

```bash
curl -s -G \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  "https://monitoring.googleapis.com/v3/projects/{project_id}/metricDescriptors" \
  --data-urlencode 'filter=metric.type=starts_with("{prefix}")' \
  | jq -r '.metricDescriptors[] | "\(.type) (\(.metricKind)/\(.valueType)): \(.description)"'
```

## Reference Documentation

-   [Cloud VPN logs and metrics](https://docs.cloud.google.com/network-connectivity/docs/vpn/how-to/viewing-logs-metrics.md.txt)
threat-analysis.md 4.8 KB
# Threat Log Analysis Reference

Use Firewall Threat Logs and Cloud IDS logs to identify, analyze, and
troubleshoot security incidents in your VPC network.

## Table of Contents

-   [1. View Threat Alerts (Cloud Logging)](#1-view-threat-alerts-cloud-logging):
    Lines 16-38
-   [2. Aggregate Threat Trends (BigQuery)](#2-aggregate-threat-trends-bigquery):
    Lines 40-89
-   [3. CLI Fallback (gcloud and bq)](#3-cli-fallback-gcloud-and-bq): Lines
    91-122
-   [4. Key Fields](#4-key-fields): Lines 124-134

## 1. View Threat Alerts (Cloud Logging)

Use `list_log_entries` (when Cloud Logging MCP is declared) or `gcloud logging
read` for quick identification of recent alerts. Search **both** Cloud Firewall
Plus and Cloud IDS threat log sources:

```text
logName:(
"projects/{project_id}/logs/networksecurity.googleapis.com%2Ffirewall_threat" OR
"projects/{project_id}/logs/ids.googleapis.com%2Fthreat")
```

To filter for high-severity threats (`HIGH` or `CRITICAL`):

```text
logName:(
"projects/{project_id}/logs/networksecurity.googleapis.com%2Ffirewall_threat" OR
"projects/{project_id}/logs/ids.googleapis.com%2Fthreat")
jsonPayload.threatDetails.severity=("HIGH" OR "CRITICAL")
```

*(Append `jsonPayload.action="DENY"` when filtering specifically for blocked
threats.)*

## 2. Aggregate Threat Trends (BigQuery)

Use `execute_sql_readonly` (when BigQuery MCP is declared) or `bq query` for
multi-day audits and top attacker analysis.

**Note**: In BigQuery `_AllLogs`, the top-level column is `json_payload`
(`snake_case`), while nested threat log JSON keys retain `camelCase` (e.g.,
`threatDetails`, `clientIp`, `serverIp`, `serverPort`).

```sql
SELECT
  timestamp,
  JSON_VALUE(json_payload.threatDetails.threat) AS threat_name,
  JSON_VALUE(json_payload.threatDetails.severity) AS severity,
  JSON_VALUE(json_payload.threatDetails.category) AS category,
  JSON_VALUE(json_payload.action) AS action,
  JSON_VALUE(json_payload.connection.clientIp) AS src_ip,
  JSON_VALUE(json_payload.connection.serverIp) AS dest_ip,
  JSON_VALUE(json_payload.connection.serverPort) AS dest_port,
  JSON_VALUE(json_payload.threatDetails.description) AS description
FROM `{project_id}.{dataset_id}._AllLogs`
WHERE
  log_id IN (
    'networksecurity.googleapis.com/firewall_threat',
    'ids.googleapis.com/threat'
  )
  AND JSON_VALUE(json_payload.threatDetails.severity) IN ('HIGH', 'CRITICAL')
  AND timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
ORDER BY timestamp DESC
LIMIT 20
```

To rank top attacker IPs:

```sql
SELECT
  JSON_VALUE(json_payload.connection.clientIp) AS attacker_ip,
  COUNT(*) AS attack_count,
  ARRAY_AGG(DISTINCT JSON_VALUE(json_payload.threatDetails.threat) LIMIT 5) AS sample_threats
FROM `{project_id}.{dataset_id}._AllLogs`
WHERE
  log_id IN (
    'networksecurity.googleapis.com/firewall_threat',
    'ids.googleapis.com/threat'
  )
  AND timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
GROUP BY 1
ORDER BY attack_count DESC
LIMIT 10
```

## 3. CLI Fallback (gcloud and bq)

**View High-Severity Threat Alerts (`gcloud`)**:

```bash
gcloud logging read 'logName:("projects/{project_id}/logs/networksecurity.googleapis.com%2Ffirewall_threat" OR "projects/{project_id}/logs/ids.googleapis.com%2Fthreat") AND jsonPayload.threatDetails.severity=("HIGH" OR "CRITICAL") AND timestamp>="{start_time}"' \
  --project={project_id} --limit=20 --format=json --quiet
```

**Aggregate High-Severity Threat Trends (`bq`)**:

```bash
bq query --use_legacy_sql=false --format=json --project_id={project_id} '
SELECT
  timestamp,
  JSON_VALUE(json_payload.threatDetails.threat) AS threat_name,
  JSON_VALUE(json_payload.threatDetails.severity) AS severity,
  JSON_VALUE(json_payload.threatDetails.category) AS category,
  JSON_VALUE(json_payload.action) AS action,
  JSON_VALUE(json_payload.connection.clientIp) AS src_ip,
  JSON_VALUE(json_payload.connection.serverIp) AS dest_ip,
  JSON_VALUE(json_payload.connection.serverPort) AS dest_port
FROM `{project_id}.{dataset_id}._AllLogs`
WHERE
  log_id IN ("networksecurity.googleapis.com/firewall_threat",
             "ids.googleapis.com/threat")
  AND JSON_VALUE(json_payload.threatDetails.severity) IN ("HIGH", "CRITICAL")
  AND timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
ORDER BY timestamp DESC
LIMIT 20
'
```

## 4. Key Fields

-   `jsonPayload.threatDetails.threat`: Human-readable threat name.
-   `jsonPayload.threatDetails.severity`: `CRITICAL`, `HIGH`, `MEDIUM`, `LOW`,
    `INFORMATIONAL`.
-   `jsonPayload.threatDetails.category`: Threat category.
-   `jsonPayload.action`: `"ALLOW"`, `"DENY"`, or `"ALERT"`.
-   `jsonPayload.connection.clientIp`: Source IP.
-   `jsonPayload.connection.serverIp` / `serverPort`: Destination IP and port.
-   `jsonPayload.threatDetails.cves`: Associated CVE IDs.
-   `jsonPayload.threatDetails.description`: Attack payload details.
vpc-flow-analysis.md 6.2 KB
# VPC Flow Analysis Reference

Use VPC Flow Logs to analyze traffic volume, top talkers, latency, and packet
drops for various Cloud products such as PSC, serverless workloads, and others.

## Table of Contents

-   [1. Querying VPC Flow Logs (BigQuery and Cloud Logging)](#1-querying-vpc-flow-logs-bigquery-and-cloud-logging):
    Lines 20-65
-   [2. Core, Instance, Subnet, Latency and Drop Fields](#2-core-instance-subnet-latency-and-drop-fields):
    Lines 67-88
-   [3. Packet Drops Analysis](#3-packet-drops-analysis): Lines 90-98
-   [4. Private Service Connect (PSC) Analysis](#4-private-service-connect-psc-analysis):
    Lines 100-110
-   [5. Serverless Workloads (Direct VPC Egress)](#5-serverless-workloads-direct-vpc-egress):
    Lines 112-121
-   [6. Flow Analyzer and Reference Documentation](#6-flow-analyzer-and-reference-documentation):
    Lines 123-132

## 1. Querying VPC Flow Logs (BigQuery and Cloud Logging)

Always include **both** legacy subnet (`compute.googleapis.com/vpc_flows`) and
Network Management (`networkmanagement.googleapis.com/vpc_flows`) log names.
Prefer BigQuery (`_AllLogs`) for volume/Top-N aggregations and Cloud Logging for
small exploratory lookups.

-   **Column Naming**: In BigQuery `_AllLogs`, the top-level JSON column is
    `json_payload` (`snake_case`); in Cloud Logging filters, it is `jsonPayload`
    (`camelCase`). Nested VPC Flow Log fields are `snake_case` in both.

### BigQuery (`execute_sql_readonly` MCP or `bq query`)

```bash
bq query --use_legacy_sql=false --format=json --project_id={project_id} '
SELECT
  JSON_VALUE(json_payload.src_instance.vm_name) AS src_vm,
  JSON_VALUE(json_payload.connection.src_ip) AS src_ip,
  JSON_VALUE(json_payload.connection.dest_ip) AS dest_ip,
  SUM(CAST(JSON_VALUE(json_payload.bytes_sent) AS INT64)) AS total_bytes_sent
FROM `{project_id}.{dataset_id}._AllLogs`
WHERE
  log_name IN (
    "projects/{project_id}/logs/compute.googleapis.com%2Fvpc_flows",
    "projects/{project_id}/logs/networkmanagement.googleapis.com%2Fvpc_flows"
  )
  AND JSON_VALUE(json_payload.reporter) = "SRC"
  AND timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR)
GROUP BY 1, 2, 3
ORDER BY total_bytes_sent DESC
LIMIT 10
'
```

### Cloud Logging (`list_log_entries` MCP or `gcloud logging read`)

```text
(logName="projects/{project_id}/logs/compute.googleapis.com%2Fvpc_flows" OR
 logName="projects/{project_id}/logs/networkmanagement.googleapis.com%2Fvpc_flows")
resource.type="gce_subnetwork"
```

```bash
gcloud logging read '(logName="projects/{project_id}/logs/compute.googleapis.com%2Fvpc_flows" OR logName="projects/{project_id}/logs/networkmanagement.googleapis.com%2Fvpc_flows") AND resource.type="gce_subnetwork" AND timestamp>="{start_time}"' \
  --project={project_id} --limit=10 --format=json --quiet
```

## 2. Core, Instance, Subnet, Latency and Drop Fields

-   **5-Tuple (`connection`)**: `src_ip`, `src_port`, `dest_ip`, `dest_port`,
    `protocol` (`6` = TCP, `17` = UDP, `1` = ICMP).
-   **Volume & Direction**: `bytes_sent`, `packets_sent` (string-encoded `INT64`
    in JSON; `CAST(JSON_VALUE(...) AS INT64)`), `reporter` (`"SRC"` or `"DEST"`
    — filter to one side when summing traffic between internal VMs to avoid
    double-counting).
-   **VM Instance Metadata (`src_instance` / `dest_instance`)**: `vm_name`,
    `project_id`, `region`, `zone`. (`NULL` when subnet metadata is
    `EXCLUDE_ALL_METADATA`; fall back to `connection.src_ip` / `dest_ip`.)
-   **VPC & Subnetwork Metadata**: `src_vpc` / `dest_vpc` (`vpc_name`,
    `subnetwork_name`, `subnetwork_region`, `project_id`), plus
    `resource.labels.{subnetwork_name, subnetwork_id, location}` on
    `resource.type="gce_subnetwork"`.
-   **Latency (RTT)**: Prefer `round_trip_time.median_msec` (`DOUBLE`,
    sub-millisecond precision across TCP and Falcon); `rtt_msec` (`INT64`, whole
    ms) is TCP-only.
-   **Packet Drops**: `disposition` (`"DROPPED"`), `drop_reason`,
    `packets_dropped`, `bytes_dropped`, `throughput_inclusion` (`"INCLUDED"`
    when `packets_sent` / `bytes_sent` already include dropped traffic;
    `"EXCLUDED"` when dropped traffic is counted separately).

## 3. Packet Drops Analysis

VPC Flow Logs record dropped packet volume, drop reasons, dropped packet/byte
counters, and `throughput_inclusion` (check whether dropped traffic is already
included in `packets_sent` / `bytes_sent` before combining counters).

-   **Firewall Deny Attribution**: VPC Flow Logs report firewall drops without
    naming the specific rule. To attribute denies to specific firewall rules,
    query **Firewall Rules Logging** (`compute.googleapis.com/firewall`).

## 4. Private Service Connect (PSC) Analysis

VPC Flow Logs annotate Private Service Connect (PSC) traffic across endpoints,
service attachments, and PSC interfaces (PSC-I), recording the reporting side
(consumer or producer), endpoint/attachment metadata, connection IDs, network
attachments, and producer project or service class metadata.

-   **Cross-Project Correlation**: Producer-side flow logs include the
    consumer's pre-NAT 5-tuple annotation alongside the local connection,
    supporting correlation across consumer and producer logs via the shared
    connection ID or consumer connection annotation.

## 5. Serverless Workloads (Direct VPC Egress)

VPC Flow Logs annotate serverless workloads using Direct VPC egress (such as
Cloud Run and App Engine), capturing workload-specific metadata on source or
destination.

-   **Dynamic IP Allocation**: Serverless instances dynamically allocate IP
    addresses from the VPC subnet pool. Rather than filtering by static IP
    addresses, identify serverless traffic using the serverless workload
    metadata annotations.

## 6. Flow Analyzer and Reference Documentation

-   **Visual Analysis**: Include
    [Google Cloud Console Flow Analyzer](https://console.cloud.google.com/net-intelligence/flow-analyzer)
    in VPC Flow Log responses for interactive flow visualization.
-   **Record Schema Discovery**: For exact nested field paths (such as packet
    drops, PSC endpoints/interfaces, or serverless metadata), inspect a sample
    log record (`LIMIT 1` / `--limit=1`) or search/fetch the official public
    documentation (e.g., via `curl -sL`):
    [VPC Flow Logs record format](https://docs.cloud.google.com/vpc/docs/about-flow-logs-records.md.txt)
vpc-flow-logs-cost-estimation.md 11.9 KB
# VPC Flow Logs Cost Estimation Reference

Use this reference to estimate the monthly cost of VPC Flow Logs across
Subnetworks, VPCs, or entire Projects. This logic implements the cost estimation
calculations for VPC Flow Logs using the standard tiered pricing model.

## Table of Contents

-   [Agent Instructions](#agent-instructions): Lines 22-33
-   [Step 1: Scope and Capabilities (Boundaries)](#step-1-scope-and-capabilities-boundaries):
    Lines 37-67
-   [Step 2: Configuration Defaults](#step-2-configuration-defaults): Lines
    71-78
-   [Step 3: Resource Resolution (Discover Target Subnets)](#step-3-resource-resolution-discover-target-subnets):
    Lines 82-138
-   [Step 4: Retrieve Metrics (Batch Query)](#step-4-retrieve-metrics-batch-query):
    Lines 142-215
-   [Step 5: Cost Calculations (CLI Calculator)](#step-5-cost-calculations-cli-calculator):
    Lines 219-293
-   [Step 6: Format Report](#step-6-format-report): Lines 297-338

## Agent Instructions

When a user requests a cost estimation, the agent MUST follow this procedure
step-by-step.

> [!IMPORTANT] **In-Memory Execution Only**:
>
> -   Do not create persistent `.py`, `.sh`, or `.json` files in the working
>     directory.
> -   Run `gcloud` and `curl` directly, parse JSON responses in-memory with
>     `jq` or `python3 -c`, and format the final markdown report in your
>     response.

---

### Step 1: Scope and Capabilities (Boundaries)

Before starting, validate that the request is supported.

> [!IMPORTANT] **Supported Scopes**: Subnetworks, VPC Networks, or the entire
> GCP Project.

-   **ALWAYS** reject cost estimation requests for Cloud VPN, Cloud
    Interconnect, or Organization-level configurations, and use the standardized
    refusal response.
-   **ALWAYS** show your step-by-step mathematical calculations in the final
    cost estimation report to ensure transparency and allow manual verification.

> **UNSUPPORTED Features & Scopes (Strictly Reject)**:
>
> -   Cloud VPN (VPN Tunnels)
> -   Cloud Interconnect (Interconnect attachments)
> -   Organization-level configurations
> -   Custom log aggregation intervals (other than default 5 seconds)
> -   Custom metadata fields
> -   Enterprise or Committed Use Discounts (estimates must use standard list
>     prices only)
>
> If the user requests estimation for an unsupported feature or resource,
> decline immediately without running `gcloud` or Monitoring API queries,
> substituting the unsupported feature or resource name in the response (e.g.,
> `Cloud VPN`, `Cloud Interconnect`, `Organization`):
>
> ```text
> I'm sorry, {feature_resource} is not supported. I only support estimation for Subnets, VPCs, or Projects.
> ```

---

### Step 2: Configuration Defaults

If not specified by the user, use these default parameters:

-   **Sampling Rate**: 100% (`1.0` multiplier).
-   **Metadata**: Include Metadata (`True`).
    -   *If the user explicitly requests "No Metadata" or "Exclude Metadata",
        set Metadata to `False`.*

---

### Step 3: Resource Resolution (Discover Target Subnets)

Resolve the target scope to identify the subnetworks we need to estimate and get
the **total count** of subnetworks in that scope (needed for the inactive count
in the report).

Use `gcloud` based on the scope:

#### Step 3.A: Subnetwork Scope (User specified a subnet)

If the user specified a subnet, but did not provide the VPC or Region, ask them
for clarification using the Ambiguity response:

```text
I found multiple matches for {subnet_name}. Please specify the Region or VPC to continue.
```

Once all details are known, describe the subnet to verify it exists and get its
ID:

```bash
gcloud compute networks subnets describe {subnet_name} --region={region} --project={project_id} --format="json(name, id, region, network)"
```

*If not found, immediately respond with:*
`"I was unable to find {subnet_name}. Please verify the name and try again."`

-   **Total Subnets Count**: 1

#### Step 3.B: VPC Scope (User specified a VPC)

Find all subnetworks in the VPC and get their details:

```bash
gcloud compute networks subnets list --filter="network:https://www.googleapis.com/compute/v1/projects/{project_id}/global/networks/{vpc_name}" --project={project_id} --format="json(name, id, region, network)"
```

*If 0 subnetworks are found, immediately respond with:*
`"I found no subnets for {vpc_name}. Nothing to estimate."`

-   **Total Subnets Count**: Count the number of subnetworks returned in this
    list.

#### Step 3.C: Project Scope (User specified the entire project)

Find all subnetworks in the project and get their details:

```bash
gcloud compute networks subnets list --project={project_id} --format="json(name, id, region, network)"
```

*If 0 subnetworks are found, immediately respond with:*
`"I found no subnets for {project_id}. Nothing to estimate."`

-   **Total Subnets Count**: Count the number of subnetworks returned in this
    list. Use this list to group the active vs inactive subnets by their VPC
    later in the report.

---

### Step 4: Retrieve Metrics (Batch Query)

To avoid per-subnet API quota exhaustion and high latency on large projects, do
**not** query the Monitoring API in a loop. Instead, run one project-wide batch
query and filter the results in-memory.

#### Step 4.A: Calculate Time Window (Last 30 Days)

Use the terminal to calculate the RFC 3339 timestamps for 30 days ago and now:

```bash
project_id={project_id}
end_time=$(date -u +%Y-%m-%dT%H:%M:%SZ)
start_time=$(date -u -d '30 days ago' +%Y-%m-%dT%H:%M:%SZ)
```

#### Step 4.B: Execute Batch Query

Query the predicted log count for **all** subnetworks in the project in a single
call, grouping by subnetwork. Format the output as clean JSON lines for easy
reading:

```bash
URL="https://monitoring.googleapis.com/v3/projects/${project_id}/timeSeries?filter=metric.type%3D%22networking.googleapis.com/vpc_flow/predicted_max_vpc_flow_logs_count%22%20AND%20resource.type%3D%22gce_subnetwork%22&interval.startTime=${start_time}&interval.endTime=${end_time}&aggregation.alignmentPeriod=2592000s&aggregation.perSeriesAligner=ALIGN_SUM&aggregation.crossSeriesReducer=REDUCE_SUM&aggregation.groupByFields=resource.labels.subnetwork_name&aggregation.groupByFields=resource.labels.subnetwork_id&aggregation.groupByFields=resource.labels.location"

RESPONSE=$(curl -s -H "Authorization: Bearer $(gcloud auth print-access-token 2>/dev/null)" "$URL")
if echo "$RESPONSE" | grep -q "401"; then
  RESPONSE=$(curl -s -H "Authorization: Bearer $(gcloud auth application-default print-access-token 2>/dev/null)" "$URL")
fi

printf '%s\n' "$RESPONSE" | python3 -c '
import sys, json
try:
    data = json.load(sys.stdin)
    if "error" in data:
        print("API_ERROR:", json.dumps(data["error"]), file=sys.stderr)
        sys.exit(1)
    for ts in data.get("timeSeries", []):
        labels = ts.get("resource", {}).get("labels", {})
        points = ts.get("points", [])
        if points:
            val_dict = points[0].get("value", {})
            logs = val_dict.get("doubleValue", val_dict.get("int64Value", 0))
            print(json.dumps({
                "name": labels.get("subnetwork_name"),
                "id": labels.get("subnetwork_id"),
                "region": labels.get("location"),
                "logs": int(logs)
            }))
except Exception as e:
    print(f"Error: {e}", file=sys.stderr)
    sys.exit(1)
'
```

*If the `curl` command returns an API error (e.g. `UNAUTHENTICATED`,
`ACCESS_TOKEN_TYPE_UNSUPPORTED`), immediately respond with:*
`"ERROR: Monitoring API Request failed. Please check your token/permissions."`
*and STOP. Do not proceed to cost calculation.*

This will return a list of active subnetworks (those with traffic). If a
subnetwork is not in this list, its log count is `0`.

#### Step 4.C: Filter Results In-Context

Match the active subnetworks from the query output against your target scope
(from Step 3):

-   **Project Scope**: Use all subnetworks returned by the query.
-   **VPC Scope**: Keep only the subnetworks from the query whose `id` or `name`
    matches the subnetworks list resolved for the VPC in Step 3.
-   **Subnetwork Scope**: Keep only the single subnetwork specified by the user.

Any target subnetwork not present in the query output has `0` logs (No traffic).

---

### Step 5: Cost Calculations (CLI Calculator)

To prevent arithmetic errors, you **MUST** use `python3 -c` as an in-memory
calculator to perform all mathematical steps.

#### Step 5.A: Determine Parameters

-   **Sampling Rate**: $S$ (e.g., `1.0` for 100%, `0.5` for 50%)
-   **Bytes per Log**: $B = 1418$ (if Metadata=True) else $B = 542$ (if
    Metadata=False)

#### Step 5.B: Calculate Subnetwork Volume

For each active subnetwork in your filtered list, calculate the volume in GB:

```bash
python3 -c "print(({L_raw} * {S} * {B}) / (1024**3))"
```

Keep track of these individual $V_{subnet}$ values for the report breakdown.

#### Step 5.C: Calculate Aggregate Totals & Tiered Pricing

Sum all effective logs ($L_{raw} \times S$) to get $L_{total}$. Sum all
$V_{subnet}$ to get $V_{total}$.

Run the following Python command (filling in $V_{total}$ and $L_{total}$) to
calculate the monthly tiered generation and Cloud Logging storage costs:

```bash
python3 -c '
total_gb = {V_total}
total_logs = {L_total}

# Tiered Generation Pricing (Network Telemetry)
remaining_gb = total_gb
generation_cost = 0.0
TIB = 1024.0

# Tier 1: 0-10 TiB @ $0.25/GB
tier1_limit = 10 * TIB
tier1_volume = min(remaining_gb, tier1_limit)
generation_cost += tier1_volume * 0.25
remaining_gb -= tier1_volume

if remaining_gb > 0:
    # Tier 2: 10-30 TiB @ $0.15/GB
    tier2_limit = 20 * TIB
    tier2_volume = min(remaining_gb, tier2_limit)
    generation_cost += tier2_volume * 0.15
    remaining_gb -= tier2_volume

    if remaining_gb > 0:
        # Tier 3: 30-50 TiB @ $0.075/GB
        tier3_limit = 20 * TIB
        tier3_volume = min(remaining_gb, tier3_limit)
        generation_cost += tier3_volume * 0.075
        remaining_gb -= tier3_volume

        if remaining_gb > 0:
            # Tier 4: > 50 TiB @ $0.05/GB
            generation_cost += remaining_gb * 0.05

# Storage Pricing (Cloud Logging)
storage_cost = total_gb * 0.25

total_cost = generation_cost + storage_cost

print(f"TOTAL_LOGS: {total_logs:,.0f}")
print(f"TOTAL_GB: {total_gb:.4f}")
print(f"GEN_COST: {generation_cost:.4f}")
print(f"STORE_COST: {storage_cost:.4f}")
print(f"TOTAL_COST: {total_cost:.4f}")
'
```

---

### Step 6: Format Report

Format your final report exactly like this. You must sort the VPCs
alphabetically, and sort the subnets within each VPC by Monthly Volume (GB)
descending.

-   **Active Subnets**: Show their logs and volume in the table.
-   **Inactive Subnets**: Do not list them in the table. Instead, calculate `N =
    Total Subnets Count - Active Subnets Count` and show them in the note
    `*(Note: N other subnets...)*`.

```markdown
**VPC Flow Logs Cost Estimation Report**

**Scope:** [Scope Name, e.g., Project 'my-project' or VPC 'my-vpc']

**Configuration:** Sampling [Sampling Rate]%, Metadata: [Yes/No]

**Summary:**
- **Total Monthly Logs:** [TOTAL_LOGS]
- **Total Monthly Data Volume:** [TOTAL_GB] GB
- **Estimated Monthly Cost:**
    - **Generation (Network Telemetry):** $[GEN_COST]
    - **Storage (Cloud Logging):** $[STORE_COST]
    - **Total List Price:** $[TOTAL_COST]

**Detailed Breakdown:**

### VPC: [VPC Name]
| Subnet Name | Region | Monthly Logs | Monthly Volume (GB) |
| :--- | :--- | :---: | :---: |
| [subnet-a] | [us-central1] | [L_eff formatted] | [V_subnet formatted to 4 decimals] |

*(Note: [N] other subnets in the '[VPC Name]' VPC showed no traffic during the analysis period.)*

---
**DISCLAIMER:** This is an estimation only.
1. **Unsupported Resources:** Interconnects and VPNs are excluded from this estimate.
2. **Aggregation:** This assumes the default 5s aggregation interval; volumes may vary with custom intervals.
3. **Pricing:** Estimates use standard list prices and do not include enterprise or committed use discounts.
4. **Analysis period:** Based on a 30-day analysis period.
```

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