Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install application-design-center-design-deploy@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin application-design-center-design-deploy v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install application-design-center-design-deploy

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

Download and extract to your repository:

.github/skills/application-design-center-design-deploy/

Extract the ZIP to .github/skills/ in your repo. The folder name must match application-design-center-design-deploy for Copilot to auto-discover it.

Skill Files (15)

SKILL.md 17.7 KB
---
name: application-design-center-design-deploy
description: >-
  Processes GCP infrastructure design and deployment workflows within Application Design Center (ADC).
  Use when:
  - Designing GCP infrastructure with Terraform.
  - Validating local HCL.
  - Performing best-practice plan scans.
  - Importing templates to Application Design Center (ADC).
  - Deploying templates.
  - Troubleshooting deployment failures.
  Boundaries:
  - Only use for GCP-specific cloud infrastructure.
  - Only use for Terraform coding within the ADC context.
license: Apache-2.0
metadata:
  version: "1.0.2"
  publisher: google
  category: CloudInfrastructure
---

# Designing and Deploying GCP Infrastructure with Application Design Center

## 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:application-design-center-design-deploy)"`
and append `agent-skills/1.0 (skill:application-design-center-design-deploy)` to `User-Agent` headers.

## Overview

This skill provides a prescriptive, production-grade workflow for the entire
infrastructure lifecycle on Google Cloud Platform (GCP). It replaces the
automated, opaque-box GAD `design_infra` tool with an **agent-controlled design
and validation loop** utilizing modular Terraform and local CLI validation,
followed by a **shifted-left best practices plan scan** prior to synchronization
with the Application Design Center (ADC) registry for deployment and lifecycle
management.

Always maintain the persona of a Principal Cloud Architect. Keep the local
Terraform configuration as the source of truth, and ensure the design is fully
compliant with best practices before importing it into the cloud registry.

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

## Index

