Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cloud-global-frontend-configuration@skills-hub

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

Install with the gh extension
gh skills-hub install google-cloud-global-frontend-configuration

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

Download and extract to your repository:

.github/skills/google-cloud-global-frontend-configuration/

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

Skill Files (8)

SKILL.md 10.7 KB
---
name: google-cloud-global-frontend-configuration
metadata:
  version: "1.0.2"
  category: Networking
description: |
  Guides agents through a 6-step discovery process to design and deploy Google Cloud global external Application Load Balancers with Cloud CDN, Cloud Armor, and Service Extensions, mapping workload requirements to best-practice configurations.
  Use when:
  - Designing, configuring, or deploying a Google Cloud global external Application Load Balancer, Cloud CDN, Cloud Armor WAF, or Service Extensions.
  - Discovering existing Google Cloud resources (Cloud Storage, MIGs, GKE, Cloud Run) to use as backends.
  - Generating production-grade Terraform HCL or gcloud CLI scripts for global external Application Load Balancers.
  - Actuating deployments via Infrastructure Manager or bash scripts, including IAM pre-checks.
  - Detecting, analyzing, or reconciling configuration drift on deployed global external Application Load Balancers.
  Don't use for:
  - Non-Google Cloud load balancing or security configurations.
  - Purely regional or internal load balancing setups (unless part of a hybrid/failover global design).
---

# Google Cloud global external Application Load Balancer Configuration Skill

## Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:google-cloud-global-frontend-configuration)"`
and append
`agent-skills/1.0 (skill:google-cloud-global-frontend-configuration)`
to `User-Agent` headers.

## Purpose & Agent Guidance

This skill enables the agent to guide users through a structured, 6-step discovery process to design and deploy Google Cloud global external Application Load Balancers (incorporating Cloud CDN, Cloud Armor, and Service Extensions).

**Assumptions & Target Environments:**
- This skill assumes it is called from environments (such as Gemini CLI, Antigravity, etc.) where the Google Cloud CLI (`gcloud`) can be executed.
- If `gcloud` is not available or accessible, the skill cannot perform automated resource discovery or managed deployment actuation. In such environments, the skill will limit its support to guiding the design and generating Terraform HCL configurations.

When executing this skill, the agent must:
- Map user workload requirements to simplified, opinionated best-practice configurations using actual Google Cloud product names.
- Progressively disclose details, hiding advanced complexity unless the user explicitly asks for customization.
- Leverage the reference documents in the `references/` directory to perform resource discovery, code generation, actuation, and drift detection.

## The 6-Step Configuration Flow

### Step 1: Basics
*   **Project Discovery:** Consult `references/resource-discovery.md` to auto-detect the Google Cloud project ID. Present the discovered project ID to the user.
*   Ask the user for the foundational details of their load balancer:
    *   **Name & Description:** What should we call this load balancer?
    *   **Protocol Selection:** Do they need HTTP, HTTPS, or both?
    *   **Certificate Management:** Do they want to use Google-managed certificates or bring their own existing certificates?

### Step 2: Origin Configuration
Help the user define their backend workloads through a strictly sequential, step-by-step loop. Do NOT ask everything at once. All steps are mandatory.

*   **Sub-step A - Origin Setup:** Ask if they have a single origin or need multi-origin support. Wait for response.
*   **Sub-step B - Origin Types:** Ask them to select the backend types from: Cloud Storage Buckets, Compute Engine Managed Instance Groups (MIGs), Google Kubernetes Engine (GKE) Clusters, Cloud Run Services, or External/Internet origins (IP/FQDN). Wait for response.
*   **Sub-step C - Origin Definition Loop:** Execute the following loop sequentially for EACH origin type selected in Sub-step B. Wait for the user to answer for one origin before asking about the next:
    *   **Resource Discovery:** For Google Cloud-native origins (Cloud Storage, MIGs, GKE, Cloud Run), consult `references/resource-discovery.md` to fetch resources. Present the list starting with **1. Create New**, **2. NA**. For External/Internet origins, just ask for the FQDN/IP.
    *   **Workload Type (CRITICAL):** Immediately after they define the resource, ask exactly what type of workload is being served:
        1.  **Static Images / Objects** (Static content, images, videos, styling assets)
        2.  **Cacheable API** (Read-only, public APIs where cached data is acceptable)
        3.  **Uncacheable API / Transactions** (Transactional endpoints, login, checkout, account changes)
        4.  **Dynamic Web (SSR)** (Dynamic pages, server-side rendered apps, custom dynamic sessions)
*   **Sub-step D - Routing Rules:** Once ALL origins have been fully defined one by one, ask how traffic should be routed between them (Path-based, header-based, or query-param-based). Wait for response.
*   **Sub-step E - Logging:** After routing is established, ask if they want to enable Cloud CDN logging, and if so, at what sampling rate (0-100%). Wait for response.

### Step 3: Traffic Management & Extensibility
*   Provide a brief summary of the origins and routing rules defined in Step 2.
*   Ask if they need to enable Advanced Traffic Management settings (such as granular weighted load balancing, traffic mirroring, or **Cloud Load Balancing Service Extensions** for custom WASM plugins / callouts), or if they want to proceed with **Google Cloud Best Practice Configuration**.

### Step 4: Caching (Cloud CDN)
Propose a "Recommended Configuration" based entirely on the Workload Type from Step 2. Do not list the advanced settings (TTL, Cache Keys, Compression) unless they reject the recommendation and want to customize.

*   **If Workload = Static Images / Objects:**
    *   Cache Mode: Cache All Static
    *   TTL: Client (1 day / 86400s), Default (30 days / 2592000s), Max (365 days / 31536000s) — balances long-term cache offload for static assets with periodic re-validation.
    *   Cache Key: Backend services use Protocol + Host + Path (Ignore Query
        Strings); Cloud Storage backend buckets omit Protocol and Host (Object
        Path + Cloud Storage query parameters only)
    *   Compression: Enabled (Brotli & Gzip)
    *   Negative Caching: Enabled
    *   Serve while stale: Enabled
*   **If Workload = Cacheable API:**
    *   Cache Mode: Use Origin Headers
    *   TTL: Managed by Origin (Omitted from configuration to prevent errors)
    *   Cache Key: Protocol + Host + Path + Include Query Strings
    *   Compression: Enabled (Gzip)
    *   Negative Caching: Enabled
    *   Serve while stale: Disabled
*   **If Workload = Uncacheable API / Transactions:**
    *   Cache Mode: Disabled (CDN Bypassed)
*   **If Workload = Dynamic Web (SSR):**
    *   Cache Mode: Use Origin Headers
    *   TTL: Managed by Origin (Omitted from configuration to prevent errors)
    *   Cache Key: Protocol + Host + Path
    *   Compression: Enabled (Brotli & Gzip)
    *   Cache Bypass: Bypass cache if session cookies (e.g., SESSID, JWT) are present

### Step 5: Security (Cloud Armor)
Propose a "Recommended Configuration" based entirely on the Workload Type from Step 2. Keep advanced protection (Bot Management, Threat Intel, Geo-blocking) hidden unless requested.

*   **If Workload = Static Images / Objects:**
    *   Rate Limiting: None (Standard Edge behavior; rate limiting is unsupported on Cloud Armor Edge policies for Cloud Storage buckets).
    *   OWASP Protection: Disabled
*   **If Workload = Cacheable API:**
    *   Rate Limiting: 100 requests per minute per client IP (standard baseline to prevent API abuse and DDoS while accommodating normal interactive usage).
    *   OWASP Protection: Enabled (SQLi, XSS, Local File Inclusion)
*   **If Workload = Uncacheable API / Transactions:**
    *   Rate Limiting: Strict 30 requests per minute per client IP (tight threshold to protect sensitive transactional endpoints like login/checkout from credential stuffing and brute-force attacks).
    *   OWASP Protection: Enabled (SQLi, XSS, Remote Command Execution, Session Fixation)
    *   Bot Management & Threat Intel: Enabled (Block malicious bots and known malicious IPs)
*   **If Workload = Dynamic Web (SSR):**
    *   Rate Limiting: 120 requests per minute per client IP (generous threshold to accommodate burst requests for initial page loads and asset hydration in SSR web applications).
    *   OWASP Protection: Enabled (SQLi, XSS, CSRF, Shellshock)
    *   Geo-blocking: Optional (Restrict/allow specific country access)

### Step 6: Review & Deploy
*   **Configuration Summary:** Generate a complete, formatted markdown table showing all finalized settings from Steps 1 through 5, using Google Cloud product names. Follow this exact template structure:

    | Component | Parameter / Setting | Value & Justification |
    | :--- | :--- | :--- |
    | **Load Balancer** | Name & Protocol | `<Name>` (HTTP/HTTPS) |
    | **Origins** | Backends & Workloads | `<Backend 1>` (`<Workload Type>`), `<Backend 2>`... |
    | **Traffic Management** | Routing Rules | `<Path / Header rules or Default>` |
    | **Cloud CDN** | Cache Mode & TTLs | `<Cache Mode>`, Default TTL: `<TTL>` |
    | **Cloud Armor** | Rate Limiting & OWASP | `<RPM Limit>`, OWASP Rules: `<Enabled/Disabled>` |
    | **Service Extensions**| WASM / Callouts | `<Enabled/Disabled or N/A>` |

*   **Next Action:** Ask the user to choose their deployment/generation format (Terraform HCL or gcloud CLI Bash Script) and their next action:
    1.  **Show Code / Script** (Display the HCL code or gcloud bash script. Once displayed, offer options to **Download** or **Deploy/Execute**)
    2.  **Download files** (Save `main.tf` or `deploy.sh` to the local workspace)
    3.  **Deploy Configuration:** Initiate the deployment via Infrastructure Manager or execute the gcloud script. This should be done using the deployment instructions in `references/managed-deployment.md`.