1.  [Pre-requisites: Setup & Confirmation](#pre-requisites-setup-confirmation)
2.  [Phase 1: Local Infrastructure Design & Validation](#phase-1-local-infrastructure-design-validation)
3.  [Phase 2: Shifted-Left Best Practices Assessment & Iterative Remediation](#phase-2-shifted-left-best-practices-assessment-iterative-remediation)
4.  [Phase 3: Import IaC to Application Design Center](#phase-3-import-iac-to-application-design-center)
5.  [Phase 4: Application Deployment & Monitoring](#phase-4-application-deployment-monitoring)
6.  [Phase 5: Troubleshoot Deployment Failures](#phase-5-troubleshoot-deployment-failures)
7.  [Phase 6: Verification & E2E Testing](#phase-6-verification-e2e-testing)

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

## Pre-requisites: Setup & Confirmation

Before executing Phase 1, you **must** perform the following setup steps:

1.  **Confirm Target Project & Location**:

    *   Explicitly ask the user to confirm the target GCP **project ID** and
        **location** (region).
    *   If the user does not specify a location, use **`us-central1`** as the
        default.
    *   Verify that your local environment has the active project set:

        ```bash
        gcloud config set project <project_id>
        ```

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

## Phase 1: Local Infrastructure Design & Validation

**Goal**: Transform user requirements and codebase characteristics into a 100%
validated, secure, and compile-ready Terraform configuration locally.

1.  **Invoke the `design` Skill**: Call and execute the `design` skill (defined
    in [design](references/design_guide.md))
    for the user's prompt.
    *   The `design` skill will autonomously perform the Codebase Analysis,
        query the catalog registry, planning, HCL generation, and local CLI
        validation loop (`terraform init`, `validate`, `plan`) in a dedicated
        scratch directory.
2.  **Locate Validated HCL**: Identify the scratch directory where the `design`
    skill saved the validated, compile-ready Terraform files (e.g.,
    `scratch/tf_validate_<session_id>/`).
3.  **Verify Handover (MANDATORY)**: Ensure that the local validation loop in
    the `design` skill completed successfully with a clean plan before
    proceeding. Meticulously inspect the HCL to verify:
    *   **Secret-Safe Policy**: Confirm that no plaintext credentials,
        passwords, or hardcoded secrets are written in `terraform.tfvars` or HCL
        resource blocks. All sensitive inputs must be wired through GCP Secret
        Manager.
    *   **State Isolation Policy**: Confirm that there is no remote backend
        block (e.g., `backend "gcs" {}`) in the HCL files. State must remain
        local in the scratch folder during validation, allowing ADC to handle
        the remote state registry upon import.
    *   *Remediation*: If any violations are found, correct them in the HCL,
        re-run local validation, and verify again. Do not proceed with
        unvalidated or insecure code.
4.  **Export Terraform Plan to JSON (MANDATORY)**: In the scratch directory, run
    the following commands to generate a binary plan and convert it into a clean
    JSON representation:

    ```bash
    terraform plan -out=tfplan && terraform show -json tfplan > tfplan.json
    ```

    Verify that the `tfplan.json` file is successfully written in your scratch
    directory.

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

## Phase 2: Shifted-Left Best Practices Assessment & Iterative Remediation

**Goal**: Validate the local plan's alignment with security, cost, and
reliability benchmarks BEFORE importing it into the cloud registry, using the
native ADC plan assessment API.

1.  **Discover Space ID (MANDATORY)**: Before running the assessment or creating
    templates, you **must** dynamically discover the active ADC Space ID in your
    target location:

    *   **List Spaces**: Run the command:

        ```bash
        gcloud design-center spaces list --project=<project_id> --location=<location>
        ```

    *   **Select Space**: Parse the output to identify the active space (e.g.,
        `test-deploy` or `googlespace`). If multiple spaces exist, ask the user
        to confirm. If no space exists, ask the user or create one:

        ```bash
        gcloud design-center spaces create <space_id> --project=<project_id> --location=<location>
        ```

2.  **Execute Plan Assessment via gcloud**: Run the plan-based assessment using
    the discovered Space ID and your exported `tfplan.json` file. Execute the
    command directly in your terminal:

    ```bash
    gcloud alpha design-center spaces generate-terraform-assessment-report <space_id> \
        --location=<location> \
        --project=<project_id> \
        --terraform-plan="<scratch_directory_path>/tfplan.json" \
        --format=json
    ```

3.  **Analyze Findings**: Present all findings to the user in a clean tabular
    format, detailing specific violations, resource scopes, and associated
    severity levels.

4.  **Local Remediation Loop**:

    *   **Do not** attempt to import or commit insecure code.
    *   Edit your **local HCL files** in the scratch directory to fix the
        reported violations (e.g., adding encryption keys, enabling OS Login, or
        restricting IAM scopes).
    *   Re-run Phase 1 local validation and plan export:

        ```bash
        terraform validate && terraform plan -out=tfplan && terraform show -json tfplan > tfplan.json
        ```

    *   Re-run the plan assessment command shown in step 2.

5.  **Exit Criteria**:

    *   All high/critical findings resolved, or acceptable trade-offs
        documented.
    *   Maximum of three (3) iterative attempts reached. Once clean or
        acceptable, proceed to Phase 3.

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

## Phase 3: Import IaC to Application Design Center

**Goal**: Synchronize the fully validated and best-practice-compliant local HCL
configuration with the ADC cloud registry to establish the deployable template
resource.

1.  **Verify or Create the Application Template (MANDATORY)**: Before importing
    the HCL, you **must** ensure the parent Application Template resource exists
    in the discovered ADC space.

    *   **Check Existence**: Run `gcloud design-center spaces
        application-templates describe <template_id> --space=<space_id>
        --project=<project_id> --location=<location>` to check if the template
        exists.
    *   **Create if Missing**: If the describe command returns a `NOT_FOUND`
        error, create the template resource first by running:

        ```bash
        gcloud design-center spaces application-templates create <template_id> --space=<space_id> --project=<project_id> --location=<location> --display-name="<Name>" --description="<Description>"
        ```

2.  **Strict HCL Parser Constraints (CRITICAL):** Before calling the import
    operation, ensure your local HCL complies with the ADC registry's strict
    ingestion rules:

    *   **Pure Module Policy (No Resource Blocks):** The ADC parser strictly
        **prohibits any `resource` blocks** inside the imported HCL. Only
        `module`, `variable`, `output`, and `provider` blocks are allowed. If a
        resource is required (e.g. Private Service Access peering) but no
        standalone module is registered for it in the catalog, you MUST check if
        it is supported as a built-in configuration option inside an existing
        registered module (e.g. setting `private_service_access_config` inside
        `module "vpc"`).
    *   **Strict String Typing:** The ADC parser does not perform implicit type
        coercion from boolean to string. For example, subnet private access must
        be declared as a literal string: `subnet_private_access = "true"`, NOT
        as a boolean `true`.
    *   **No Terraform Block:** The parser strictly prohibits the `terraform {}`
        version constraint block. Omit it entirely from `providers.tf` or
        `main.tf`.

3.  **Import to ADC Template**: Once the template resource is confirmed to exist
    and the HCL is validated against the above constraints, invoke the hosted
    `application_design_center:manage_application_template` MCP tool with the
    `APPLICATION_TEMPLATE_OPERATION_IMPORT_IAC` operation:

    *   **Arguments**:

        *   `project`: The target project ID.
        *   `location`: The GCP deployment region (e.g., `us-central1`).
        *   `spaceId`: The discovered ADC space ID.
        *   `applicationTemplateId`: A unique name for your application
            template.
        *   `operation`: `APPLICATION_TEMPLATE_OPERATION_IMPORT_IAC`
        *   `iacModule`: A structured object containing the files list:

            ```json
            {
              "files": [
                { "name": "main.tf", "content": "<content of main.tf>" },
                { "name": "variables.tf", "content": "<content of variables.tf>" },
                { "name": "terraform.tfvars", "content": "<content of terraform.tfvars>" }
              ]
            }
            ```

    *   **Resilience & Retries (MANDATORY)**:

        *   If the `IMPORT_IAC` call fails due to a transient error (e.g., `502
            Bad Gateway`, `504 Gateway Timeout`, or `429 Rate Limit`), **do not
            immediately retry**.
        *   Use **exponential backoff with jitter** (e.g., waiting 2s, 4s, 8s
            plus a random fraction of a second).
        *   **Verify Revision before Retry**: If a timeout occurred, first call
            `gcloud alpha design-center spaces application-templates describe`
            to check if the import actually succeeded in the background. Only
            retry if the template was not updated.

4.  **Capture Template URI**: Upon success, this establishes the template
    resource in your space. Construct the `applicationTemplateUri` using the
    pattern:
    `projects/{project}/locations/{location}/spaces/{spaceId}/applicationTemplates/{applicationTemplateId}`

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

## Phase 4: Application Deployment & Monitoring

**Goal**: Deploy the validated, best-practice-compliant application template to
the GCP environment.

1.  **Deploy Application**: Invoke the hosted
    `application_design_center:manage_application` MCP tool with the
    `APPLICATION_OPERATION_DEPLOY` operation:
    *   **Arguments**:
        *   `project`: Target project ID.
        *   `location`: Target deployment location.
        *   `spaceId`: Target space ID.
        *   `applicationId`: A unique ID for the deployed application instance.
        *   `applicationTemplateUri`: The URI established in Phase 3.
        *   `serviceAccount`: The deployment service account.
    *   **Resilience & Retries (MANDATORY)**:
        *   If the `DEPLOY` operation fails with transient network or gateway
            errors (e.g., `502`, `504`), apply **exponential backoff with
            jitter** before retrying.
        *   If the deployment LRO times out or fails with a state conflict,
            verify the application status using `gcloud design-center spaces
            applications describe` to confirm its status before retrying the
            deploy call, avoiding concurrent conflicting deployments.
2.  **Active LRO Monitoring**:
    *   The tool returns a Long-Running Operation (LRO). Inform the user that
        the deployment has started.
    *   **Do not sleep** during deployment status polling. Poll the LRO actively
        every 30–60 seconds until `done: true` using the command `gcloud
        design-center operations describe <operation_name>`.
3.  **Handle Results**:
    *   **Success**: If `done` is `true` and there is no `error` field, proceed
        to Phase 6.
    *   **Failure**: If an `error` field is present, analyze the error type and
        proceed to Phase 5.

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

## Phase 5: Troubleshoot Deployment Failures

**Goal**: Diagnose and remediate deployment failures iteratively using the
specialized troubleshooting skill and established cloud resolution patterns.

1.  **Iterative Cloud Resolution Patterns (CRITICAL):** If the deployment fails
    with a `REVISION_FAILED` or `TERRAFORM` error, check for these common
    resource conflicts:

    *   **Service Account 409 Conflict (`alreadyExists`):** If the deployment
        fails because a service account generated by the module (e.g.
        `frontend-service-us-central-sa`) already exists in the project,
        remediate the local HCL by disabling service account creation and
        referencing the existing one:

        ```hcl
        create_service_account = false
        service_account        = "<existing_service_account_email>"
        ```

    *   **Container Image 404 NotFound:** If the deployment fails because a
        container image is not found, confirm that the image exists in your
        registry. For testing or hello-world deployments, leverage the official
        public Google hello-world image:
        `us-docker.pkg.dev/cloudrun/container/hello`

2.  **Delegate to the Troubleshooting Skill**: If a deployment failure occurs
    and does not match the above patterns, invoke and execute the specialized
    `infra-deployment-debugging` guide (located in
    [infra-deployment-debugging](references/troubleshooting_guide.md)).

3.  **Select the Troubleshooting Context**:

    *   **For Local Validation Errors (Phase 1/2)**: Follow **Case B: Raw
        Terraform Deployment** instructions in the troubleshooting skill to
        isolate syntax, compilation, and plan-time validation errors.
    *   **For Cloud Deployment Failures (Phase 4)**: Follow **Case A: ADC
        Application Deployment** instructions in the troubleshooting skill to
        analyze LRO errors, retrieve service logs, and diagnose cloud
        environment issues.

4.  **Apply Local-First Remediation**:

    *   Follow the troubleshooting skill's remediation guides to formulate a
        fix.
    *   **MANDATORY**: Apply the fix directly to your **local HCL files** in the
        scratch directory, re-run local validation, re-import the HCL, and
        trigger a new deployment.
    *   Re-run Phase 1 local validation and plan export:

        ```bash
        terraform validate && terraform plan -out=tfplan && terraform show -json tfplan > tfplan.json
        ```

    *   Re-run the plan assessment (Phase 2) to ensure no new violations are
        introduced.

    *   Re-import the corrected HCL to ADC using
        `APPLICATION_TEMPLATE_OPERATION_IMPORT_IAC`.

    *   Trigger a new deployment using `APPLICATION_OPERATION_DEPLOY`.

5.  **Iteration Threshold**: Repeat the troubleshooting, validation, import, and
    redeployment cycle up to five (5) times. If it still fails, report the full
    history and diagnostics to the user.

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

## Phase 6: Verification & E2E Testing

**Goal**: Confirm that the deployed services are healthy and fully functional.

1.  **Retrieve Deployed Resources**: Invoke the hosted
    `application_design_center:manage_application` MCP tool with the
    `APPLICATION_OPERATION_GET` operation to retrieve the resource details,
    public endpoints, and output parameters.
2.  **Health Check**: Verify that all services are using the correct container
    image URLs and that their runtime status is healthy.
3.  **E2E Validation**: Conduct a simple demo test (e.g., checking public HTTP
    endpoints or triggering a dry-run transaction) to ensure E2E functionality.
    Present the results and public URLs to the user to conclude the task.

## Reporting Issues

Report bugs or improvements for this skill at [Google Skills Issues](https://github.com/google/skills/issues).
references/
adc_application_troubleshooting.md 6.6 KB
# ADC Application Troubleshooting Process

Use this template to analyze and resolve deployment failures in Application
Design Center (ADC). This process relies exclusively on standard `gcloud`
commands and does not use any custom backend tools.

## Objective & Goals

Analyze a deployment error for a given ADC application and provide the minimal,
safest change required to eliminate the reported error.

## Constraints

-   **Use gcloud**: All interactions with ADC and Google Cloud must be performed
    using standard `gcloud` commands.
-   **No Real Deployments**: Do not execute `gcloud design-center spaces
    applications deploy`.
-   **Read-Only Discovery**: Do not run any mutating commands (e.g., modifying
    IAM policies, enabling APIs, or updating configurations) during the
    discovery phase (Steps 1 & 2). Discovery must be strictly read-only.

## Troubleshooting Process

Follow these steps in sequence to troubleshoot the deployment failure:

### Step 1: Fetch the Debugging Context

*   **Input**: An `application_uri` (e.g.,
    `projects/P/locations/L/spaces/S/applications/A`).
*   **Act**: Parse the URI to extract Project ID, Location, Space, and
    Application Name. Run the following command to fetch details:

    ```bash
    gcloud design-center spaces applications describe A --space=S --location=L --project=P
    ```

*   **Analyze**:

    *   Verify that the application `state` is `FAILED`. This debugging workflow
        is designed for failed deployments. If the state is
        `UPDATING_DEPLOYMENT`, you may need to wait or check if it eventually
        fails.
    *   Look for error messages in `deploymentMetadata.error` and identify the
        build ID in `deploymentMetadata.build`. This data is typically only
        present when the state is `FAILED`.
    *   If both `deploymentMetadata.error` and `deploymentMetadata.build` are
        missing, the debugging context is insufficient. Proceed directly to Step
        8 and report failure.

### Step 2: Fetch the Cloud Build Logs

*   **Act**: If a build ID was identified in Step 1, retrieve the raw deployment
    execution logs. The region is typically the same as the location `L`
    extracted in Step 1:

    ```bash
    gcloud builds log BUILD_ID --project=P --region=L
    ```

    *   **Guidance**: To avoid overwhelming your context, consider fetching the
        logs incrementally if they are very large. You can start by reading the
        last 20 to 50 lines (e.g., by piping to `tail`) and increase the amount
        if more context is needed.
    *   **Note**: If the command fails with `NOT_FOUND`, verify the region in
        `deploymentMetadata.error.deploymentFailureResolutionInfo.resolutionLink`
        from Step 1.

*   If no build ID is present, proceed to Step 3 using available context.

### Step 3: Analyze the Error and Determine Remediation

*   **Act**: Analyze the error message from Step 1 and the logs from Step 2 to
    determine the root cause and identify the failing component.
*   **Guidance**: Refer to the detailed
    [Error Analysis Guide](error_analysis_guide.md) for heuristics on:
    *   **Identifying the Component**: Mapping Terraform resource names in logs
        to ADC component names.
    *   **Classifying the Error**:
        *   **Config Issues** (validation/compatibility): Fetch the component
            schema (see below) and then proceed to Step 4.
        *   **Resource Conflicts** (already exists): Proceed to Step 4 (to
            update the resource name).
        *   **IAM/API Issues** (permission denied/API disabled): Proceed to
            Step 5.
*   **Fetch Component Schema (Conditional)**: If you identified a configuration
    issue, fetch the schema for the failing component to understand its
    supported parameters.

    *   **Command**:

        ```bash
        gcloud design-center spaces shared-templates describe SHARED_TEMPLATE_NAME --space=SPACE_ID --location=LOCATION --project=PROJECT_ID
        ```

    *   **Note**: The `SHARED_TEMPLATE_NAME`, `SPACE_ID`, `LOCATION`, and
        `PROJECT_ID` must be extracted from the `sharedTemplateRevisionUri`
        found in the application details in Step 1. The URI typically follows
        the format:
        `projects/PROJECT_ID/locations/LOCATION/spaces/SPACE_ID/sharedTemplates/SHARED_TEMPLATE_NAME/revisions/REVISION`.

*   Choose only one remediation path.

### Step 4: Remediation via Configuration Changes

*   **Guidance**: Refer to the [Remediation Guide](remediation_guide.md) for
    details on constructing configuration changes.
*   **Reason**: Determine the necessary changes to the application
    configuration.
*   **Act**: Construct the suggested changes. Since you cannot apply them
    directly via a tool, you must output them in the final response.
*   Proceed to Step 6 to generate output.

### Step 5: Remediation via gcloud Commands (IAM/API)

*   **Guidance**: Refer to the [Remediation Guide](remediation_guide.md) for
    details on constructing `gcloud` commands.
*   **Reason**: Determine missing permissions or disabled APIs.
*   **Act**: Generate the specific `gcloud` commands to fix the issue.
*   **Validate**: Ensure commands are syntactically correct. Use placeholders
    like `<PRINCIPAL>` if the member cannot be determined.
*   Proceed to Step 7 to generate output.

### Step 6: Generate FINAL Output for Configuration Changes

Construct the complete JSON response object strictly matching this schema:

```json
{
  "overall_status": {
    "agent_failed": false,
    "reason": ""
  },
  "troubleshooting_result": {
    "summary": "Concise summary of the error and fix.",
    "troubleshooting_steps": [
      {
        "description": "Description of the change.",
        "component_parameters": [
          {
            "component_uri": "projects/P/locations/L/spaces/S/applicationTemplates/A/components/C",
            "parameters": [
              { "key": "param_key", "value": "param_value" }
            ]
          }
        ]
      }
    ]
  }
}
```

### Step 7: Generate FINAL Output for gcloud Commands

Construct the complete JSON response object strictly matching this schema:

```json
{
  "overall_status": {
    "agent_failed": false,
    "reason": ""
  },
  "troubleshooting_result": {
    "summary": "Concise summary of the error and fix.",
    "troubleshooting_steps": [
      {
        "description": "Description of the command.",
        "gcloud_command": "gcloud command here"
      }
    ]
  }
}
```

### Step 8: Failure Output Generation

If resolution could not be determined:

```json
{
  "overall_status": {
    "agent_failed": true,
    "reason": "Reason for failure"
  },
  "troubleshooting_result": {
    "summary": "",
    "troubleshooting_steps": []
  }
}
```
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:application-design-center-design-deploy)" \
    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:application-design-center-design-deploy)` 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:application-design-center-design-deploy)
    ```

-   **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.
design_guide.md 14.3 KB
---
name: design
description: >-
  Processes cloud architectural design and local validation.
  Use when designing modular Terraform architectures, authoring local HCL, validating HCL via terraform validate, or planning HCL via terraform plan.
  Don't use for deploying templates, plan assessment, or troubleshooting deployment failures.
license: Apache-2.0
metadata:
  version: v1
  publisher: google
  category: CloudInfrastructure
---

# Simplified GCP Modular Terraform Architect Skill

This skill performs an agentic design cycle around a 4-phase generation
pipeline:

```mermaid
graph LR
    A[1. Ingest Intent & Catalog Query] --> B[2. High-Level Architecture Planning]
    B --> C[3. Module-Only Gen & CLI Validation]
    C --> D[4. Semantic Review & Handover]
    D -->|"Goals Unmet"| B
```

You MUST follow these 4 explicit phases strictly in order. You must not skip
phases. If the semantic review in Phase 4 determines that the configuration does
not fully meet the user's architectural goals or intent, you MUST loop back to
Phase 2 to replan and regenerate.

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

## ⚠️ Strict Architectural Constraints

All generated configurations must prioritize the modular structure while
adhering to naming and HCL style constraints. Refer to:

-   `generator_instructions.md` for generation constraints and
    project defaults.
-   `terraform_validator_instructions.md` for semantic validation
    rules.

General defaults & policies:

-   **Default Network and Subnetwork:** Target the pre-existing VPC network and
    subnetwork both named `"default"` in `<project_id>` unless otherwise
    specified.
-   **Secret-Safe Policy (MANDATORY):** NEVER write plaintext passwords, API
    keys, or credentials in HCL code or `terraform.tfvars`. All secrets must be
    declared as resources in GCP Secret Manager (using the
    `terraform-google-secret-manager` module) and referenced dynamically by
    target services.
-   **State Isolation Policy (MANDATORY):** Keep the Terraform state local in
    the scratch folder for validation. NEVER generate a remote backend block
    (e.g., `backend "gcs" {}`), as remote state is managed dynamically by the
    parent orchestrator/deployment registry.

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

## Phase 1: Ingest Intent & Catalog Query

1.  **Load Inputs:** Ingest user goals and instructions.
2.  **Query Catalog Registry (Private and Public):** To supplement the design,
    search both your project's custom private catalog and the public Google
    catalog by calling the native **`manage_catalog`** MCP tool with the
    **`CATALOG_OPERATION_LIST_COMPONENTS`** operation.

    *   **Query Private Catalog (Target Space):**

        *   ServerName: `application_design_center`
        *   ToolName: `manage_catalog`
        *   Arguments:

            ```json
            {
              "project": "<project_id>",
              "location": "<location>",
              "spaceId": "<space_id>",
              "operation": "CATALOG_OPERATION_LIST_COMPONENTS"
            }
            ```

    *   **Query Public Google Catalog:**

        *   ServerName: `application_design_center`
        *   ToolName: `manage_catalog`
        *   Arguments:

            ```json
            {
              "project": "gcpdesigncenter",
              "location": "us-central1",
              "spaceId": "googlespace",
              "catalogId": "googlecatalog",
              "operation": "CATALOG_OPERATION_LIST_COMPONENTS"
            }
            ```

    -   *Priority Rule:* You MUST prioritize using private catalog templates
        (found in your target space) over public Google ones to ensure
        project-specific customizations are respected.

3.  **Get Module Details:** Fetch detailed module metadata containing inputs,
    outputs, and dependencies by calling the native **`manage_catalog`** MCP
    tool with the **`CATALOG_OPERATION_GET_COMPONENT_METADATA`** operation (or
    **`CATALOG_OPERATION_GET_COMPONENT_IAC`** to retrieve the underlying
    Terraform source code directly):

    *   **MCP Tool Call:**

        *   ServerName: `application_design_center`
        *   Tool Name: `manage_catalog`
        *   Arguments:

            ```json
            {
              "project": "<project_id>",
              "location": "<location>",
              "spaceId": "<space_id>",
              "catalogTemplateId": "<short_module_id>",
              "catalogTemplateRevisionId": "<revision_id>",
              "operation": "CATALOG_OPERATION_GET_COMPONENT_METADATA"
            }
            ```

    -   *Constraint:* Pass only the short module ID (e.g., `cloud-run-job`,
        which is the last segment of the fully qualified resource name), NOT the
        full resource name path returned by the list command.

    > [!IMPORTANT] To ensure your local HCL declarations perfectly match the
    > version constraints validated by the Design Center registry, you MUST
    > extract the precise Git repository tag from the registry and use it in
    > your HCL module `source`.
    >
    > The `gitSource` metadata block (including `refTag`, `repo`, and `dir`) is
    > returned directly in the output of the **`manage_catalog`** MCP tool
    > (under the `gitSource` field).
    >
    > If you need to fallback to the CLI to describe the revision details, you
    > can run the `describe` command directly using the revision URI retrieved
    > from the MCP tool:
    >
    > ```bash
    >    gcloud design-center spaces catalogs templates revisions describe <revision_uri>
    > ```
    >
    > 1.  **Extract the fields** from the `gitSource` block:
    >
    >     ```yaml
    >     gitSource:
    >       dir: modules/v2
    >       refTag: v0.33.0
    >       repo: GoogleCloudPlatform/terraform-google-cloud-run
    >     ```
    >
    > 2.  **Construct the HCL `source` URI** using the pattern
    >     `github.com/<repo>//<dir>?ref=<refTag>`:
    >
    >     ```terraform
    >     source = "github.com/GoogleCloudPlatform/terraform-google-cloud-run//modules/v2?ref=v0.33.0"
    >     ```

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

## Phase 2: High-Level Architecture Planning

1.  **Resource Initialization (MANDATORY):** Before formulating any plan, you
    MUST read instructions from `planner_instructions.md`. Do not
    proceed until these instructions are in your active context.
2.  **Design the High-Level Architecture:** Based on the modules identified in
    Phase 1, plan the design topology connecting the key modular building blocks
    (VPC, Compute, Databases, Security).
3.  **Formulate Integration Pattern Decisions:** Determine core pattern layout
    decisions (such as GKE vs. Cloud Run computing model, storage engines,
    network boundaries, private interconnects, and database hosting structures)
    using available modules.
    -   *Note:* Follow Google best practices while formulating a pattern. For
        example:
        1.  Always use Secret Manager to store and reference database
            credentials instead of using passphrases as input parameters.
        2.  Use Private Service Connect instead of public access for private
            connectivity.
4.  **Gather pre-existing reusable TF modules:** Check if there are any
    preexisting TF modules from the catalog to understand available building
    blocks to create end to end solution matching user intent. Catalog contains
    modules public catalog (published by GCP) and private catalog owned by the
    customer. When there is a duplicate module between public and private
    catalog, always prefer private catalog component/module. Inspect the
    selected modules by calling the native **`manage_catalog`** MCP tool with
    the **`CATALOG_OPERATION_GET_COMPONENT_METADATA`** operation to verify
    inputs, outputs, required inputs, and reference outputs:

    *   **MCP Tool Call:**

        *   ServerName: `application_design_center`
        *   Tool Name: `manage_catalog`
        *   Arguments:

            ```json
            {
              "project": "gcpdesigncenter",
              "location": "us-central1",
              "spaceId": "googlespace",
              "catalogId": "googlecatalog",
              "operation": "CATALOG_OPERATION_GET_COMPONENT_METADATA",
              "catalogTemplateId": "<module_id>"
            }
            ```

    -   *Constraint:* Use the short module ID (the last segment of the resource
        name, e.g., `cloud-run-job`), NOT the full resource path starting with
        `projects/...`. If querying a private catalog, update the `project`,
        `spaceId`, and `catalogId` arguments accordingly.

5.  **Review End to End Solution Templates:** Review well-architected solutions
    published by GCP as well as solutions published by the customer's own
    organization. Use these solutions as reference architectures when
    applicable. To explore available templates, run the local CLI script
    `list_terraform_templates` to see if a pre-existing application template can
    serve as your design baseline. You MUST pass your active target project ID
    and space ID to retrieve both public Google templates and private templates:

    ```bash
    python3 scripts/list_terraform_templates.py --project="<project_id>" --space_id="<space_id>" --catalog_id="<catalog_id>"
    ```

    -   *Priority Rule:* In the returned list, private application templates
        appear first (marked with `"source": "private"`). You MUST prioritize
        using private application templates over public Google ones (marked with
        `"source": "google"`) if a suitable private template is available!

6.  **Fetch Terraform Template:** Fetch the baseline template config to your
    local workspace by running the local CLI script `fetch_terraform_template`.
    You MUST pass your active target project ID and space ID:

    ```bash
    python3 scripts/fetch_terraform_template.py <template_id> --project="<project_id>" --space_id="<space_id>" --out_dir="<target_directory_path>"
    ```

    (the output directory will be created automatically if it does not exist).

7.  **Review Planner Principles:** Crosscheck planning directives in
    `planner_instructions.md`.

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

## Phase 3: Module-Only Generator & CLI Validation Loop

1.  **Resource Initialization (MANDATORY):** Before writing any HCL, you MUST
    read instructions from `generator_instructions.md`. Do not
    proceed until these instructions are in your active context.
2.  **Generate Raw HCL:** Write standard Terraform code, prioritizing module
    blocks as much as possible, or using direct resources where no suitable
    module is available, based on rules in the loaded instructions.
3.  **Save Configuration File:** Create a dedicated workspace scratch directory
    unique to this execution/session (e.g. `scratch/tf_validate_{session_id}/`,
    using the session, conversation, or a unique run ID to avoid concurrent
    executions overwriting one another) and write the generated HCL code split
    into:
    -   `providers.tf`: Provider and terraform blocks.
    -   `main.tf`: Module and resource declarations.
    -   `variables.tf`: Variable declarations.
    -   `terraform.tfvars`: Variable values.
    -   `outputs.tf`: Output declarations.
4.  **Semantic Architecture Validation (MANDATORY):** Before running any CLI
    validation, you MUST read instructions from
    `terraform_validator_instructions.md`. Perform a comprehensive
    semantic audit to ensure the configuration complies with the validator
    guidelines (preferring modules over resources, no custom variables, correct
    GitHub source formatting, etc.). Do not proceed until these instructions are
    in your active context.
5.  **Execute Local CLI Validation Check (CRITICAL):**

    -   Initialize the directory using the Terraform CLI directly to pull CFT
        sources and download provider plugins:

        ```bash
        terraform -chdir=scratch/tf_validate_{session_id}/ init
        ```

    -   Validate HCL block structures and type connections using the Terraform
        CLI directly:

        ```bash
        terraform -chdir=scratch/tf_validate_{session_id}/ validate
        ```

    -   Dry-run resource changes and verify configuration feasibility with the
        Terraform CLI:

        ```bash
        terraform -chdir=scratch/tf_validate_{session_id}/ plan
        ```

    -   *Remediation Loop:* If errors or warnings are reported by the Terraform
        CLI during initialization, validation, or planning, correct `main.tf`
        and repeat the check commands until clean.

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

## Phase 4: Semantic Review & Handover

Your final modular code must be clean, robust, and securely wired.

1.  **Semantic Review & Goal Alignment:** Audit the validated configuration
    against the user's intent and architectural constraints. If the architecture
    fails to meet the goal or requires adjustment, loop back to **Phase 2:
    High-Level Architecture Planning** to replan and regenerate.
2.  **Deliver Architectural Rationale:** Output a clear, thorough final report
    that describes:
    -   The **High-Level Architecture Layout**: Clear overview detailing each
        module or resource block and its structural role in the GCP
        infrastructure.
    -   The **Architectural Rationale**: Explicit decisions for why specific
        compute systems, boundaries, and database models were picked. Explain
        the necessity of using direct resources if any were created instead of
        modules. If multiple products were considered, include rationale for
        product choice.
    -   The **Inter-Module Topology & Dataflow**: A descriptive text-based
        walk-through of how data flows between the VPC network boundaries,
        computing blocks, and dependent database components.
3.  **Output Intact Terraform Code:** Read each generated file (including `.tf`
    and `.tfvars` files) in the target validation directory (using your standard
    file viewing/reading tools) and output its exact, intact HCL configuration
    in your final response. Each file MUST be formatted as:

    ````markdown
    File: `<path>`
    ```hcl
    [content]
    ```
    ````

    Ensure you output the complete and exact file contents for all final
    validated files.
error_analysis_guide.md 6.6 KB
# ADC Deployment Error Analysis Guide

This guide provides heuristics and examples for analyzing deployment errors in
Application Design Center (ADC).

## 1. Identifying the Failing Component

Deployment failures usually manifest as Terraform errors in the Cloud Build
logs. To fix the issue, you must first identify which ADC component corresponds
to the failing Terraform resource.

*   **Naming Convention**: ADC generates modular Terraform. In error logs,
    resources are typically referenced by their module path:
    `module.<component_name>.<resource_type>.<resource_internal_name>`.
    *   Example: In `module.sql-postgresql-1.google_sql_database_instance.db`,
        the component name is `sql-postgresql-1`.
    *   *Note for Composite Templates*: Native components may be grouped under a
        single module named `native-components` (e.g.,
        `module.native-components.google_compute_instance.vm`). For these, you
        must identify the component by matching resource parameters (like names
        or labels) back to the SAT.
*   **Mapping**: Locate the component in the Serialized Application Template
    (SAT) where the `uri` ends with `.../components/<component_name>`.
    *   Example:
        `projects/P/locations/L/spaces/S/applicationTemplates/A/components/sql-postgresql-1`.

## 2. Analyzing the Component Schema

For **Configuration** errors, you must analyze the component schema (fetched in
`SKILL.md` Step 3) to identify invalid parameters.

*   **Key Schema Sections**:
    *   `connectionDefinitions`: Details the parameters that connect components.
    *   `properties`: Defines the allowed parameters, their types, descriptions,
        and constraints.
    *   `required`: Lists parameters that must be specified.
*   **Analysis Method**: Compare the parameters in the application configuration
    (from Step 1) with the schema definitions to identify mismatches (e.g.,
    invalid values, missing required fields, or incorrect types).

## 3. Error Classification & Remediation Heuristics

Analyze the error message (from `deploymentMetadata.error` or Cloud Build logs)
and classify it to determine the remediation path.

Error Pattern (Substring)                                                     | Error Category        | Root Cause                                                 | Remediation Path                                                                   | Example Remediation
:---------------------------------------------------------------------------- | :-------------------- | :--------------------------------------------------------- | :--------------------------------------------------------------------------------- | :------------------
`incompatible`, `must be one of`, `constraint violation`, `validation failed` | **Configuration**     | Invalid or conflicting parameters in component definition. | **Step 4 (Config Change)**: Update the invalid parameter in the SAT.               | Update `edition` to `ENTERPRISE_PLUS` if `tier` requires it.
`duplicate`, `already exists`, `Conflict`, `409`                              | **Resource Conflict** | Resource name is already in use in the target project.     | **Step 4 (Config Change)**: Update the `name` or `id` parameter to a unique value. | Change `name` of SQL instance from `my-db` to `my-db-unique-1`.
`Permission denied`, `403`, `caller does not have permission`                 | **IAM Permission**    | Deployment service account lacks required GCP permissions. | **Step 5 (gcloud IAM)**: Grant the required role to the SA.                        | `gcloud projects add-iam-policy-binding ... --role=roles/bigquery.dataEditor`
`API not enabled`, `has not been used in project`, `disabled`                 | **API Disabled**      | Required GCP service API is not enabled in the project.    | **Step 5 (gcloud API)**: Enable the API.                                           | `gcloud services enable compute.googleapis.com`

## 4. Generic Examples

### Example 1: Incompatible Configuration (Config Error)

*   **Generic Error Pattern**:

    ```
    Error: ... [PARAMETER_A] [VALUE_A] is incompatible with [PARAMETER_B] [VALUE_B].
    ```

    *   *Example*: `Instance edition ENTERPRISE is incompatible with tier
        db-perf-optimized-N-8.`

*   **Analysis**: Two parameters of the same component have conflicting values.
    The component schema or provider validation defines compatibility rules that
    are violated.

*   **Remediation**: Identify the component from the resource name in the log
    (e.g., `google_sql_database_instance.<component_name>`). Update one of the
    conflicting parameters in the SAT to a compatible value (refer to the
    component schema fetched in Step 3).

### Example 2: Duplicate Configuration (Config Error)

*   **Generic Error Pattern**:

    ```
    Error: Duplicate [FIELD] definition '[VALUE]' for [PARENT] '[PARENT_VALUE]' in [PARAMETER_NAME].
    ```

    *   *Example*: `Duplicate path definition '/*' for host 'example.com' in
        host_path_mappings.`

*   **Analysis**: A parameter that expects unique keys (or unique combinations
    of fields) contains duplicates.

*   **Remediation**: Locate the component. Update the parameter in the SAT to
    remove the duplicate entry.

### Example 3: Missing Permission (IAM Error)

*   **Generic Error Pattern**:

    ```
    Error: googleapi: Error 403: Permission '[PERMISSION_NAME]' denied on resource '[RESOURCE_URI]' (or it may not exist).
    ```

    *   *Example*: `Error: googleapi: Error 403: Permission
        'bigquery.datasets.create' denied on resource 'projects/my-project'`

*   **Analysis**: The deployment service account (principal) lacks the
    permission `[PERMISSION_NAME]` required to create or modify
    `[RESOURCE_URI]`.

*   **Remediation**:

    1.  Identify the service account used for deployment (typically found in the
        application details fetched in Step 1).
    2.  Determine the GCP role that grants `[PERMISSION_NAME]`.
    3.  Construct a `gcloud` command to grant that role to the service account.
    4.  *Template*: `gcloud projects add-iam-policy-binding <PROJECT_ID>
        --member='serviceAccount:<SA_EMAIL>' --role='<ROLE>'`

### Example 4: Resource Conflict (Conflict Error)

*   **Generic Error Pattern**:

    ```
    Error: ... Error 409: The [RESOURCE_TYPE] already exists.
    ```

    *   *Example*: `Error: Error creating Instance: googleapi: Error 409: The
        instance already exists., alreadyExists`

*   **Analysis**: A resource with the same name/identifier already exists in the
    target GCP project/location.

*   **Remediation**: Locate the component in the SAT. Update its name or
    identifier parameter to a new, unique value.
generator_instructions.md 8.4 KB
# Generator & Code Builder CLI Instructions

You generate raw Terraform configurations, prioritizing **module declarations**
as much as possible or using direct resources where modules are unavailable or
insufficient, ensuring a fully static, well-architected production layout.

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

## 1. Strict HCL and Resource Constraints

-   **Module Preference over Direct Resources:** Prioritize using approved
    modules from the registry or templates as much as possible. Direct
    `resource` blocks are allowed ONLY when no approved module is available or
    to complement modular configurations where direct resource definition is
    necessary.
-   **Match Input Code Style:** If the user provides existing HCL/Terraform code
    as part of their prompt or input files, prioritize matching their style and
    structure exactly. Do not rewrite their code to use modules unless
    explicitly requested.
-   **Enforce Pinned GitHub Source Format:** Under all circumstances, all
    `module` block `source` declarations MUST use their Git/GitHub repository
    source path (e.g., `github.com/...` with `https://` prefix removed) instead
    of the Terraform Registry format.
-   **Mandatory Version Pinning (CRITICAL):** The Git source URI MUST always
    contain the `ref` tag (e.g., `?ref=vX.Y.Z`). This tag **MUST be exactly the
    same** as the `refTag` declared in the `gitSource` metadata of the
    corresponding component resource in the Design Center registry. You MUST
    query the component's active revision metadata (using `gcloud alpha
    design-center spaces catalogs templates revisions describe`) to extract the
    exact `refTag` (e.g., `v0.33.0`) and construct the pinned source path. For
    example, use
    `"github.com/GoogleCloudPlatform/terraform-google-cloud-run//modules/v2?ref=v0.33.0"`
    instead of a version-less path.
-   **Use Configurable Variables:** Parameterize your configuration using
    `variable` blocks for environment-specific values (like project ID, region,
    resource names). Define these variables in `variables.tf` and provide
    default values in `terraform.tfvars`.
-   **Allowed Standard HCL Blocks:** Standard `terraform`, `provider`,
    `variable`, and `output` blocks are fully allowed.
    -   **DO** use `output` blocks to expose key references (endpoints,
        connection names).
    -   **MUST DO:** You MUST include standard `terraform` (declaring required
        providers like `hashicorp/google` with a minimum version query) and
        `provider "google"` blocks configured with appropriate defaults (such as
        targeting project `"test-cf-1"` and region `"us-central1"`). Failing to
        include these configuration definitions will break the hermetic local
        validation routine (`terraform init/validate/plan`) performed in
        Phase 3.
-   **NO Complex HCL Logic:** Do **NOT** use iteration syntax (`for_each`,
    `count`), conditional ternary logic, or `locals` blocks unless explicitly
    required. Keep structures flat and declarative.

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

## 2. Project Context

-   **Target Project ID:** Always assume that the target GCP project context is
    established. The default project ID is `"test-cf-1"`. When parameterizing
    input fields or passing a project ID to any modules, use `"test-cf-1"`
    directly, unless the user explicitly specifies a different project ID.
-   **Static Project Definitions:** Do not dynamically fetch or lookup the
    project ID; use `"test-cf-1"` statically in module inputs or provider
    definitions.

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

## 3. Inter-Module Bindings & Syntax

-   **Parameter Wiring:** Pass output parameters from one active module to
    another to establish bindings:

    ```terraform
    module "my_service" {
      source       = "github.com/GoogleCloudPlatform/terraform-google-cloud-run//modules/v2"
      vpc_network  = module.my_network.network_name
      db_connector = module.my_database.instance_connection_name
    }
    ```

-   **Never Hardcode Linked Configurations:** Links between layers (e.g.,
    subnets, databases, IAM service accounts) must always reference their
    exporter module outputs, unless referencing pre-existing resources like the
    pre-established network and subnetwork both named `"default"`.

-   **Resource attributes:** If a direct resource is really necessary, configure
    the resource parameters correctly using attributes supported by the GCP
    provider.

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

## 4. Local Terraform Validation Routine (CRITICAL)

You **MUST** write the code to a local file and test its syntactic correctness
directly using the Terraform CLI:

1.  **Create a Validation Folder:** Create a unique temporary workspace
    directory inside the user's active workspace (e.g.,
    `scratch/tf_validate_<session_id>/`, where `<session_id>` is a unique run,
    conversation, or session ID) to guarantee concurrent executions do not
    overwrite one another.
2.  **Save the Configuration:** Save your raw configuration split into standard
    files in `scratch/tf_validate_<session_id>/`:
    -   `providers.tf`: Provider and terraform blocks.
    -   `main.tf`: Module and resource declarations.
    -   `variables.tf`: Variable declarations.
    -   `terraform.tfvars`: Variable values.
    -   `outputs.tf`: Output declarations.
3.  **Initialize the Directory:** Initialize the catalog source modules and core
    google providers by running `terraform init` inside that directory:

    ```bash
    terraform -chdir=scratch/tf_validate_<session_id>/ init
    ```

4.  **Run Validation:** Run `terraform validate` to ensure all inputs,
    connections, and block values map correctly:

    ```bash
    terraform -chdir=scratch/tf_validate_<session_id>/ validate
    ```

5.  **Generate Execution Plan:** Run `terraform plan` to dry-run resource
    changes and verify configuration feasibility:

    ```bash
    terraform -chdir=scratch/tf_validate_<session_id>/ plan
    ```

    -   If any of the CLI commands print failures, errors, or configuration
        mismatches during initialization, validation, or planning, modify
        `main.tf` to resolve them and repeat.

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

## 5. Architecture-Aware Parameterization

-   **Architecture-Aware Parameterization:** Configure module parameters to
    align with specified architectural requirements instead of relying on
    minimalist, single-instance defaults. For example, if a high-availability
    database setup is requested, ensure you configure the module with
    appropriate parameters (e.g., multiple read replicas for a MySQL instance,
    multi-zone/regional failover, etc.).

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

## 6. Unique Module Instance Naming (CRITICAL)

To prevent naming conflicts (e.g., 409 Conflict) when deploying multiple
instances or redeploying after a failed run:

-   **Parameterize Module Naming Inputs**: Always expose the key
    name-identifying inputs of your modules (e.g., the `name` parameter in the
    database or secret modules, the `service_name` in the Cloud Run module) as
    variables in `variables.tf`.
-   **Use Unique Defaults**: In `terraform.tfvars` (or as default values in
    `variables.tf`), do not use generic static names. Instead, append a random
    5-character alphanumeric suffix to the value (e.g., `webapp-db-a1b2c`,
    `webapp-frontend-x7y9z`, `db-password-f3g4h`).
-   **Avoid Hardcoding in Modules**: Never hardcode these naming inputs directly
    inside the `module` blocks in `main.tf`. Always reference the corresponding
    variable (e.g., `name = var.db_instance_name`).

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

## 7. Architecture Layout Review

After local validation commands pass cleanly, perform a final architectural
verification check:

1.  **Link Integrity:** Perform a comprehensive audit to ensure all module or
    resource interface mappings connect cleanly.
2.  **Constraint Integrity:** Verify that the configuration prioritizes modules
    as much as possible, using direct resources only when a suitable module is
    unavailable or to complement modular structures where direct resource
    definition is necessary.
planner_instructions.md 2.7 KB
# Planner & Architecture Persona (IaC Focus with Module Preference)

You are an Enterprise GCP Solution Architect under the App Design Center
framework. Your sole objective is to translate design queries into modular,
production-ready Google Cloud architectures, preferring **Terraform modules** as
much as possible, yet supporting direct Terraform resources when necessary.

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

## Core Planning Loop

When you receive a design query, run this simplified 3-step process:

```mermaid
graph LR
    A["1. Query Registry & Architectures"] --> B["2. Convert to TF Module/Resource info"]
    B --> C["3. Generate Preferred-Modular HCL"]
```

### Step 1: Query Terraform Templates, Predefined Architectures, Static Registry, Best Practices, and Architecture Docs

-   Assess the user's design requirements (e.g. need for web hosting, secret
    storage, or a relational database).
-   **Query the modules catalog registry** by calling the native
    `manage_catalog` MCP tool with the `CATALOG_OPERATION_LIST_COMPONENTS`
    operation. Pass the active target project and space ID to retrieve both
    public Google templates and private templates:

    -   *Priority Rule:* In the returned list, private templates appear first
        (marked with `"source": "private"`). You MUST prioritize using private
        catalog templates over public Google ones (marked with `"source":
        "google"`) to ensure project-specific customizations are respected.

-   Retrieve matching GCP services, supported bindings, and properties.

### Step 2: Convert to Equivalent CFT Modules or Terraform Resources

-   Leverage matched approved modules from the fetched template, static
    registry, or predefined architecture templates as your baseline.
-   Identify corresponding approved modules or resources. Prefer using modules;
    fall back to direct resources only if no approved module exists for the
    required service.
-   Inspect module inputs, outputs, and required configurations by calling the
    native `manage_catalog` MCP tool with the
    `CATALOG_OPERATION_GET_COMPONENT_METADATA` operation:
    -   *Constraint:* Pass only the short module ID, which is the last segment
        of the fully qualified resource name (e.g., `cloud-run-job`), NOT the
        full resource path starting with `projects/...`, to determine exact
        inputs, outputs, and requirements.

### Step 3: Plan Module and Resource Integration Flows

-   For the selected modules, pre-plan output-to-input bindings (no
    hardcoding!).
-   Format connections strictly using direct outputs
    (`module.<exporter_name>.<output_name>`).
-   Capture these mappings and topological decisions before generating files.
raw_terraform_troubleshooting.md 4.3 KB
# Raw Terraform Troubleshooting Process

Use this template when troubleshooting direct/raw Terraform deployment errors.

## Troubleshooting Process

Follow these steps in sequence to analyze and resolve the Terraform deployment
failure:

### Step 1: Gather Input Terraform Code

*   **Act**: Identify all Terraform configuration files in the workspace (e.g.,
    `main.tf`, `variables.tf`, `outputs.tf`, `providers.tf`).
*   **Verify**: Read and understand their contents.

### Step 2: Initialize Terraform

*   **Act**: Run the following command in the workspace directory containing the
    HCL files to initialize Terraform and download required modules and
    providers:

    ```bash
    terraform init
    ```

*   **Observe**:

    *   If it fails, analyze the error message.
    *   If it succeeds, proceed to Step 3.

### Step 3: Run Validation

*   **Act**: Run the following command to check if the configuration is
    syntactically valid and internally consistent:

    ```bash
    terraform validate
    ```

*   **Observe**:

    *   If it fails, capture the error message and proceed to Step 5 (Analyze
        and Fix).
    *   If it succeeds, proceed to Step 4.

### Step 4: Run Dry-Run Plan

*   **Act**: Run the following command to create a execution plan and verify
    against the cloud provider's schemas and constraints:

    ```bash
    terraform plan
    ```

*   **Observe**:

    *   If it fails, capture the error message and proceed to Step 5 (Analyze
        and Fix).
    *   If it succeeds, and you have made modifications that resolved previous
        errors, proceed to Step 6 (Generate Output).

### Step 5: Analyze and Fix

*   **Analyze the Error**:
    *   If the error message references a file under `.terraform/modules/`
        (e.g., `.terraform/modules/secret-manager-1/variables.tf`), it means the
        error is due to a mismatch between your configuration and the module's
        expected inputs.
    *   **Act**: Read the referenced module file in `.terraform/modules/` using
        `view_file` to inspect the variable definition, its type constraints,
        default values, and required attributes.
    *   If the error is a Terraform HCL syntax error (e.g., duplicate keys,
        invalid type), locate the line in your local files.
*   **Apply the Fix**:
    *   Modify your local Terraform files (do NOT modify files inside
        `.terraform/modules/`) to fix the error. For example:
        *   Add missing required attributes to variables or module inputs.
        *   Change attribute types to match module schemas.
        *   Remove duplicate block definitions or keys.
*   **Format Files**:
    *   Run `terraform fmt <file_name>` on every Terraform file you modified to
        ensure consistent formatting (spacing, alignment, etc.).
*   **Re-Verify**:
    *   After applying the fix and formatting the files, run `terraform
        validate` (Step 3).
    *   If validation passes, run `terraform plan` (Step 4).
    *   Repeat this loop (Fix -> Format -> Validate -> Plan) until both commands
        succeed without errors.

### Step 6: Generate Output

Construct the complete JSON response object containing the final, fixed
Terraform files and a summary of the troubleshooting.

*   **CRITICAL Constraint**: NEVER run `terraform apply` or any other mutating
    commands under any circumstances. Only use `terraform init`, `terraform
    validate`, and `terraform plan` for dry-run analysis.
*   **Format**: The output must strictly follow the schema below.

```json
{
  "overall_status": {
    "agent_failed": false,
    "reason": ""
  },
  "troubleshooting_result": {
    "summary": "Detailed summary explaining the root cause of the error and how the configuration was fixed.",
    "terraform_files": [
      {
        "name": "main.tf",
        "content": "..."
      },
      {
        "name": "variables.tf",
        "content": "..."
      }
    ]
  }
}
```

If you are unable to resolve the error after multiple attempts (e.g. because of
missing credentials or invalid schemas that cannot be fixed), generate a failure
response:

```json
{
  "overall_status": {
    "agent_failed": true,
    "reason": "Explain why the agent failed to fix the error (e.g., 'terraform init failed with network error')."
  },
  "troubleshooting_result": {
    "summary": "",
    "terraform_files": []
  }
}
```
remediation_guide.md 4.3 KB
# ADC Deployment Remediation Guide

This guide provides instructions on how to construct remediation plans for ADC
deployment failures, mapping analysis results to the required output formats.

## 1. Configuration Remediations (Step 4 & Step 6)

When the error is classified as a **Configuration Issue** or **Resource
Conflict**, the remediation involves suggesting changes to the application's
component parameters.

### 1.1. Constructing Component Parameters

You must identify the exact component and the parameter that needs modification.

*   **Component URI**: Must be the full resource name of the component, NOT just
    the display name.
    *   Format:
        `projects/<PROJECT_ID>/locations/<LOCATION>/spaces/<SPACE_ID>/applicationTemplates/<APP_TEMPLATE_ID>/components/<COMPONENT_NAME>`
    *   Example:
        `projects/my-project/locations/us-central1/spaces/my-space/applicationTemplates/my-app/components/sql-postgresql-1`
*   **Parameter Key**: Use the top-level parameter name as defined in the
    component schema.
    *   **CRITICAL RULE**: Do **NOT** use dotted notation (e.g. `settings.tier`
        or `backup_configuration.enabled`) for nested parameters. The engine
        does not support modifying nested sub-fields via dotted paths. You must
        always target the top-level parameter key (e.g., `settings` or
        `backup_configuration`).
    *   Example: `settings` (Correct) vs `settings.tier` (Incorrect).
*   **Parameter Value**: Specify the new value. Ensure it conforms to the type
    and constraints defined in the component schema.
    *   **Structured Parameters (Objects/Arrays)**: Because updating a parameter
        completely overwrites its existing value, you **MUST** provide the
        complete object or array with all of its fields.
        *   Inspect the original value of the parameter in the input template.
        *   Copy all unchanged sub-fields and values.
        *   Modify only the specific sub-field that requires remediation.

### 1.2. Example: Configuration Fix

**Scenario**: Cloud Run service deployment failed because CPU throttling is
enabled when using GPUs. To resolve this, CPU throttling must be disabled by
setting `cpu_idle` to `false`.

**Remediation JSON Component Parameters**:

```json
[
  {
    "component_uri": "projects/my-project/locations/us-central1/spaces/my-space/applicationTemplates/my-application-template/components/cloud-run-1",
    "parameters": [
      {
        "key": "cpu_idle",
        "value": "false"
      }
    ]
  }
]
```

## 2. gcloud Remediations (Step 5 & Step 7)

When the error is classified as an **IAM Permission** or **API Disabled** issue,
the remediation involves generating `gcloud` commands.

### 2.1. IAM Permission Fixes

Use the minimum required privilege.

*   **Command Template**:

    ```bash
    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SA_EMAIL" --role="roles/ROLE_NAME"
    ```

*   **Identifying the Principal (SA_EMAIL)**:

    *   Look for the service account in the error message (e.g.,
        `service-12345678@gcp-sa-adc.iam.gserviceaccount.com` or the deployment
        SA).
    *   If the service account cannot be determined, use the placeholder
        `<SERVICE_ACCOUNT_EMAIL>`.

*   **Identifying the Role**:

    *   Use the error message to determine what permission is missing (e.g.,
        `compute.instances.create`).
    *   Map the permission to a standard GCP role (e.g., `roles/compute.admin`
        or a more specific role if known).

### 2.2. API Activation Fixes

*   **Command Template**:

    ```bash
    gcloud services enable SERVICE_API_NAME --project=PROJECT_ID
    ```

    *   Example: `gcloud services enable sqladmin.googleapis.com
        --project=my-project`

### 2.3. Combined Example

If multiple commands are needed (e.g., enable API AND grant permission), list
them as separate steps in the final output.

```json
"troubleshooting_steps": [
  {
    "description": "Enable the Cloud SQL Admin API.",
    "gcloud_command": "gcloud services enable sqladmin.googleapis.com --project=my-project"
  },
  {
    "description": "Grant Cloud SQL Editor role to the deployment service account.",
    "gcloud_command": "gcloud projects add-iam-policy-binding my-project --member='serviceAccount:deploy-sa@my-project.iam.gserviceaccount.com' --role='roles/cloudsql.editor'"
  }
]
```
terraform_validator_instructions.md 2.5 KB
# Terraform Validation Guidelines

You act as a semantic validator to review module configurations and verify they
are fully production-ready.

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

## 1. Key Validator Assertions

During validation, verify these parameters:

-   **Enforce Module Preference (CRITICAL):** Verify that the configuration
    prioritizes modules over direct `resource` blocks. Resource blocks are
    allowed only if no suitable approved module is available from the registry
    or templates. Flag any resource block that maps to an available approved
    module.
-   **Match Input Code Style:** If the input has user-provided Terraform/HCL
    code, relax the module-preference check. The validated code should match the
    user's coding style (e.g., resources vs. modules) and not be rewritten in a
    module-centric way.
-   **Static Configuration Checks:** Verify that no `locals`, `for_each`, or
    `count` statements are declared.
-   **Encourage Configurable Variables:** Verify that configurable parameters
    (like project ID, region, resource names) are parameterized using `variable`
    blocks in `variables.tf`, with default values defined in `terraform.tfvars`.
    Avoid hardcoding environment-specific values.
-   **Inspect Inter-Module Output Bindings:**
    -   Enforce that database connection strings, network identifiers (subnets,
        VPC names), and keys/endpoints are set via output bindings from other
        modules, except for pre-existing default configurations (like the
        network or subnet named `"default"`).
    -   Flag manual text assignments that should be structured module-output
        linkages, unless they are intentionally referencing default pre-existing
        GCP project resources like `"default"`.
-   **Enforce Pinned GitHub Source Format:** Ensure that every module's `source`
    uses the GitHub repository source path (e.g., `github.com/...`) instead of
    the registry format.
-   **Assert Mandatory Version Pinning (CRITICAL):** Verify that every single
    module block containing a Git/GitHub source has a `?ref=...` parameter
    appended, and that the tag matches the registry's `refTag` of the
    corresponding component revision exactly. Flag any version-less Git source
    as a critical validation failure.

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

## 2. Handover

If all validations are successfully cleared and the setup matches the design
CUJs, output exactly: **LGTM**.
troubleshooting_guide.md 2.6 KB
---
name: infra-deployment-debugging
description: >-
  Troubleshoots infrastructure deployment failures.
  Use when analyzing deployment failures of ADC applications or direct/raw Terraform deployment errors.
  Don't use for design, local validation, plan assessment, or non-deployment troubleshooting.
license: Apache-2.0
metadata:
  version: v1
  publisher: google
  category: CloudInfrastructure
---

# Deployment Troubleshooting Skill

Use this skill to analyze and resolve deployment failures. This skill supports
troubleshooting:

1.  **ADC Applications**: High-level designs deployed in Application Design
    Center.
2.  **Raw Terraform (TF)**: Infrastructure configurations managed directly via
    Terraform HCL files.

## Constraints

-   **Use standard tools**: All interactions with GCP must be performed using
    standard commands (e.g., `gcloud`, `terraform`). Do not use custom internal
    backend APIs.
-   **No Real Deployments**: NEVER run mutating deployment commands (e.g.,
    `gcloud design-center spaces applications deploy` or `terraform apply`)
    under any circumstances, as this is a read-only validation and dry-run
    troubleshooting workflow.
-   **Read-Only Discovery**: Do not run mutating commands during discovery.
    Discovery must be strictly read-only.
-   **Strict Step Adherence**: You MUST execute all steps in the chosen
    troubleshooting template in sequence. Do NOT skip steps or jump directly to
    remediation, even if the error seems obvious. Every step (e.g., init,
    validate, plan, or describes/logs fetches) must be executed and their
    outputs verified.

## Troubleshooting Process (Progressive Disclosure)

To begin, you must determine the appropriate troubleshooting context based on
the user's input.

### Step 1: Determine the Entry Point

Evaluate the input provided by the user:

-   **Case A: ADC Application Deployment**:
    *   **Indicator**: The input contains an `application_uri` (e.g.,
        `projects/P/locations/L/spaces/S/applications/A`) or references an App
        Design Center context.
    *   **Act**: Read and follow the detailed instructions in
        [adc_application_troubleshooting.md](adc_application_troubleshooting.md)
        to complete the troubleshooting task.
-   **Case B: Raw Terraform Deployment**:
    *   **Indicator**: The input contains raw Terraform configuration code (HCL
        contents), `.tf` files, or direct Terraform plan/apply execution errors.
    *   **Act**: Read and follow the detailed instructions in
        [raw_terraform_troubleshooting.md](raw_terraform_troubleshooting.md)
        to complete the troubleshooting task.
scripts/
fetch_terraform_template.py 9.8 KB
#!/usr/bin/env python3
"""CLI tool to generate and fetch HCL code for a template revision."""

import json
import os
import shutil
import subprocess
import sys
import tempfile
from absl import app
from absl import flags

_PROJECT = flags.DEFINE_string("project", "", "Optional target GCP project ID.")
_LOCATION = flags.DEFINE_string(
    "location", "us-central1", "Design Center location ID."
)
_SPACE_ID = flags.DEFINE_string("space_id", "", "Optional target Space ID.")
_CATALOG_ID = flags.DEFINE_string(
    "catalog_id", "", "Optional target Catalog ID."
)
_OUT_DIR = flags.DEFINE_string(
    "out_dir", "", "Optional local directory path to save the files."
)


def _run_cmd(cmd: list[str]) -> str:
  """Runs a command and returns its stdout, raising an error on failure."""
  result = subprocess.run(cmd, capture_output=True, text=True, check=True)
  return result.stdout


def _parse_input(
    input_id: str,
) -> tuple[str, str, str, str, str]:
  """Parses the input resource path or resolves parameters using flags."""
  # Step 1: Parse the input path or resolve using flags
  # Supports full resource paths:
  # projects/{project}/locations/{location}/spaces/{space}/
  # catalogs/{catalog}/templates/{template_id}
  if input_id.startswith("projects/"):
    parts = input_id.split("/")
    try:
      project = parts[1]
      location = parts[3]
      space_id = parts[5]
      if "catalogs" in parts:
        catalog_index = parts.index("catalogs")
        catalog_id = parts[catalog_index + 1]
        short_template_id = parts[catalog_index + 3]
      else:
        catalog_id = _CATALOG_ID.value or "default-catalog"
        short_template_id = parts[-1]
    except (IndexError, ValueError) as e:
      print(f"Error parsing resource path '{input_id}': {e}", file=sys.stderr)
      sys.exit(1)
  else:
    project = _PROJECT.value or "gcpdesigncenter"
    space_id = _SPACE_ID.value or "googlespace"
    location = _LOCATION.value or "us-central1"
    catalog_id = _CATALOG_ID.value or "googlecatalog"
    short_template_id = input_id
  return project, location, space_id, catalog_id, short_template_id


def _get_latest_revision_id(
    project: str,
    location: str,
    space_id: str,
    catalog_id: str,
    short_template_id: str,
) -> str:
  """Describes the Catalog Template to find the latestRevisionId."""
  # Step 2: Describe the Catalog Template to find the latestRevisionId
  describe_template_cmd = [
      "gcloud",
      "alpha",
      "design-center",
      "spaces",
      "catalogs",
      "templates",
      "describe",
      short_template_id,
      f"--project={project}",
      f"--space={space_id}",
      f"--location={location}",
      f"--catalog={catalog_id}",
      "--format=json",
  ]

  try:
    stdout = _run_cmd(describe_template_cmd)
    template_data = json.loads(stdout)
    latest_revision_id = template_data.get("latestRevisionId")
    if not latest_revision_id:
      print(
          f"Error: Catalog template '{short_template_id}' does not have a"
          " latest revision ID.",
          file=sys.stderr,
      )
      sys.exit(1)
    return latest_revision_id
  except subprocess.CalledProcessError as e:
    print(f"Error describing catalog template: {e.stderr}", file=sys.stderr)
    sys.exit(1)


def _get_app_template_revision_source(
    latest_revision_id: str,
    project: str,
    location: str,
    space_id: str,
    catalog_id: str,
    short_template_id: str,
) -> str:
  """Describes the Catalog Template Revision to find the source.

  Args:
    latest_revision_id: The latest revision ID or full resource name.
    project: Target GCP project ID.
    location: Target location ID.
    space_id: Target Space ID.
    catalog_id: Target Catalog ID.
    short_template_id: Short template ID.

  Returns:
    The applicationTemplateRevisionSource.
  """
  # Step 3: Describe the Catalog Template Revision to find
  # applicationTemplateRevisionSource.
  # Revision path: projects/{project}/locations/{location}/spaces/{space_id}/
  # catalogs/{catalog_id}/templates/{short_template_id}/revisions/{rev}
  if latest_revision_id.startswith("projects/"):
    revision_path = latest_revision_id
  else:
    revision_path = (
        f"projects/{project}/locations/{location}/spaces/{space_id}/"
        f"catalogs/{catalog_id}/templates/{short_template_id}/revisions/"
        f"{latest_revision_id}"
    )
  print(
      f"Retrieving Catalog Template Revision: {latest_revision_id}...",
      file=sys.stderr,
  )

  describe_revision_cmd = [
      "gcloud",
      "alpha",
      "design-center",
      "spaces",
      "catalogs",
      "templates",
      "revisions",
      "describe",
      revision_path,
      "--format=json",
  ]

  try:
    stdout = _run_cmd(describe_revision_cmd)
    revision_data = json.loads(stdout)
    app_template_revision_source = revision_data.get(
        "applicationTemplateRevisionSource"
    )
    if not app_template_revision_source:
      print(
          f"Error: Catalog revision '{latest_revision_id}' does not specify an"
          " applicationTemplateRevisionSource.",
          file=sys.stderr,
      )
      sys.exit(1)
    return app_template_revision_source
  except subprocess.CalledProcessError as e:
    print(
        f"Error describing catalog template revision: {e.stderr}",
        file=sys.stderr,
    )
    sys.exit(1)


def _generate_iac(app_template_revision_source: str) -> str:
  """Generates IaC for the Application Template Revision.

  Args:
    app_template_revision_source: Source application template revision.

  Returns:
    The GCS URI.
  """
  # Step 4: Generate IaC for the Application Template Revision
  generate_cmd = [
      "gcloud",
      "alpha",
      "design-center",
      "spaces",
      "application-templates",
      "revisions",
      "generate",
      app_template_revision_source,
      "--format=json",
  ]

  try:
    stdout = _run_cmd(generate_cmd)
    data = json.loads(stdout)
    artifact_location = data.get("artifactLocation") or {}
    gcs_uri = data.get("gcsUri") or artifact_location.get("gcsUri")
    if not gcs_uri:
      print(
          "Error: Generation completed but no GCS URI was returned. Response:"
          f" {stdout}",
          file=sys.stderr,
      )
      sys.exit(1)
    return gcs_uri
  except subprocess.CalledProcessError as e:
    print(
        f"Error generating IaC from application template revision: {e.stderr}",
        file=sys.stderr,
    )
    sys.exit(1)


def _download_from_gcs(gcs_uri: str, local_temp_dir: str) -> None:
  """Downloads files from GCS to local SSD temp directory."""
  # Step 5: Download files from GCS to local SSD temp directory (/tmp)
  gcs_source = f"{gcs_uri.rstrip('/')}/*"
  cp_cmd = ["gcloud", "storage", "cp", "-r", gcs_source, local_temp_dir]

  try:
    _run_cmd(cp_cmd)
  except subprocess.CalledProcessError as e:
    print(f"Error downloading files from GCS: {e.stderr}", file=sys.stderr)
    sys.exit(1)


def _output_files(
    local_temp_dir: str, short_template_id: str, gcs_uri: str
) -> None:
  """Distributes files to target destination or prints HCL content to stdout."""
  working_dir = os.environ.get("BUILD_WORKING_DIRECTORY", os.getcwd())

  # Step 6: Distribute files to target destination
  if _OUT_DIR.value:
    if os.path.isabs(_OUT_DIR.value):
      target_dir = _OUT_DIR.value
    else:
      target_dir = os.path.abspath(os.path.join(working_dir, _OUT_DIR.value))

    os.makedirs(target_dir, exist_ok=True)
    saved_files = []
    for filename in sorted(os.listdir(local_temp_dir)):
      src_file = os.path.join(local_temp_dir, filename)
      if os.path.isfile(src_file):
        dest_file = os.path.join(target_dir, filename)
        shutil.copy2(src_file, dest_file)
        saved_files.append(dest_file)

    print(
        f"SUCCESS: Fetched template '{short_template_id}' and saved files"
        f" to {target_dir}"
    )
  else:
    hcl_files = []
    for filename in sorted(os.listdir(local_temp_dir)):
      file_path = os.path.join(local_temp_dir, filename)
      if os.path.isfile(file_path):
        try:
          with open(file_path, "r", encoding="utf-8") as f:
            content = f.read()
            hcl_files.append(f"# === {filename} ===\n{content}")
        except (OSError, UnicodeDecodeError) as e:
          print(
              f"Warning: Could not read file '{filename}': {e}",
              file=sys.stderr,
          )

    if hcl_files:
      print("\n\n".join(hcl_files))
    else:
      print(
          f"Warning: No files were downloaded from {gcs_uri}", file=sys.stderr
      )


def main(argv: list[str]) -> None:
  if len(argv) < 2:
    print(
        "Usage: fetch_terraform_template <template_path_or_id>"
        " [--project=<project>] [--location=<location>] [--space_id=<space_id>]"
        " [--catalog_id=<catalog_id>] [--out_dir=<out_dir>]",
        file=sys.stderr,
    )
    sys.exit(1)

  project, location, space_id, catalog_id, short_template_id = _parse_input(
      argv[1]
  )

  print(
      "Resolving Catalog Template:"
      f" {project}/{location}/{space_id}/{catalog_id}/{short_template_id}...",
      file=sys.stderr,
  )

  latest_revision_id = _get_latest_revision_id(
      project, location, space_id, catalog_id, short_template_id
  )

  app_template_revision_source = _get_app_template_revision_source(
      latest_revision_id,
      project,
      location,
      space_id,
      catalog_id,
      short_template_id,
  )

  print(
      "Resolved Source Application Template Revision:"
      f" {app_template_revision_source}",
      file=sys.stderr,
  )
  print("Generating IaC for Application Template Revision...", file=sys.stderr)

  gcs_uri = _generate_iac(app_template_revision_source)

  print(f"Downloading HCL code from GCS: {gcs_uri}...", file=sys.stderr)

  # Download files from GCS to local SSD temp directory (/tmp)
  with tempfile.TemporaryDirectory() as local_temp_dir:
    _download_from_gcs(gcs_uri, local_temp_dir)
    _output_files(local_temp_dir, short_template_id, gcs_uri)


if __name__ == "__main__":
  app.run(main)
fetch_terraform_template_test.py 1.4 KB
import subprocess
import unittest
from unittest import mock

import fetch_terraform_template


class FetchTerraformTemplateTest(unittest.TestCase):

  @mock.patch("subprocess.run")
  def test_run_cmd_success(self, mock_run: mock.Mock) -> None:
    mock_run.return_value = mock.Mock(stdout="success output")
    result = fetch_terraform_template._run_cmd(["gcloud", "--version"])
    self.assertEqual(result, "success output")

  @mock.patch("subprocess.run")
  def test_run_cmd_failure(self, mock_run: mock.Mock) -> None:
    mock_run.side_effect = subprocess.CalledProcessError(1, ["cmd"])
    with self.assertRaises(subprocess.CalledProcessError):
      fetch_terraform_template._run_cmd(["invalid_cmd"])

  def test_parse_input_short_id(self) -> None:
    result = fetch_terraform_template._parse_input("my-template")
    self.assertEqual(
        result,
        (
            "gcpdesigncenter",
            "us-central1",
            "googlespace",
            "googlecatalog",
            "my-template",
        ),
    )

  def test_parse_input_full_path(self) -> None:
    full_path = (
        "projects/my-proj/locations/us-east1/spaces/my-sp/catalogs/my-cat/"
        "templates/tpl-123"
    )
    result = fetch_terraform_template._parse_input(full_path)
    self.assertEqual(
        result, ("my-proj", "us-east1", "my-sp", "my-cat", "tpl-123")
    )


if __name__ == "__main__":
  unittest.main()
list_terraform_templates.py 4.0 KB
#!/usr/bin/env python3
"""CLI tool to list Application Templates from Google and Private catalogs."""

import json
import subprocess
import sys
from typing import Any
from absl import app
from absl import flags

_PROJECT = flags.DEFINE_string(
    "project",
    "",
    "Optional target GCP project ID to query your private catalog.",
)
_LOCATION = flags.DEFINE_string(
    "location", "us-central1", "Design Center location ID."
)
_SPACE_ID = flags.DEFINE_string(
    "space_id", "", "Optional target Space ID to query your private catalog."
)
_CATALOG_ID = flags.DEFINE_string(
    "catalog_id",
    "",
    "Optional target Catalog ID to query your private catalog.",
)


def _run_gcloud_list(
    project: str, location: str, space: str, catalog: str
) -> list[dict[str, Any]]:
  """Runs gcloud command to list templates and returns parsed JSON list."""
  cmd = [
      "gcloud",
      "alpha",
      "design-center",
      "spaces",
      "catalogs",
      "templates",
      "list",
      f"--project={project}",
      f"--location={location}",
      f"--space={space}",
      f"--catalog={catalog}",
      "--format=json",
  ]
  try:
    result = subprocess.run(cmd, capture_output=True, text=True, check=True)
    if result.stdout.strip():
      return json.loads(result.stdout)
  except subprocess.CalledProcessError as e:
    print(
        f"Warning: gcloud query failed for space '{space}' in project"
        f" '{project}': {e.stderr}",
        file=sys.stderr,
    )
  except (json.JSONDecodeError, ValueError, TypeError) as e:
    print(f"Warning: Failed to parse gcloud output: {e}", file=sys.stderr)
  return []


def _process_templates(
    templates: list[dict[str, Any]],
    is_private: bool,
    seen_template_ids: set[str],
    aggregated_results: list[dict[str, Any]],
) -> None:
  """Filters and appends structured templates to aggregated results."""
  for template in templates:
    if not isinstance(template, dict):
      continue

    # Filter for APPLICATION_TEMPLATE only
    category = template.get("templateCategory", "")
    if category != "APPLICATION_TEMPLATE":
      continue

    name = template.get("name", "")
    description = template.get("description", "")
    display_name = template.get("displayName", "")

    # Extract unique template ID suffix
    template_id = name.split("/")[-1] if "/" in name else name
    if not template_id:
      continue

    # Skip if already seen (private has priority because it runs first)
    if template_id in seen_template_ids:
      continue

    seen_template_ids.add(template_id)
    aggregated_results.append({
        "name": name,
        "templateId": template_id,
        "description": description,
        "displayName": display_name,
        "templateCategory": category,
        "source": "private" if is_private else "google",
    })


def main(argv: list[str]) -> None:
  del argv  # Unused.
  is_private_query = bool(_PROJECT.value and _SPACE_ID.value)
  private_raw = []

  # Step 1: Query Private Catalog (if project and space are provided)
  if is_private_query:
    target_catalog = _CATALOG_ID.value or "default-catalog"
    private_raw = _run_gcloud_list(
        project=_PROJECT.value,
        location=_LOCATION.value,
        space=_SPACE_ID.value,
        catalog=target_catalog,
    )

  # Step 2: Query Public Google Catalog
  google_raw = _run_gcloud_list(
      project="gcpdesigncenter",
      location="us-central1",
      space="googlespace",
      catalog="googlecatalog",
  )

  aggregated_results = []
  seen_template_ids = set()

  # Process private templates FIRST (priority and top placement)
  if private_raw:
    _process_templates(
        private_raw,
        is_private=True,
        seen_template_ids=seen_template_ids,
        aggregated_results=aggregated_results,
    )

  # Process public Google templates SECOND
  if google_raw:
    _process_templates(
        google_raw,
        is_private=False,
        seen_template_ids=seen_template_ids,
        aggregated_results=aggregated_results,
    )

  print(json.dumps(aggregated_results, indent=2))


if __name__ == "__main__":
  app.run(main)
list_terraform_templates_test.py 0.9 KB
import subprocess
import unittest
from unittest import mock

import list_terraform_templates


class ListTerraformTemplatesTest(unittest.TestCase):

  @mock.patch("subprocess.run")
  def test_run_gcloud_list_success(self, mock_run: mock.Mock) -> None:
    mock_run.return_value = mock.Mock(
        stdout='[{"name": "app1", "templateCategory": "APPLICATION_TEMPLATE"}]'
    )
    result = list_terraform_templates._run_gcloud_list(
        project="p", location="l", space="s", catalog="c"
    )
    self.assertEqual(
        result, [{"name": "app1", "templateCategory": "APPLICATION_TEMPLATE"}]
    )

  @mock.patch("subprocess.run")
  def test_run_gcloud_list_failure(self, mock_run: mock.Mock) -> None:
    mock_run.side_effect = subprocess.CalledProcessError(
        1, ["cmd"], stderr="err"
    )
    result = list_terraform_templates._run_gcloud_list("p", "l", "s", "c")
    self.assertEqual(result, [])


if __name__ == "__main__":
  unittest.main()

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