---

## Relevant Documentation & Supportive Links
- [Cloud Load Balancing Overview](https://cloud.google.com/load-balancing/docs/load-balancing-overview)
- [Cloud CDN Documentation](https://cloud.google.com/cdn/docs)
- [Cloud Armor Documentation](https://cloud.google.com/armor/docs)
- [Cloud Load Balancing Service Extensions](https://cloud.google.com/service-extensions/docs/overview)
- [Infrastructure Manager Overview](https://cloud.google.com/infrastructure-manager/docs)
- [Official Terraform LB-HTTP Module](https://registry.terraform.io/modules/GoogleCloudPlatform/lb-http/google/latest)
- [Official Terraform Cloud Armor Module](https://registry.terraform.io/modules/GoogleCloudPlatform/cloud-armor/google/latest)
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-global-frontend-configuration)" \
    gcloud <command> [flags]
    ```

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

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

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:google-cloud-global-frontend-configuration)
    ```

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

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
drift-detection.md 3.0 KB
# Google Cloud global external Application Load Balancer Drift Detection Guidelines

This reference document details how to detect, analyze, and reconcile configuration drift in Google Cloud global external Application Load Balancer infrastructure using Infrastructure Manager previews.

---

## Core Directives - Behavioral Rules

1. **Safety First:** Never modify production infrastructure directly during drift detection. Always generate a **preview** first to safely inspect differences.
2. **Reconciliation Options:** When drift is detected, always present the user with a clear, two-choice decision path:
    *   **Option A (Reconcile to Code):** Overwrite manual changes by re-applying the Terraform configuration.
    *   **Option B (Backport to Code):** Update the Terraform HCL code to match the manual changes made in the Google Cloud console.

---

## The Drift Detection Flow

### Step 1: Generate Infrastructure Preview
Create a preview using Infrastructure Manager to compare the deployed infrastructure against the local Terraform code.

*   Run the preview command, passing the existing deployment name and the path to the local Terraform directory:
    ```bash
    gcloud infra-manager previews create {preview_name} \
        --location={region} \
        --local-source={path_to_tf_dir} \
        --service-account={service_account_email} \
        --deployment="projects/{project_id}/locations/{region}/deployments/{deployment_name}"
    ```
*   *Wait for the preview creation to complete successfully.*

### Step 2: List Detected Drifts
Query the generated preview to identify specific resources that have drifted.

*   Run the command to list resource drifts:
    ```bash
    gcloud infra-manager resource-drifts list \
        --preview="projects/{project_id}/locations/{region}/previews/{preview_name}"
    ```
*   Present the output list of drifted resources to the user in a clean, readable table format, detailing:
    *   Resource Name & Type
    *   Action (e.g., UPDATE, DELETE)
    *   Drift Status (e.g., DRIFTED)

### Step 3: Present Reconciliation Paths
Analyze the list from Step 2 and present the two reconciliation options:

*   **Option A: Overwrite and Re-align to Code**
    *   Explain that this will revert all manual Google Cloud console changes and re-apply the local Terraform state.
    *   Provide the command to re-apply the deployment (referencing `references/managed-deployment.md`):
        ```bash
        gcloud infra-manager deployments apply projects/{project_id}/locations/{region}/deployments/{deployment_name} \
            --local-source={path_to_tf_dir} \
            --service-account={service_account_email} \
            --import-existing-resources
        ```
*   **Option B: Backport Console Changes to Code**
    *   Explain that this will update their local Terraform files to reflect the manual changes made in the Google Cloud console, preserving them.
    *   Detail the exact HCL changes they need to make to their `main.tf` based on the drift output.
gcloud-generation.md 6.9 KB
# Google Cloud global external Application Load Balancer gcloud Script Generation Guidelines

This reference document details how to generate robust, ordered, production-grade bash scripts containing `gcloud` CLI commands to deploy Google Cloud global external Application Load Balancer architectures (incorporating Cloud CDN and Cloud Armor WAF) based on a design spec.

---

## Core Directives - Behavioral Rules

1.  **Deterministic Command Ordering:** You must strictly follow the **Dependency Execution Order** below. Google Cloud resource creation has strict dependency trees; executing commands out of order will result in immediate deployment failures.
2.  **Resource Prefixing:** You must prefix every created resource name with the environment variable `$ARCHITECTURE_NAME` to ensure global uniqueness and prevent 409 conflicts.
3.  **Destruction Pairing (Mandatory):** For every script you generate, you MUST generate an accompanying destruction script (`destroy.sh`) that tears down the exact same resources in exact reverse dependency order.
4.  **Error Handling (Strict Requirement):** You must include `set -e` (exit immediately on error) at the top of all generated scripts to prevent cascading failures if an intermediate command fails.

---

## Dependency Execution Order (The Creation Sequence)

All `gcloud` commands must be ordered in this exact sequence in your output script:

1.  **Variables & Setup:** Define environment variables (`ARCHITECTURE_NAME`, `PROJECT_ID`, `REGION`, etc.) and set the active project via `gcloud config set project`.
2.  **Network Endpoint Groups (NEGs):** Create region/global NEGs if using Serverless or External origins.
3.  **Cloud Armor Security Policies:** Create policies and rules.
4.  **Backend Services & Buckets:** Create backends, configure CDN settings, and attach security policies.
5.  **URL Maps:** Create the root URL map and attach backend services.
6.  **Path & Host Rules:** Apply path matchers and routing rules to the URL map.
7.  **Target Proxies:** Create HTTP/HTTPS target proxies, linking the URL map and certificates.
8.  **Global Forwarding Rules:** Create the frontend forwarding rules, binding target proxies to public IPs.

---

## Workload Profile CLI Map (The Source of Truth)

| Workload Type | CDN Flags | WAF Policy & Rules |
| :--- | :--- | :--- |
| **Static Images / Objects** | `--enable-cdn`<br>`--cache-mode=CACHE_ALL_STATIC`<br>`--default-ttl=2592000`<br>`--client-ttl=86400`<br>`--max-ttl=31536000` | None (Rate Limiting unsupported on CLOUD_ARMOR_EDGE) |
| **Cacheable API**| `--enable-cdn`<br>`--cache-mode=USE_ORIGIN_HEADERS` | Rate limit (100 RPM) + OWASP rules (SQLi, XSS, LFI)<br>`--action=deny-403`<br>`--expression="evaluatePreconfiguredWaf('sqli-v422-stable') \|\| evaluatePreconfiguredWaf('xss-v422-stable')"` |
| **Uncacheable API / Transactions**| `--no-enable-cdn` | Strict Rate limit (30 RPM) + OWASP rules + Bot Management/Threat Intel |
| **Dynamic Web (SSR)** | `--enable-cdn`<br>`--cache-mode=USE_ORIGIN_HEADERS` | Rate limit (120 RPM) + OWASP rules (SQLi, XSS, CSRF) |

---

## Backend Reference Directory (Commands)

### 1. Google Cloud Storage Buckets
```bash
gcloud compute backend-buckets create "${ARCHITECTURE_NAME}-bucket-backend" \
    --gcs-bucket-name="{bucket_name}" \
    --enable-cdn \
    --cache-mode="{cache_mode}" \
    --default-ttl="{default_ttl}" \
    --client-ttl="{client_ttl}" \
    --max-ttl="{max_ttl}"
```

### 2. Cloud Run Services
```bash
# Create Serverless NEG
gcloud compute network-endpoint-groups create "${ARCHITECTURE_NAME}-neg" \
    --network-endpoint-type=serverless \
    --region="{region}" \
    --cloud-run-service="{service_name}"

# Create Backend Service and Attach Security Policy
gcloud compute backend-services create "${ARCHITECTURE_NAME}-backend" \
    --global \
    --load-balancing-scheme=EXTERNAL_MANAGED \
    --protocol=HTTP
gcloud compute backend-services update "${ARCHITECTURE_NAME}-backend" \
    --global \
    --security-policy="{security_policy_name}"

# Add NEG to Backend
gcloud compute backend-services add-backend "${ARCHITECTURE_NAME}-backend" \
    --global \
    --network-endpoint-group="${ARCHITECTURE_NAME}-neg" \
    --network-endpoint-group-region="{region}"
```

### 3. Compute Engine MIGs
```bash
# Create Backend Service and Attach Security Policy
gcloud compute backend-services create "${ARCHITECTURE_NAME}-backend" \
    --global \
    --load-balancing-scheme=EXTERNAL_MANAGED \
    --protocol=HTTP
gcloud compute backend-services update "${ARCHITECTURE_NAME}-backend" \
    --global \
    --security-policy="{security_policy_name}"

# Add MIG to Backend
gcloud compute backend-services add-backend "${ARCHITECTURE_NAME}-backend" \
    --global \
    --instance-group="{mig_name}" \
    --instance-group-zone="{zone}"
```

### 4. GKE Clusters
```bash
# Create Backend Service and Attach Security Policy
gcloud compute backend-services create "${ARCHITECTURE_NAME}-backend" \
    --global \
    --load-balancing-scheme=EXTERNAL_MANAGED \
    --protocol=HTTP
gcloud compute backend-services update "${ARCHITECTURE_NAME}-backend" \
    --global \
    --security-policy="{security_policy_name}"

# Add GKE NEG to Backend
gcloud compute backend-services add-backend "${ARCHITECTURE_NAME}-backend" \
    --global \
    --network-endpoint-group="{gke_neg_name}" \
    --network-endpoint-group-zone="{zone}"
```

### 5. External / Internet Origins (IP/FQDN)
```bash
# Create Global NEG for External Origin
gcloud compute network-endpoint-groups create "${ARCHITECTURE_NAME}-neg" \
    --global \
    --network-endpoint-type=internet-fqdn-port

# Add Endpoint
gcloud compute network-endpoint-groups update "${ARCHITECTURE_NAME}-neg" \
    --global \
    --add-endpoint="fqdn={domain_name},port=443"

# Create Backend Service and Attach Security Policy
gcloud compute backend-services create "${ARCHITECTURE_NAME}-backend" \
    --global \
    --load-balancing-scheme=EXTERNAL_MANAGED \
    --protocol=HTTPS
gcloud compute backend-services update "${ARCHITECTURE_NAME}-backend" \
    --global \
    --security-policy="{security_policy_name}"

# Add NEG to Backend
gcloud compute backend-services add-backend "${ARCHITECTURE_NAME}-backend" \
    --global \
    --network-endpoint-group="${ARCHITECTURE_NAME}-neg" \
    --global-network-endpoint-group
```

---

## Script Assembly Workflow

1.  **Define Header:** Set `set -e` and export the variables (`ARCHITECTURE_NAME`, `PROJECT_ID`, etc.).
2.  **Generate Creation Block:** Assemble the commands sequentially following the **Dependency Execution Order** and utilizing the **Workload Profile CLI Map** and **Backend Reference Directory**.
3.  **Generate Destruction Block:** Append or output a separate `destroy.sh` script that tears down the exact same resources in exact reverse dependency order.
4.  **Output and Hand-off:** Present the scripts to the user. State the next action (Download Files or Deploy Configuration) and transition to `references/managed-deployment.md` (specifically Phase 2 Option B) to guide them through deployment execution.
managed-deployment.md 3.9 KB
# Google Cloud global external Application Load Balancer Managed Actuation Guidelines

This reference document details how to deploy finalized global external Application Load Balancer configurations (Terraform via Infrastructure Manager or gcloud scripts), including performing mandatory IAM pre-checks to ensure deployment success.

---

## The 2-Phase Actuation Workflow

### Phase 1: IAM Pre-checks (Mandatory)
Before executing any deployment, you MUST verify that your acting identity has the necessary permissions. Failing to do so will result in half-provisioned infrastructure and orphaned resources.

1.  **Identity Identification:** Find the active identity using `gcloud config get-value account`.
2.  **Permission & Role Validation:** Check for the following permissions and
    roles on the target project:
    *   `resourcemanager.projects.get` (Read project metadata)
    *   `roles/compute.admin` (Full access to Cloud Load Balancing, Cloud CDN,
        and Cloud Armor WAF)
    *   *If using Terraform (via Infrastructure Manager):*
        *   `roles/config.admin` (Infrastructure Manager Administrator)
        *   `iam.serviceAccounts.actAs` (Permission to act as the deployment
            service account, e.g., `roles/iam.serviceAccountUser`)
3.  **Service Account Pre-check:** Infrastructure Manager runs deployments using
    a user-managed service account. You must verify that:
    *   A user-managed service account exists in the project (create one if none
        is provided; do not pass the Google-managed service agent
        `service-{project_number}@gcp-sa-config.iam.gserviceaccount.com` to
        `--service-account`).
    *   The service account has `roles/config.agent` (Infra Manager Agent) plus
        resource-provisioning roles (`roles/editor` or `roles/owner`, or
        granular admin roles such as `roles/compute.admin` and
        `roles/storage.admin`).

---

### Phase 2: Actuation (Choose based on format)

#### Option A: If using Terraform (via Infrastructure Manager)
Infrastructure Manager is Google's managed service for deploying Terraform configurations. It guarantees remote state management and lock enforcement.

1.  **Cleanup Local State:** Ensure any local `.terraform` directory is deleted before deploying, as Infrastructure Manager will fail otherwise:
    ```bash
    rm -rf {local_source_dir}/.terraform
    ```
2.  **Execution:** Run the `gcloud infra-manager deployments apply` command. You MUST specify the `--service-account` to avoid validation errors, and you must have `iam.serviceAccounts.actAs` permission on it. Always include the `--import-existing-resources` flag:
    ```bash
    gcloud infra-manager deployments apply projects/{project_id}/locations/us-central1/deployments/{deployment_id} \
        --local-source="{local_source_dir}" \
        --service-account="{service_account_email}" \
        --import-existing-resources
    ```
3.  **Status Monitoring:** Poll the deployment status until it reaches `ACTIVE`. Run:
    ```bash
    gcloud infra-manager deployments describe projects/{project_id}/locations/us-central1/deployments/{deployment_id}
    ```
4.  **Teardown Instructions:** Always provide the user with the exact command to tear down the infrastructure if they want to clean up:
    ```bash
    gcloud infra-manager deployments delete projects/{project_id}/locations/us-central1/deployments/{deployment_id}
    ```

#### Option B: If using gcloud CLI Script
If the user chose the gcloud script format:

1.  **Permissions Check:** Ensure the active identity has `roles/compute.admin`
    and `roles/storage.admin` (if using Google Cloud Storage bucket).
2.  **Execution:** Instruct the user to save the generated script as `deploy.sh` and execute it:
    ```bash
    chmod +x deploy.sh
    ./deploy.sh
    ```
3.  **Teardown Instructions:** Provide the accompanying `destroy.sh` script to tear down the resources in exact reverse dependency order.
resource-discovery.md 1.7 KB
# Google Cloud Resource Discovery Guidelines

This reference document details how to execute gcloud commands to discover and list existing Google Cloud resources (Cloud Storage buckets, Compute Engine Managed Instance Groups, GKE clusters, and Cloud Run services) in the project to assist with load balancer configuration.

## Target Environment Assumptions
This resource discovery flow assumes it is executed in an environment (such as Gemini CLI, Antigravity, or a configured gLinux terminal) where the Google Cloud SDK (`gcloud`) is installed and has active credentials for the target project. If `gcloud` is not available, the agent must skip discovery and prompt the user to input their resource names manually.

---

## Core Directives

1. **Discovery UX:** Prioritize a clean, numbered-list UX for all resource discovery. Never ask for manual string input for existing resources. Always present lists starting with: **1. Create New**, **2. NA**.
2. **Project ID Detection:** Auto-detect the target Google Cloud project ID using `gcloud config get-value project`.
3. **Resource Fetching Guidelines:**
    When requested by the main configuration skill, fetch the specific resource types:
    *   **Google Cloud Storage Buckets:** Run `gcloud storage buckets list --format="value(name,location)"`
    *   **Compute Engine Managed Instance Groups (MIGs):** Run `gcloud compute instance-groups managed list --format="value(name,region,zone)"`
    *   **Cloud Run Services:** Run `gcloud run services list --format="value(name,region)"`
    *   *(Only fetch the resource types that the user explicitly selected in their Origin Types.)*

4. **Return Format:** Return the discovered items clearly labeled with their region/zone where applicable.
terraform-generation.md 6.6 KB
# Google Cloud global external Application Load Balancer Terraform Code Generation Guidelines

This reference document details how to generate syntactically perfect, production-grade Terraform HCL code for Google Cloud global external Application Load Balancer architectures (incorporating Cloud CDN and Cloud Armor WAF) based on a design spec.

---

## Core Directives - Behavioral Rules

1.  **Deterministic Output:** You must strictly follow the **Workload Profile Map** below. If a user selects a workload type, you MUST apply the corresponding HCL properties. Do not deviate or get "creative" with the code.
2.  **Schema Enforcement:** You expect a "Design Spec" containing: Architecture Name, Project, Region, Protocols, Origins (with associated Workload Types), and Routing Rules.
3.  **Cross-Resource Linking:** Ensure all Terraform resources are correctly linked using reference syntax (e.g., `service = google_compute_backend_service.example.id`) rather than hardcoding names.
4.  **Directory Isolation:** Always generate HCL code inside a dedicated, isolated subdirectory named after the architecture (e.g., `/gfe/deployments/{architecture_name}/`) to avoid stale state or resource name pollution.
5.  **Resource Prefixing:** Ensure all Google Cloud resource names in the generated HCL are dynamically prefixed with the Architecture Name (either via input variables or string interpolation) to guarantee global uniqueness and prevent 409 resource conflicts.
6.  **Lowercase Naming Only:** Infrastructure Manager and Google Cloud APIs are strict on resource naming. The architecture name, deployment IDs, and all generated resource names MUST be strictly lowercase and match `^[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?$`. If the user provides a name with uppercase characters, convert it to lowercase automatically before using it in the configuration.

---

## Terraform Syntax & Google Cloud API Constraints

To prevent validation and deployment errors, always adhere to the following Google Cloud provider constraints:

1.  **Cloud Armor (`google_compute_security_policy`)**:
    *   **Default Action**: Do NOT use `default_rule_action = "..."` at the top level. You must explicitly define the default action as a `rule` block with priority `2147483647` and action `allow` (or `deny`).
    *   **Rate Limiting Action**: Use `action = "throttle"` instead of `rate-based-ban` for rate limit rules. This ensures compatibility across different API/provider versions.
    *   **Cloud Armor Edge Constraints**: `type = "CLOUD_ARMOR_EDGE"` policies (required for Backend Buckets) DO NOT support `rate_limit_options`. Only use standard `allow` or `deny` rules. Do not generate rate limiting configurations for backend buckets.
2.  **Backend Buckets (`google_compute_backend_bucket`)**:
    *   **Cache Key Policy**: Do NOT include a `cache_key_policy` block (e.g., trying to set `include_query_string = false`). Backend buckets do not support these arguments; query strings are automatically ignored by default when using `CACHE_ALL_STATIC`.
    *   **Default TTL Limits**: The `cdn_policy.default_ttl` cannot be greater than the `max_ttl`. If you set `default_ttl` to a value larger than the default `86400` (e.g., the recommended `2592000` / 30 days for static objects), you MUST explicitly set `max_ttl` to a value equal to or larger than `default_ttl` (e.g., `31536000` / 365 days).
3.  **Backend Services (`google_compute_backend_service`)**:
    *   **Origin Header TTLs**: If using `cache_mode = "USE_ORIGIN_HEADERS"`, you MUST omit `default_ttl` and `client_ttl` from the `cdn_policy` block. Specifying them will cause validation errors.
    *   **Request Coalescing**: Avoid using `request_coalescing = true` inside the `cdn_policy` of backend services unless verified to be supported by the active provider version.
4.  **Provider Version**:
    *   Always configure the `required_providers` block to use the Google provider version `~> 5.0` (or newer) to ensure rate-limiting features are correctly supported.

---

## Workload Profile Map (The Source of Truth)

| Workload Type | `enable_cdn` | `cdn_policy.cache_mode` | `default_ttl` | `max_ttl` | Cache Key Policy | WAF Protection (Cloud Armor) |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| **Static Images / Objects** | `true` | `CACHE_ALL_STATIC` | `2592000` (30d) | `31536000` (365d) | Backend Services: Host + Protocol + Path (Ignore Query Strings); Backend Buckets: Object Path (Protocol & Host omitted; `cache_key_policy` unsupported) | None (Rate Limiting unsupported on CLOUD_ARMOR_EDGE) |
| **Cacheable API**| `true` | `USE_ORIGIN_HEADERS` | Omitted (Managed by Origin) | Omitted | **Include Query Strings** | OWASP (SQLi/XSS/LFI) + Rate Limit (100 RPM) |
| **Uncacheable API / Transactions**| `false`| N/A | N/A | N/A | N/A | OWASP (SQLi/XSS/RCE/Session Fixation) + Strict Rate Limit (30 RPM) + Bot Management |
| **Dynamic Web (SSR)** | `true` | `USE_ORIGIN_HEADERS` | Omitted (Managed by Origin) | Omitted | Host + Protocol + Path (Bypass on session cookie) | OWASP (SQLi/XSS/CSRF/Shellshock) + Rate Limit (120 RPM) |

---

## The Generation Workflow

1.  **Consume Spec:** Read the provided Design Spec carefully.
2.  **Prepare Directory Structure:** Create the dedicated subdirectory `/gfe/deployments/{architecture_name}/`.
3.  **Assemble HCL:**
    *   Generate a `variables.tf` and `terraform.tfvars` defining the input variables (`architecture_name`, `project_id`, `region`, etc.) to dynamically parameterize the blueprint.
    *   Generate the `terraform` and `provider` blocks in `main.tf`.
    *   For each origin, create the appropriate backend resource (`backend_bucket`, `backend_service`, or `region_network_endpoint_group`), dynamically prefixing the `name` field using the architecture name prefix, and injecting properties from the **Workload Profile Map**.
    *   Create the `google_compute_security_policy` resources for each backend using the WAF rules defined in the map, with dynamic prefixing.
    *   Create the `google_compute_url_map` using the provided path and header-based routing rules.
    *   Create the frontend resources (`target_http_proxy` / `target_https_proxy` with `ssl_certificates`, and `global_forwarding_rule`), with dynamic prefixing.
4.  **Output Code:** Provide the complete, finalized `main.tf`, `variables.tf`, and `terraform.tfvars` files to the user. Do not include conversational filler; focus on the technical integrity of the code.
5.  **Hand-off:** Once the code is output, state the next action (Download Files or Deploy Configuration) and transition to `references/managed-deployment.md` (specifically Phase 2 Option A) to guide the user through deployment pre-checks and execution.
terraform-module.md 6.1 KB
# Google Cloud global external Application Load Balancer Official Terraform Module Guidelines

This reference document provides guidelines and examples for designing and managing Google Cloud global external Application Load Balancer architectures using the official Google-managed Terraform modules (`lb-http` and `cloud-armor`).

## Table of Contents
- [Core Directives](#core-directives)
- [Comprehensive Multi-Backend Example](#comprehensive-multi-backend-example)
  - [Cloud Armor Security Policies](#comprehensive-multi-backend-example)
  - [Serverless NEG (Cloud Run)](#comprehensive-multi-backend-example)
  - [Global Load Balancer (Official Module)](#comprehensive-multi-backend-example)

---

## Core Directives

1.  **Prefer Official Modules:** Whenever generating complex, production-grade configurations, prefer using the official Google-supported modules to ensure best-practices, security defaults, and ongoing updates:
    *   **Load Balancer:** [terraform-google-lb-http](https://registry.terraform.io/modules/GoogleCloudPlatform/lb-http/google/latest)
    *   **Cloud Armor WAF:** [terraform-google-cloud-armor](https://registry.terraform.io/modules/GoogleCloudPlatform/cloud-armor/google/latest)
2.  **Module Versioning:** Always lock the module version to the latest stable major version (e.g., `version = "~> 10.0"` for `lb-http` or `version = "~> 2.0"` for `cloud-armor`) to prevent breaking changes.
3.  **Backend Structure:** Map the design spec origins to the `backends` map of the `lb-http` module. Each backend entry must configure `protocol`, `enable_cdn`, `cdn_policy`, and its target endpoint groups (`groups`).

---

## Comprehensive Multi-Backend Example

The following example demonstrates a complete, production-ready `main.tf` using the official modules to configure a Google Cloud global external Application Load Balancer with three distinct backends (Serverless NEG for API, Google Cloud Storage bucket for static content, and Cloud Armor security policies):

```hcl
terraform {
  required_version = ">= 1.0"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 5.0"
    }
  }
}

provider "google" {
  project = var.project_id
  region  = var.region
}

# --- Cloud Armor Security Policies ---

module "security_policy_api" {
  source  = "GoogleCloudPlatform/cloud-armor/google"
  version = "~> 2.0"

  project_id   = var.project_id
  policy_name  = "${var.architecture_name}-waf-api"
  description  = "Cloud Armor WAF policy for API backends"
  default_action = "allow"

  # Rate limiting rule (100 RPM)
  rate_limiting_rules = [
    {
      action        = "throttle"
      priority      = 1000
      description   = "Rate limit API requests"
      src_ip_ranges = ["*"]
      
      rate_limit_options = {
        exceed_action            = "deny(403)"
        rate_limit_threshold = {
          count        = 100
          interval_sec = 60
        }
      }
    }
  ]

  # Preconfigured OWASP rules
  preconfigured_rules = [
    {
      action        = "deny(403)"
      priority      = 9000
      description   = "OWASP SQLi protection"
      expression    = "evaluatePreconfiguredWaf('sqli-v422-stable')"
      src_ip_ranges = ["*"]
    },
    {
      action        = "deny(403)"
      priority      = 9001
      description   = "OWASP XSS protection"
      expression    = "evaluatePreconfiguredWaf('xss-v422-stable')"
      src_ip_ranges = ["*"]
    }
  ]
}

# --- Serverless NEG (Cloud Run) ---

resource "google_compute_region_network_endpoint_group" "serverless_neg" {
  name                  = "${var.architecture_name}-serverless-neg"
  network_endpoint_type = "SERVERLESS"
  region                = var.region
  
  cloud_run {
    service = var.cloud_run_service_name
  }
}

# --- Global Load Balancer (Official Module) ---

module "gce_lb_http" {
  source  = "GoogleCloudPlatform/lb-http/google"
  version = "~> 10.0"

  project       = var.project_id
  name          = var.architecture_name
  firewall_networks = [] # Not creating internal firewall rules for global external LB

  # Frontend Configuration
  ssl                          = true
  use_ssl_certificates        = false
  ssl_certificates             = [google_compute_managed_ssl_certificate.default.id]
  http_forward                 = true

  backends = {
    # Default External Backend (API)
    default = {
      protocol        = "HTTP"
      enable_cdn      = true
      security_policy = module.security_policy_api.policy_id

      cdn_policy = {
        cache_mode = "USE_ORIGIN_HEADERS"
        cache_key_policy = {
          include_query_string = true
        }
      }

      groups = [
        {
          group = google_compute_global_network_endpoint_group.external_neg.id
        }
      ]
    }

    # Google Cloud Storage Bucket Backend
    gcs = {
      protocol        = "HTTP"
      enable_cdn      = true

      cdn_policy = {
        cache_mode  = "CACHE_ALL_STATIC"
        default_ttl = 2592000
        max_ttl     = 2592000
      }

      groups = [
        {
          group = "projects/${var.project_id}/global/backendBuckets/${var.architecture_name}-gcs-backend"
        }
      ]
    }

    # Serverless Backend
    serverless = {
      protocol        = "HTTP"
      enable_cdn      = true
      security_policy = module.security_policy_api.policy_id

      cdn_policy = {
        cache_mode  = "CACHE_ALL_STATIC"
        default_ttl = 2592000
        max_ttl     = 2592000
      }

      groups = [
        {
          group = google_compute_region_network_endpoint_group.serverless_neg.id
        }
      ]
    }
  }

  # Custom Path Routing Matchers
  url_map = {
    default_service = "default"
    path_matchers = {
      main-matcher = {
        default_service = "default"
        path_rules = [
          {
            paths   = ["/api", "/api/*"]
            service = "default"
          },
          {
            paths   = ["/static", "/static/*"]
            service = "gcs"
          },
          {
            paths   = ["/app", "/app/*"]
            service = "serverless"
          }
        ]
      }
    }
  }
}

resource "google_compute_managed_ssl_certificate" "default" {
  name = "${var.architecture_name}-cert"

  managed {
    domains = [var.domain_name]
  }
}
```

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