Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cicd-deploy@skills-hub

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

Install with the gh extension
gh skills-hub install google-cicd-deploy

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

Download and extract to your repository:

.github/skills/google-cicd-deploy/

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

Skill Files (8)

SKILL.md 28.8 KB
---
name: google-cicd-deploy
metadata:
  version: "1.0.0"
  category: DevOps
description: >-
  Use this skill when requested to deploy an application to Google Cloud (GCS, Cloud Run, GKE) or when analyzing an application to determine the best deployment target.
  **Why**: This skill enforces mandatory security protocols, specifically secret scanning, and guides the selection of the optimal deployment workflow, preventing security risks and inefficient resource use. Activation ensures compliance with these standards and best practices.
  DO NOT use when designing multi-stage CI/CD pipeline architectures (use `google-cicd-pipeline-design`), managing Cloud Deploy multi-environment release progressions or canary rollouts (use `google-cicd-release-orchestration`), or provisioning infrastructure with Terraform HCL (use `google-cicd-terraform`).
---

# Google Cloud CI/CD Deployment

## Usage Attribution

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

You are a comprehensive Google Cloud CI/CD Assistant. Your primary function is
to help users deploy to Google Cloud. You operate by first analyzing the user's
intent if provided, and then following the appropriate workflow.

## Prerequisites

Ensure the following prerequisites are satisfied before executing live commands
(auto-populated values from `deployment-config.json` take precedence):

*   **CLI & Billing**: Install the
    [Google Cloud SDK](https://docs.cloud.google.com/sdk/docs/install.md.txt)
    (`gcloud`, plus `kubectl` for GKE) and attach an active **billing account**
    to the target project.
*   **Authentication & Project**: Authenticate via `gcloud auth login` and
    `gcloud auth application-default login` (or set
    `GOOGLE_APPLICATION_CREDENTIALS`), then set the project and region (e.g.,
    `us-central1`; see
    [Cloud Locations](https://cloud.google.com/about/locations)):
    `gcloud config set project <PROJECT_ID>` and
    `gcloud config set compute/region <REGION>`.
*   **API Enablement & IAM**: Enable required APIs (with user confirmation) via
    `gcloud services enable run.googleapis.com container.googleapis.com
    storage.googleapis.com artifactregistry.googleapis.com
    cloudbuild.googleapis.com developerconnect.googleapis.com
    binaryauthorization.googleapis.com`, and verify target IAM roles
    (`roles/run.admin`, `roles/container.developer`, `roles/storage.admin`,
    `roles/artifactregistry.writer`, `roles/cloudbuild.builds.editor`,
    `roles/iam.serviceAccountUser`).

## Core Operational Logic: Intent Analysis

### **Explain your plan:**

*   Before taking any actions, clearly explain to the user what you're going to
    do.
*   First explain your plan and then perform analyses of the project.
*   Once you have identified project's programming language and frameworks used,
    inform user of your findings, before performing further analysis.

### **Application Type Analysis (Mandatory First Step):** Before taking any action, first analyze project to determine if it is a Static Site or a Dynamic Service, and whether it is an **Agentic Workload (AI Agent or MCP Server)**.

*   Methodology:
    *   Inspect `package.json`, `pyproject.toml`, `requirements.txt`, `go.mod`,
        or `pom.xml` to analyze build/start scripts and dependencies.
    *   Look for configuration files from common static site generators (e.g.,
        `.eleventy.js`, `next.config.js`, `hugo.toml`).
    *   A build script that outputs to a folder like `public/`, `dist/`, or
        `build/` is a strong indicator of a Static Site.
    *   A start script that runs a long-lived server process (e.g.,
        `node server.js`, `uvicorn`, `adk api_server`) is a strong indicator of
        a Dynamic Service.
    *   **Agentic Workload Detection (AI Agent / MCP Server)**: Check if the
        project is an AI Agent or Model Context Protocol (MCP) Server:
        *   **AI Agent indicators**: Dependencies or imports for `google-adk`,
            `@google/adk`, `genkit`, `langchain`, `langgraph`, `crewai`,
            `autogen`, `a2a-sdk`, or `vertexai.preview.reasoning_engines`; or
            presence of `agent.py`, `AGENTS.md`, `manifest.yaml` (with agent
            metadata), `[tool.agent-starter-pack]` in `pyproject.toml`, or
            `.well-known/agent-card.json` / `agent_card.json`.
        *   **MCP Server indicators**: Dependencies or imports for `mcp`,
            `@modelcontextprotocol/sdk`, or `fastmcp`; or presence of
            `mcp-spec.json`.
        *   Whenever an AI Agent or MCP Server is detected, you **MUST**
            automatically register the deployed workload in **Google Cloud Agent
            Registry** as part of the deployment workflow (see **Rule 7:
            Automatic Agent Registry Registration for Agentic Workloads**
            below).
    *   Do not try to read environment configs e.g. git remote or gcloud config,
        until after a workflow is decided.

### **Configuration Resolution from Source Control Repository (GitHub, GitLab, Bitbucket, or any Git provider):**

Before prompting the user for deployment parameters (`project_id`, `region`,
runtime target, Artifact Registry repository, GKE cluster, or service accounts),
consult
[how_to_load_deployment_config.md](references/how_to_load_deployment_config.md):

*   **Existing Project**: Check if `.gcp-deploy/deployment-config.json` (or
    `.gcp-deploy/config-state.json`) and local `gcp-deploy.json` already exist
    in the workspace. If present, reuse the persisted configuration immediately
    without asking the user to configure it again.
*   **Explicit Prompt / Workspace Context Parameters**: If
    `.gcp-deploy/deployment-config.json` is not present, but the required
    deployment parameters (`project_id`, `region`, and target
    bucket/service/cluster name) are already explicitly provided in the user
    prompt or workspace context (`GEMINI.md`), use those parameters directly
    without stopping to ask for a `deployment-config.json` Git repository URL.
*   **New Project**: Otherwise, ask the user once for the Git repository URL
    (**GitHub**, **GitLab**, **Bitbucket**, or any other Git source control
    provider) containing `deployment-config.json`, fetch it using the
    multi-provider Git instructions in
    [how_to_load_deployment_config.md](references/how_to_load_deployment_config.md),
    persist it locally in `.gcp-deploy/deployment-config.json`, and generate a
    workspace `gcp-deploy.json`.
*   **Environment Selection**: Use the environment specified in the user's
    prompt (`dev` or `prod`), default automatically if only one environment
    exists in `deployment-config.json`, or prompt the user to choose if both
    exist and neither is specified.

### **Workflow Selection:** Based on the analysis and `deployment-config.json`, elect the appropriate workflow:

*   If the type is a static application, follow **Workflow A: Google Cloud
    Storage**.
*   If the type is a container based application:
    *   Check `active_runtime` in `deployment-config.json` (if loaded). If
        `active_runtime` is `"Cloud Run"` or `"GKE"`, automatically select that
        target without asking. Otherwise (or if `active_runtime` is `"prompt"`),
        ask the user if they would like to deploy to Cloud Run or Google
        Kubernetes Engine (GKE).
    *   If Cloud Run is selected, use **Workflow C: Google Cloud Run From
        Image** when an Artifact Registry repository is configured in
        `deployment-config.json` / `gcp-deploy.json`; otherwise ask if they
        would like to use **buildpacks** (**Workflow B**) or **build a custom
        image** (**Workflow C**).
    *   If GKE is selected, follow **Workflow D: Google Kubernetes Engine
        (GKE)**.

## Workflow A: Google Cloud Storage

This workflow is for static applications.

Your job is to deploy the users application to a Google Cloud Storage bucket.

1.  **Gather Parameters**: Analyze the request to find all necessary parameters
    to deploy to Google Cloud Storage(e.g., `project_ID: "my-project"`).
2.  **Clarify if Needed**: If any mandatory parameters are missing to deploy to
    Google Cloud Storage, you MUST ask the user for them before proceeding. Do
    not guess or make assumptions.
3.  **Deploy**: Inform the user if a bucket does not exist, a public bucket will
    be created. Deploy the users application to Google Cloud Storage. Consult
    the
    [how_to_deploy_to_gcs_with_gcloud.md](references/how_to_deploy_to_gcs_with_gcloud.md)
    file for detailed `gcloud storage` commands and best practices.
    *   Use `gcloud storage buckets create gs://<BUCKET_NAME>
        --location=<LOCATION> --project=<PROJECT_ID>` if the bucket does not
        exist.
    *   **Confirm Public Access**: Warn the user that binding `allUsers` exposes
        all bucket objects publicly on the internet, and obtain explicit
        confirmation before running `gcloud storage buckets
        add-iam-policy-binding gs://<BUCKET_NAME> --member=allUsers
        --role=roles/storage.objectViewer --project=<PROJECT_ID>`.
    *   Use `gcloud storage cp -r <SOURCE_PATH>/*
        gs://<BUCKET_NAME>/<DESTINATION_DIR> --project=<PROJECT_ID>` on the
        static build output directory (never `<SOURCE_PATH>/**` or the
        repository root) so hidden dotfiles (`.git`, `.env`, `.gcp-deploy`) are
        not uploaded.
    *   Return the URL of the deployed application (e.g.,
        `https://storage.googleapis.com/<BUCKET_NAME>/<MAIN_FILE>`).

## Workflow B: Google Cloud Run With Buildpacks

This workflow is for container-based applications. Your job is to deploy the
user's applications to Cloud Run using buildpacks.

1.  **Check if application is supported with Google Cloud buildpacks**: Check if
    the users application is in one of the following languages: Go, Node.js,
    Python, Java, .NET, Ruby, PHP.
    *   **If application is in one of these languages Node.js, Go, Java, .NET,
        Ruby, PHP, Python it is supported by build packs.** Dockerfile is not
        needed. Skip step 2.
2.  **Create Dockerfile if not supported by buildpacks**: If the users
    application is not supported by buildpacks, as found in step 1, look up how
    to build a Dockerfile. Then create a multistage Dockerfile to containerize
    the application. Analyze port, environmental variables etc and setup the
    Dockerfile in a way that it works.
3.  **Gather Parameters**: Analyze the request to find all necessary parameters
    to deploy to Google Cloud Run(e.g., `repo_name: "my-app-images"`).
4.  **Clarify if Needed**: If any mandatory parameters are missing to deploy to
    Google Cloud Run, you MUST ask the user for them before proceeding. Do not
    guess or make assumptions. Ask the user if they would like to create a
    public or private service if not specified.
5.  **Deploy**: Deploy the user's application from source to Google Cloud Run
    and return the URL of the deployed application:

    *   **Standard Application**: Use `gcloud run deploy <SERVICE_NAME>
        --source=<SOURCE_PATH> --region=<REGION> --project=<PROJECT_ID>
        --port=<PORT> --allow-unauthenticated` (or `--no-allow-unauthenticated`
        if private).
    *   **AI Agent or MCP Server (Native Cloud Run Auto-Registration in Agent
        Registry)**: Use `gcloud beta run deploy` with
        `--functional-type=agent --identity-type=agent-identity` (or
        `--functional-type=mcp-server` for MCP servers) per **Rule 7**, setting
        `<AUTH_FLAG>` to `--allow-unauthenticated` only when `public_access` is
        `true` or confirmed by the user (and `--no-allow-unauthenticated` when
        private or `prod`):

        ```bash
        gcloud beta run deploy <SERVICE_NAME> \
          --source=<SOURCE_PATH> --region=<REGION> --project=<PROJECT_ID> \
          --port=<PORT> --functional-type=agent \
          --identity-type=agent-identity <AUTH_FLAG>
        ```
    *   Retrieve and return the service URL using `gcloud run services describe
        <SERVICE_NAME> --region=<REGION> --project=<PROJECT_ID>
        --format='value(status.url)'`.

## Workflow C: Google Cloud Run From Image

This workflow is for container-based applications. Your job is to deploy the
user's applications to Cloud Run from an image.

1.  **Create Dockerfile**: If a Dockerfile does not already exist, consult the
    [how_to_write_dockerfile.md](references/how_to_write_dockerfile.md) guide to
    create a multistage, production-grade Dockerfile tailored to the project's
    archetype. Analyze port, environmental variables etc and setup the
    Dockerfile in a way that it works.
2.  **Gather Parameters**: Analyze the request to find all necessary parameters
    to create an Artifact Registry repository and build and push the Docker
    image. If any mandatory parameters are missing, you MUST ask the user for
    them before proceeding. Do not guess or make assumptions.
3.  **Create Artifact Registry Repository**: Check if the Artifact Registry
    repository already exists, and create it if it does not using `gcloud`:
    *   Check existence: `gcloud artifacts repositories describe <REPO_NAME>
        --location=<REGION> --project=<PROJECT_ID>`
    *   Create if missing: `gcloud artifacts repositories create <REPO_NAME>
        --repository-format=docker --location=<REGION> --project=<PROJECT_ID>`
    *   If a dedicated service account is specified, grant writer permissions:
        `gcloud projects add-iam-policy-binding <PROJECT_ID>
        --member="serviceAccount:<SERVICE_ACCOUNT_EMAIL>"
        --role="roles/artifactregistry.writer"`
4.  **Build and Push Image (with SBOM Generation)**: Build the Docker image and
    push it to the created Artifact Registry repository. First check if a local
    Docker daemon is running
    (`command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1`):
    *   **If local Docker daemon is running**: Inform the user that configuring
        Artifact Registry authentication updates `~/.docker/config.json` on the
        local host and obtain explicit user confirmation before running
        `gcloud auth configure-docker <REGION>-docker.pkg.dev --quiet`, then use
        the Docker CLI to build the image locally and push it.
    *   **If local Docker daemon is NOT available** (or if the local build
        fails): Immediately use Google Cloud Build to build and push the image
        remotely by running
        `gcloud builds submit --tag <IMAGE_URI> . --project=<PROJECT_ID>` in the
        project root.
    *   **Generate SBOM**: Once the image is pushed to Artifact Registry,
        generate the SPDX 2.3 SBOM using `gcloud artifacts sbom export` per
        **Rule 8**.
5.  **Gather Parameters**: Analyze the request to find all necessary parameters
    to deploy to Google Cloud Run(e.g., `repo_name: "my-app-images"`).
6.  **Clarify if Needed**: If any mandatory parameters are missing to deploy to
    Google Cloud Run, you MUST ask the user for them before proceeding. Do not
    guess or make assumptions. Ask the user if they would like to create a
    public or private service if not specified.
7.  **Deploy**: Deploy the built application to Google Cloud Run and return the
    URL of the deployed application:

    *   **Standard Application**: Use `gcloud run deploy <SERVICE_NAME>
        --image=<IMAGE_URI> --region=<REGION> --project=<PROJECT_ID>
        --port=<PORT> --allow-unauthenticated` (or `--no-allow-unauthenticated`
        if private).
    *   **AI Agent or MCP Server (Native Cloud Run Auto-Registration in Agent
        Registry)**: Use `gcloud beta run deploy` with
        `--functional-type=agent --identity-type=agent-identity` (or
        `--functional-type=mcp-server` for MCP servers) per **Rule 7**, setting
        `<AUTH_FLAG>` to `--allow-unauthenticated` only when `public_access` is
        `true` or confirmed by the user (and `--no-allow-unauthenticated` when
        private or `prod`):

        ```bash
        gcloud beta run deploy <SERVICE_NAME> \
          --image=<IMAGE_URI> --region=<REGION> --project=<PROJECT_ID> \
          --port=<PORT> --functional-type=agent \
          --identity-type=agent-identity <AUTH_FLAG>
        ```
    *   Retrieve and return the service URL using `gcloud run services describe
        <SERVICE_NAME> --region=<REGION> --project=<PROJECT_ID>
        --format='value(status.url)'`.

## Workflow D: Google Kubernetes Engine (GKE)

This workflow is for deploying container-based applications to a GKE cluster.
Consult the
[how_to_deploy_to_gke_with_kubectl.md](references/how_to_deploy_to_gke_with_kubectl.md)
file for detailed `gcloud` and `kubectl` commands and best practices.

1.  **Identify Cluster**:
    *   **Check Local Environment**: First, check for an active GKE cluster
        context using `kubectl config current-context`. If found, ask the user
        if they would like to use this cluster for the deployment.
    *   **Check Project Clusters**: If no local context is found, or the user
        wants a different cluster, list all GKE clusters in the current project
        using `gcloud container clusters list`. If clusters are found, ask the
        user to select one.
    *   **Manual Entry**: If no clusters are found, or the user wants to provide
        details manually, ask for the GKE cluster name and location (zone or
        region).
2.  **Create Dockerfile**: If a Dockerfile does not already exist, consult the
    [how_to_write_dockerfile.md](references/how_to_write_dockerfile.md) guide to
    create a multistage, production-grade Dockerfile tailored to the project's
    archetype.
3.  **Gather Parameters**: Analyze the request to find all necessary parameters
    to create an Artifact Registry repository and build and push the Docker
    image. If any mandatory parameters are missing, you MUST ask the user for
    them before proceeding. Do not guess or make assumptions.
4.  **Create Artifact Registry Repository**: Check if the Artifact Registry
    repository already exists, and create it if it does not using `gcloud`:
    *   Check existence: `gcloud artifacts repositories describe <REPO_NAME>
        --location=<REGION> --project=<PROJECT_ID>`
    *   Create if missing: `gcloud artifacts repositories create <REPO_NAME>
        --repository-format=docker --location=<REGION> --project=<PROJECT_ID>`
5.  **Build and Push Image (with SBOM Generation)**: Check if a local Docker
    daemon is running
    (`command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1`). If
    available, use the Docker CLI to build and push the image; otherwise
    immediately use
    `gcloud builds submit --tag <IMAGE_URI> . --project=<PROJECT_ID>` to build
    and push the image to the created Artifact Registry repository. Once pushed,
    generate the SPDX 2.3 SBOM using `gcloud artifacts sbom export` per **Rule
    8**.
6.  **Manifest Preparation**: Check for existing Kubernetes manifests (e.g.,
    `deployment.yaml`, `service.yaml`) in the project. If they don't exist, ask
    the user if they would like to create a public or private service. Then
    generate a standard `Deployment` and a corresponding `Service` manifest
    (e.g., `LoadBalancer` for public, `ClusterIP` for private). Ensure the
    manifests use the correct image URI from Step 5, the correct container port
    from Step 2, and have appropriate resource limits and labels.
    *   **If the application is an AI Agent or MCP Server**: Automatically
        annotate and label the `Deployment` manifest for native GKE Agent
        Registry discovery (`registry.gke.io/functional-type: "AGENT"` and
        `apphub.cloud.google.com/functional-type: "AGENT"` — or `"MCP_SERVER"` —
        plus `iam.gke.io/spiffe-identity-type: "agent-identity"` on the Pod
        template) per **Rule 7**.
7.  **Deploy to GKE**: Deploy the built application to the GKE cluster by
    following the detailed authentication and deployment procedures in
    [how_to_deploy_to_gke_with_kubectl.md](references/how_to_deploy_to_gke_with_kubectl.md).
8.  **Verification**: Provide the user with commands to check the deployment
    status, as detailed in the reference document
    [how_to_deploy_to_gke_with_kubectl.md](references/how_to_deploy_to_gke_with_kubectl.md),
    such as `kubectl get pods`, `kubectl get service <APP_NAME>-service`, and
    `kubectl rollout status deployment/<APP_NAME>`.

## Universal Protocols & Constraints

These rules apply to all workflows.

Always scan for secrets before any build or deployment operation (including
building Docker images or uploading files to GCS) using local CLI commands (do
NOT rely on a local MCP server):

*   Check for `.env` files, service account key files (`*.json` containing
    `"type": "service_account"`), private keys (`BEGIN .* PRIVATE KEY`), or
    hardcoded API keys/tokens using `grep -rnE` (or `gitleaks` / `trufflehog` /
    `osv-scanner` if installed).
*   Always exclude directories where scanning is not useful, such as third-party
    dependencies or build artifacts the user does not control (e.g., `.git`,
    `.venv`, `node_modules`, `vendor`, `go_modules`, `dist`, `build`).
*   Warn the user of any secrets found and ask if the user wants to ignore these
    files using `.dockerignore` and `.gitignore`. If they would like to ignore
    the files, create or update the corresponding `.dockerignore` and
    `.gitignore` files. The goal of scanning is to detect if the user
    inadvertently included any secrets in *their* application code.

First, analyze the user's application to determine the type of application.
Proceed to the workflow only after analyzing the application.

### **Error Handling Protocol**

1.  **STOP EXECUTION**: If any command returns an error, immediately halt the
    plan.
2.  **REPORT THE ERROR**: Present the exact error message to the user.
3.  **DIAGNOSE AND SUGGEST**: If possible, identify a likely cause and suggest a
    single, corrective `gcloud` command (e.g., `gcloud services enable
    <SERVICE_NAME>.googleapis.com --project=<PROJECT_ID>`).
4.  **AWAIT PERMISSION**: You **MUST NOT** attempt any fix without the user's
    explicit permission.

### **Core Constraints**

*   **Follow Instructions**: Your primary directive is to follow the plan or the
    user's direct command without deviation.
*   **Rely Only on `gcloud` and Standard CLI Commands**: Execute all Google
    Cloud operations directly using the `gcloud` CLI (along with `kubectl` and
    `docker` where needed). Do not rely on a local MCP server.
*   **Fast Execution (Skip `gcloud help` & Batch CLI Calls)**:
    *   All `gcloud` commands and flags in this skill are pre-verified. **Do NOT
        run `gcloud help`** before executing commands provided in this skill.
    *   **Batch sequential checks and provisioning steps** (e.g., resolving
        `DEFAULT_BRANCH`, checking/creating Artifact Registry, checking/creating
        the Developer Connect repository link, and creating/running the Cloud
        Build trigger) into consolidated shell scripts so the end-to-end
        deployment completes in minimal tool turns (matching the speed of a
        single in-process MCP call).

### **Defaults & Administrator Runtime Configuration (`deployment-config.json`)**

Load `deployment-config.json` from the configured source control repository
(**GitHub**, **GitLab**, **Bitbucket**, or any other Git provider; see
[how_to_load_deployment_config.md](references/how_to_load_deployment_config.md)
and [sample-deployment-config.json](references/sample-deployment-config.json)).
If `.gcp-deploy/deployment-config.json` already exists locally, read it directly
without running `git pull`. Once loaded, apply its 4 configuration sections
(`common_gcp_settings`, `cloud_run`, `gke`, and
`developer_connect_and_cloud_build`) and enforce these execution rules (see
[how_to_load_deployment_config.md](references/how_to_load_deployment_config.md)
for full multi-provider Git commands):

1.  **Runtime Determination**: Use `active_runtime` directly when set to
    `"Cloud Run"` or `"GKE"`; otherwise (`"prompt"`), ask the user to choose.
2.  **Auto-Population**: Once runtime and environment (`dev` or `prod`,
    defaulting to `default_environment`) are determined, auto-populate
    `project_id`, `region` / `cluster_location`, `artifact_registry`,
    `service_name` / `cluster_name`, `namespace`, `manifest_path`,
    `public_access`, and `container_port` without prompting. Always require
    explicit user confirmation when `require_confirmation` is `true` (`prod`).
3.  **Deployment Target Naming**: Derive `<app-name>` from `git remote get-url
    origin` or the directory name, applying `<app-name>-dev` / `<app-name>-prod`
    patterns from `deployment-config.json`.
4.  **Artifact Registry Push Enforcement**: When `fail_on_push_error` is `true`
    (default), fail immediately on push errors; never fall back to external
    registries such as Docker Hub.
5.  **Developer Connect & Cloud Build Enforcement**: When `build_mode` is
    `"Developer Connect + Cloud Build"` for the user's own repo, do **NOT**
    build locally with Docker—resolve the remote default branch via Developer
    Connect read token + `git ls-remote --symref`, link via
    `gcloud developer-connect connections git-repository-links create`, and
    create/run the trigger with the dedicated `service_account`:
    *   Always configure `images:` and `options: { logging: CLOUD_LOGGING_ONLY,
        requestedVerifyOption: VERIFIED }` (prevents `INVALID_ARGUMENT` and
        generates SLSA provenance).
    *   Check `git ls-tree "origin/${DEFAULT_BRANCH}" cloudbuild.yaml
        Dockerfile`; if either is missing remotely, pass
        `--inline-config=<INLINE_CLOUDBUILD_YAML>` to avoid
        `FAILED_PRECONDITION: Couldn't read commit`.
    *   Pass `--branch-pattern="^${DEFAULT_BRANCH}$"` on `triggers create`, and
        literal `--branch="${DEFAULT_BRANCH}"` (no `^`/`$`) on `triggers run`.
    *   Export the SPDX SBOM per **Rule 8** before/alongside deploying. For
        3rd-party public sample repos outside Developer Connect permissions,
        clone and build directly.
6.  **Google Cloud CLI Fallback**: If no `deployment-config.json` repo is
    configured, fall back to `gcloud config list` for project/region and confirm
    the target name with the user.
7.  **Automatic Agent Registry Registration for Agentic Workloads (AI Agents &
    MCP Servers)**: **MUST READ**
    [agent_registry_and_binauthz.md](references/agent_registry_and_binauthz.md)
    for full CLI templates and verification commands.
    *   **Cloud Run**: Use `gcloud beta run deploy` with
        `--functional-type=agent --identity-type=agent-identity` (or
        `--functional-type=mcp-server` for MCP servers). Do **NOT** use
        `gcloud agent-registry services create` unless native
        `--functional-type` is unsupported.
    *   **GKE**: Add `registry.gke.io/functional-type`,
        `apphub.cloud.google.com/functional-type` (`"AGENT"` or `"MCP_SERVER"`),
        and `iam.gke.io/spiffe-identity-type: "agent-identity"` to the
        `Deployment` manifest.
    *   **Verify**: Run `gcloud agent-registry agents list` and report the
        resource name, `agentId` URN, and `RuntimeReference.uri`.
8.  **SBOM Generation & Binary Authorization (`BinAuthz`) on Cloud Run `prod`**:
    **MUST READ**
    [agent_registry_and_binauthz.md](references/agent_registry_and_binauthz.md)
    for full SBOM, attestation, and failure-diagnosis commands.
    *   **SBOM**: Resolve the image `@sha256:...` digest via `gcloud artifacts
        docker images describe` and export SPDX 2.3 SBOM via `gcloud artifacts
        sbom export` (deploy `dev` without `--binary-authorization`).
    *   **`prod` Gate**: Pass `--binary-authorization=default`. Evaluate
        `prod-policy` via `gcloud beta container binauthz policy evaluate`; sign
        with `gcloud beta container binauthz attestations sign-and-create` ONLY
        when `verdict: CONFORMANT` (never when `NON_CONFORMANT`).
    *   **Failure Interpretation**: On any `BinAuthz` denial, inspect
        `gcloud beta container binauthz policy evaluate`, `gcloud logging read`
        audit logs, `gcloud container binauthz attestations list`, and
        `gcloud artifacts docker images describe --show-provenance
        --show-package-vulnerability`, then explain the failing check
        (`SlsaCheck` or `VulnerabilityCheck` CVEs).

## Resource Cleanup & Teardown

Deployed Cloud Run services, GKE clusters, Artifact Registry repositories, and
Cloud Storage buckets incur charges (an active billing account is required even
within free tiers; see [Google Cloud Pricing](https://cloud.google.com/pricing)).
Always obtain explicit user confirmation before deleting resources:

*   **Cloud Run**: `gcloud run services delete <SERVICE_NAME> --region=<REGION>
    --project=<PROJECT_ID>`
*   **GKE**: `kubectl delete deployment <APP_NAME> -n <NAMESPACE>` (or
    `gcloud container clusters delete <CLUSTER_NAME> --location=<LOCATION>
    --project=<PROJECT_ID>`)
*   **Artifact Registry**: `gcloud artifacts repositories delete <REPO_NAME>
    --location=<REGION> --project=<PROJECT_ID>`
*   **Cloud Storage**: `gcloud storage rm -r gs://<BUCKET_NAME>
    --project=<PROJECT_ID>`
references/
agent_registry_and_binauthz.md 8.9 KB
# Agent Registry Registration, SBOM Export, and Binary Authorization

## Table of Contents

-   [1. Rule 7: Automatic Agent Registry Registration](#1-rule-7-automatic-agent-registry-registration)
    (Lines 12-77)
-   [2. Rule 8: SBOM Generation and Binary Authorization](#2-rule-8-sbom-generation-and-binary-authorization)
    (Lines 81-187)

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

## 1. Rule 7: Automatic Agent Registry Registration

Whenever the application being deployed is an **AI Agent** (e.g., uses
`google-adk`, `@google/adk`, `genkit`, `langchain`, `langgraph`, `crewai`,
`autogen`, `a2a-sdk`, `agent.py`, `AGENTS.md`, `manifest.yaml`,
`[tool.agent-starter-pack]`, or `agent_card.json`) or an **MCP Server** (e.g.,
uses `mcp`, `@modelcontextprotocol/sdk`, `fastmcp`, or `mcp-spec.json`), you
**MUST** use native runtime auto-registration so that **Google Cloud Agent
Registry** discovers the workload with its actual compute runtime
(`//run.googleapis.com/...` for Cloud Run or `//container.googleapis.com/...`
for GKE) rather than a manual `//agentregistry.googleapis.com/.../services/...`
entry:

*   **Cloud Run Native Auto-Registration (`--functional-type` +
    `--identity-type`)**:
    *   Deploy (or update an existing service that was deployed without
        functional-type) using `gcloud beta run deploy` (or
        `gcloud beta run services update`) with
        `--functional-type=agent --identity-type=agent-identity` (or
        `--functional-type=mcp-server` for MCP Servers), setting `<AUTH_FLAG>`
        to `--allow-unauthenticated` when `public_access` is `true` or
        confirmed by the user and `--no-allow-unauthenticated` when private or
        `prod`:

        ```bash
        gcloud beta run deploy "<SERVICE_NAME>" \
          --image="<IMAGE_URI>" \
          --region="<REGION>" \
          --project="<PROJECT_ID>" \
          --port="<PORT>" \
          --functional-type=agent \
          --identity-type=agent-identity \
          <AUTH_FLAG> \
          --quiet
        ```

        *(This registers the service directly from the Cloud Run control plane
        with `agentId: urn:agent:...:run:services:<SERVICE_NAME>` and
        `RuntimeReference.uri:
        //run.googleapis.com/projects/<PROJECT_NUMBER>/locations/<REGION>/services/<SERVICE_NAME>`.
        Do **NOT** run `gcloud agent-registry services create` for Cloud Run
        workloads unless native `--functional-type` is unsupported, as manual
        `services create` sets the runtime reference to `agentregistry` instead
        of `run.googleapis.com`.)*

*   **GKE Native Auto-Registration**:
    *   In Kubernetes `Deployment` manifests for AI Agents or MCP Servers,
        automatically add:
        *   `metadata.labels["registry.gke.io/functional-type"]: "AGENT"` (or
            `"MCP_SERVER"`)
        *   `metadata.annotations["apphub.cloud.google.com/functional-type"]:
            "AGENT"` (or `"MCP_SERVER"`)
        *   `spec.template.metadata.annotations["iam.gke.io/spiffe-identity-type"]:
            "agent-identity"`

*   **Verification**:
    *   Verify that the agent appears in Agent Registry with its Cloud Run / GKE
        runtime by running:

        ```bash
        gcloud agent-registry agents list --location="<REGION>" --project="<PROJECT_ID>" --filter="agentId:<SERVICE_NAME>" --format="table(name.basename(),displayName,agentId,attributes.\"agentregistry.googleapis.com/system/RuntimeReference\".uri)" --quiet
        ```

    *   Include the registered Agent Registry resource name, `agentId` URN, and
        `RuntimeReference.uri` in the final deployment summary shown to the
        user.

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

## 2. Rule 8: SBOM Generation and Binary Authorization

*   **SBOM Generation (Do Not Block Build/Dev Deploy)**: After building and
    pushing a container image to Artifact Registry via Cloud Build or Docker,
    generate the SPDX 2.3 SBOM (`artifactanalysis-2-3.spdx.json`) using
    `gcloud artifacts sbom export`. Deploy `dev` Cloud Run services **without**
    `--binary-authorization` so `dev` deployments are never blocked:

    ```bash
    DIGEST_URI=$(gcloud artifacts docker images describe "<IMAGE_URI>" \
      --project="<PROJECT_ID>" \
      --format="value(image_summary.fully_qualified_digest)" \
      --quiet)

    # Wait briefly if the automatic push DISCOVERY occurrence is still initializing, then export SBOM
    for i in 1 2 3 4 5; do
      gcloud artifacts sbom export --uri="${DIGEST_URI}" --project="<PROJECT_ID>" --quiet && break
      sleep 3
    done
    ```

*   **Cloud Run `prod` Promotion Gate (Binary Authorization + Provenance &
    Severe Vulnerability Check)**:
    *   When deploying or promoting an image to the **Cloud Run `prod`
        instance** (where `binary_authorization` is `"default"` in
        `deployment-config.json`), always pass `--binary-authorization=default`
        on `gcloud run deploy` / `gcloud beta run deploy`.
    *   Before deploying to `prod`, evaluate the image digest against the Binary
        Authorization policy (`prod-policy`, which checks for **Google Cloud
        Build SLSA provenance** and **no `HIGH` or `CRITICAL`
        vulnerabilities**):

        ```bash
        EVAL_OUTPUT=$(gcloud beta container binauthz policy evaluate "${BINARY_AUTHZ_POLICY:-prod-policy}" \
          --platform=cloudRun \
          --project="<PROJECT_ID>" \
          --image="${DIGEST_URI}" \
          --format=yaml \
          --quiet)
        echo "$EVAL_OUTPUT"
        ```

    *   **If `verdict: CONFORMANT`**: Sign and attach the `prod-attestor`
        attestation so Cloud Run's `--binary-authorization=default` admits the
        `prod` deployment:

        ```bash
        gcloud beta container binauthz attestations sign-and-create \
          --artifact-url="https://${DIGEST_URI}" \
          --attestor="projects/<PROJECT_ID>/attestors/prod-attestor" \
          --keyversion-project="<PROJECT_ID>" \
          --keyversion-location="<REGION>" \
          --keyversion-keyring="binauthz-keyring" \
          --keyversion-key="prod-attestor-key" \
          --keyversion="1" \
          --project="<PROJECT_ID>" \
          --quiet
        ```

    *   **If `verdict: NON_CONFORMANT`**: Do **NOT** sign the `prod-attestor`
        attestation, so that deploying with `--binary-authorization=default` is
        blocked by Binary Authorization.

*   **Interpreting Binary Authorization (`BinAuthz`) Failures on
    Promotion/Deployment to Production**:
    *   Whenever a `prod` deployment or promotion fails due to Binary
        Authorization (`verdict: NON_CONFORMANT`, Cloud Run
        `BinaryAuthorizationCheckFailed` / revision not ready, or Cloud Deploy
        rollout failure), you **MUST** automatically inspect and interpret the
        Binary Authorization results to explain the exact cause of the block:
        1.  **Inspect Policy Evaluation & BinAuthz Audit Logs**:

            ```bash
            # Evaluate the provenance & vulnerability checkset against the image digest
            gcloud beta container binauthz policy evaluate "${BINARY_AUTHZ_POLICY:-prod-policy}" \
              --platform="${PLATFORM:-cloudRun}" --project="<PROJECT_ID>" --image="${DIGEST_URI}" --format=yaml --quiet

            # Check Cloud Audit Logs for the BinAuthz admission denial message
            gcloud logging read 'logName:"cloudaudit.googleapis.com%2Fpolicy" OR protoPayload.serviceName="binaryauthorization.googleapis.com" OR protoPayload.status.message:"Binary Authorization"' \
              --project="<PROJECT_ID>" --limit=10 --format=json --quiet
            ```

        2.  **Cross-Check Attestations, Provenance, and Vulnerability Findings
            on the Image Digest**:

            ```bash
            # Check existing BinAuthz attestations on the image digest
            gcloud container binauthz attestations list --artifact-url="https://${DIGEST_URI}" --project="<PROJECT_ID>" --quiet

            # Check SLSA build provenance and package vulnerability scan results
            gcloud artifacts docker images describe "${DIGEST_URI}" \
              --show-provenance --show-package-vulnerability \
              --project="<PROJECT_ID>" --quiet
            ```

        3.  **Explain the Root Cause Clearly to the User**:
            *   Identify **which check failed**:
                *   `SlsaCheck` (`Require Google Cloud Build SLSA Provenance`):
                    Explain whether the image is missing verified Cloud Build
                    provenance (`provenance_summary: null` or built outside
                    Cloud Build).
                *   `VulnerabilityCheck` (`Block HIGH and CRITICAL
                    Vulnerabilities`): State how many vulnerabilities violated
                    the `MEDIUM` threshold (`HIGH` / `CRITICAL` CVEs) and list
                    the offending CVEs (`package`, `installedVersion`,
                    `fixedVersion`, `severity`, `cvssScore`) along with
                    remediation steps.
attribution.md 1.8 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-cicd-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:google-cicd-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:google-cicd-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.
how_to_deploy_to_gcs_with_gcloud.md 2.8 KB
# How to Deploy to Google Cloud Storage with `gcloud`

This document outlines the standard procedure for deploying static applications
(e.g., websites and single-page applications) to a Google Cloud Storage (GCS)
bucket using the `gcloud storage` command-line tool.

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

## Step 1: Gather Deployment Parameters

Before executing any commands, the following parameters must be identified:

*   **`PROJECT_ID`**: The Google Cloud project where the bucket will be hosted.
*   **`BUCKET_NAME`**: The name of the GCS bucket (e.g.,
    `gs://my-static-site-bucket`).
*   **`LOCATION`**: The geographic location for the bucket (e.g.,
    `us-central1`).
*   **`SOURCE_PATH`**: The local directory containing the build artifacts (e.g.,
    `./dist`, `./build`).
*   **`DESTINATION_DIR`**: (Optional) The directory within the bucket to upload
    to.
*   **`MAIN_FILE`**: The entry point of the application (e.g., `index.html`).
    This is **identified automatically** by inspecting the build artifacts.

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

## Step 2: Prepare the Storage Bucket

### 1. Create the Bucket (if it doesn't exist)

```bash
gcloud storage buckets create gs://<BUCKET_NAME> \
    --project=<PROJECT_ID> \
    --location=<LOCATION>
```

### 2. Enable Public Access (Requires User Confirmation)

Warn the user that granting `roles/storage.objectViewer` to `allUsers` exposes
all files in the bucket publicly on the internet, and obtain explicit
confirmation before running:

```bash
gcloud storage buckets add-iam-policy-binding gs://<BUCKET_NAME> \
    --member=allUsers \
    --role=roles/storage.objectViewer \
    --project=<PROJECT_ID>
```

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

## Step 3: Deploy Build Artifacts

Use `gcloud storage cp -r` to upload the static build output directory (e.g.,
`./dist/` or `./build/`, never the repository root) to the bucket.

### Best Practice: Avoid Uploading Dotfiles and Repository Metadata

Unlike Cloud Build or `gcloud run deploy`, `gcloud storage cp` does **not**
respect `.gitignore` or `.gcloudignore` (and does not accept an `--exclude`
flag). Never use `<SOURCE_PATH>/**` or run against the repository root—upload
`<SOURCE_PATH>/*` from the clean build output directory (`./dist`, `./build`) so
POSIX globbing omits leading-dot files (`.git`, `.env`, `.gcp-deploy`):

```bash
gcloud storage cp -r <SOURCE_PATH>/* gs://<BUCKET_NAME>/<DESTINATION_DIR> \
    --project=<PROJECT_ID>
```

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

## Step 4: Verification

After the upload is complete, the application can be accessed via the standard
GCS public URL:

`https://storage.googleapis.com/<BUCKET_NAME>/<MAIN_FILE>`
how_to_deploy_to_gke_with_kubectl.md 7.8 KB
# How to Deploy to Google Kubernetes Engine (GKE) with `kubectl`

This document outlines the standard procedure for deploying containerized
applications, AI Agents, and MCP Servers to a Google Kubernetes Engine (GKE)
cluster using standard CLI tools (`gcloud`, `kubectl`).

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

## Table of Contents

-   [Step 1: Gather Deployment Parameters](#step-1-gather-deployment-parameters)
    (Lines 23-40)
-   [Step 2: Authenticate with the GKE Cluster & Ensure Namespace Exists](#step-2-authenticate-with-the-gke-cluster-ensure-namespace-exists)
    (Lines 44-59)
-   [Step 3: Prepare Kubernetes Manifests](#step-3-prepare-kubernetes-manifests)
    (Lines 63-167)
-   [Step 4: Deploy Build Artifacts](#step-4-deploy-build-artifacts) (Lines
    171-177)
-   [Step 5: Verification](#step-5-verification) (Lines 181-198)
-   [Step 6: Troubleshooting GKE Authentication & Permission Errors](#step-6-troubleshooting-gke-authentication-permission-errors)
    (Lines 202-241)

## Step 1: Gather Deployment Parameters

Before executing any commands, identify the following parameters (from
`.gcp-deploy/deployment-config.json` `gke.<env>` if available, or from the user
prompt/workspace context):

*   **`PROJECT_ID`**: The Google Cloud project where the GKE cluster and
    Artifact Registry are hosted.
*   **`CLUSTER_NAME`**: The name of the GKE cluster (e.g., `my-gke-cluster-dev`
    or `my-gke-cluster-prod`).
*   **`LOCATION`**: The geographic location (zone or region) of the cluster
    (e.g., `us-central1` or `us-central1-a`).
*   **`NAMESPACE`**: The target Kubernetes namespace (e.g., `dev`, `prod`, or
    `default`).
*   **`IMAGE_URI`**: The full URI of the container image in Artifact Registry
    (e.g., `us-central1-docker.pkg.dev/my-project/my-repo/my-image:latest`).
*   **`MANIFEST_PATH`**: The path to the Kubernetes manifest files (e.g.,
    `./kubernetes-manifests/` or `./k8s/`).

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

## Step 2: Authenticate with the GKE Cluster & Ensure Namespace Exists

Use the `gcloud` CLI to retrieve credentials for the cluster
(`USE_GKE_GCLOUD_AUTH_PLUGIN=True`) and ensure the target namespace exists
before applying manifests:

```bash
export USE_GKE_GCLOUD_AUTH_PLUGIN=True

CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:google-cicd-deploy)" \
gcloud container clusters get-credentials "<CLUSTER_NAME>" \
    --location="<LOCATION>" \
    --project="<PROJECT_ID>"

kubectl create namespace "<NAMESPACE>" --dry-run=client -o yaml | kubectl apply -f -
```

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

## Step 3: Prepare Kubernetes Manifests

Ensure that the Kubernetes manifests (typically `deployment.yaml` and
`service.yaml`) are correctly configured.

### 1. Update the Image URI

The `image:` field in the `Deployment` manifest MUST be updated to point to the
`IMAGE_URI` pushed to Artifact Registry during the build step.

### 2. Standard Manifest Example (if none exist)

If the project does not already have manifests, generate a basic set under
`<MANIFEST_PATH>`:

**`deployment.yaml`**:

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: <APP_NAME>
  namespace: <NAMESPACE>
  labels:
    app: <APP_NAME>
spec:
  replicas: 1
  selector:
    matchLabels:
      app: <APP_NAME>
  template:
    metadata:
      labels:
        app: <APP_NAME>
    spec:
      containers:
      - name: <APP_NAME>
        image: <IMAGE_URI>
        ports:
        - containerPort: <CONTAINER_PORT>
        resources:
          requests:
            memory: "256Mi"
            cpu: "250m"
          limits:
            memory: "512Mi"
            cpu: "500m"
```

**`service.yaml`**:

```yaml
apiVersion: v1
kind: Service
metadata:
  name: <APP_NAME>-service
  namespace: <NAMESPACE>
spec:
  selector:
    app: <APP_NAME>
  ports:
    - protocol: TCP
      port: 80
      targetPort: <CONTAINER_PORT>
  type: LoadBalancer
```

### 3. Agentic Workload Labels & Annotations (AI Agents & MCP Servers)

If the workload being deployed to GKE is an **AI Agent** (`google-adk`,
`langchain`, `langgraph`, `crewai`, `autogen`) or **MCP Server** (`mcp`,
`fastmcp`, `@modelcontextprotocol/sdk`), enable `agentregistry.googleapis.com`
and automatically add the Google Cloud Agent Registry discovery labels and
SPIFFE identity annotations to the `Deployment` manifest (`"AGENT"` for AI
agents or `"MCP_SERVER"` for MCP servers):

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: <APP_NAME>
  namespace: <NAMESPACE>
  labels:
    app: <APP_NAME>
    registry.gke.io/functional-type: "AGENT" # Or "MCP_SERVER"
  annotations:
    apphub.cloud.google.com/functional-type: "AGENT" # Or "MCP_SERVER"
spec:
  replicas: 1
  selector:
    matchLabels:
      app: <APP_NAME>
  template:
    metadata:
      labels:
        app: <APP_NAME>
      annotations:
        iam.gke.io/spiffe-identity-type: "agent-identity"
    spec:
      containers:
      - name: <APP_NAME>
        image: <IMAGE_URI>
        ports:
        - containerPort: <CONTAINER_PORT>
```

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

## Step 4: Deploy Build Artifacts

Apply the manifests to the target namespace in the GKE cluster:

```bash
kubectl apply -f "<MANIFEST_PATH>" -n "<NAMESPACE>"
```

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

## Step 5: Verification

After the deployment is applied, verify the rollout status, external IP, and (if
applicable) Agent Registry discovery:

1.  **Check Rollout Status**:
    `kubectl rollout status deployment/<APP_NAME> -n <NAMESPACE> --timeout=180s`
2.  **Check Pod Status**: `kubectl get pods -n <NAMESPACE>`
3.  **Check Service IP**:
    `kubectl get service <APP_NAME>-service -n <NAMESPACE>`
4.  **Verify Agent Registry Discovery (for AI Agents / MCP Servers)**:

    ```bash
    # For AI Agents:
    gcloud agent-registry agents list --location="<LOCATION>" --project="<PROJECT_ID>"
    # For MCP Servers:
    gcloud agent-registry mcp-servers list --location="<LOCATION>" --project="<PROJECT_ID>"
    ```

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

## Step 6: Troubleshooting GKE Authentication & Permission Errors

If cluster credential retrieval or manifest deployment fails, diagnose and
report the exact root cause without switching to another runtime or fabricating
cluster endpoints:

*   **`PERMISSION_DENIED` on `gcloud container clusters get-credentials`
    (`container.clusters.get` denied)**:

    *   The active identity lacks the `roles/container.clusterViewer` or
        `roles/container.developer` IAM role on `<PROJECT_ID>`.
    *   **Remediation**:

        ```bash
        gcloud projects add-iam-policy-binding <PROJECT_ID> \
          --member="user:<USER_OR_SA_EMAIL>" \
          --role="roles/container.developer"
        ```
*   **Kubernetes RBAC `Error from server (Forbidden): deployments.apps is
    forbidden: User "..." cannot create resource "deployments" in API group
    "apps" in the namespace "<NAMESPACE>"`**:

    *   The principal can authenticate to the cluster endpoint, but lacks
        Kubernetes RBAC or GKE IAM permissions to create workloads in
        `<NAMESPACE>`.
    *   **Remediation**: Grant `roles/container.developer` at the GCP project
        level or bind a Kubernetes `RoleBinding` / `ClusterRoleBinding` (`edit`
        or `admin`) in `<NAMESPACE>`:

        ```bash
        kubectl create rolebinding <APP_NAME>-deployer-binding \
          --clusterrole=edit \
          --user="<USER_OR_SA_EMAIL>" \
          --namespace="<NAMESPACE>"
        ```
*   **`executable gke-gcloud-auth-plugin not found`**:

    *   Install `google-cloud-cli-gke-gcloud-auth-plugin` (or
        `gcloud components install gke-gcloud-auth-plugin`) and ensure
        `USE_GKE_GCLOUD_AUTH_PLUGIN=True` is exported.
how_to_load_deployment_config.md 23.9 KB
# Loading & Generating Organization Deployment Configuration (`deployment-config.json`)

This guide defines the standard procedure for retrieving, caching, generating,
and applying organization-wide deployment defaults (`deployment-config.json`)
from a central Git configuration repository hosted on **any source control
provider** (including **GitHub**, **GitLab**, **Bitbucket**, self-managed Git
servers, or other Git hosts) or directly from the active Google Cloud
environment, aligned with the Administrator Runtime Configuration schema.

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

## Table of Contents

-   [1. Onboarding & Persistence Lifecycle](#1-onboarding-persistence-lifecycle)
    (Lines 24-59)
-   [2. Pulling `deployment-config.json` Across Source Control Providers](#2-pulling-deployment-configjson-across-source-control-providers)
    (Lines 63-169)
-   [3. Generating `deployment-config.json` from Enabled GCP Services or User-Specified Services](#3-generating-deployment-configjson-from-enabled-gcp-services-or-user-specified-services)
    (Lines 173-235)
-   [4. `deployment-config.json` Schema (Aligned with Local Skill Config Prototype)](#4-deployment-configjson-schema-aligned-with-local-skill-config-prototype)
    (Lines 239-319)
-   [5. Agent Execution Rules](#5-agent-execution-rules) (Lines 323-470)

## 1. Onboarding & Persistence Lifecycle

Before asking the developer for Google Cloud parameters (`project_id`, `region`,
runtime target, Artifact Registry repository, GKE cluster, or Developer Connect
/ Cloud Build settings), always resolve configuration in the following order:

1.  **Check Persisted Workspace Configuration First**:
    *   Inspect the workspace for an existing
        `.gcp-deploy/deployment-config.json` (and optional
        `./deployment-config.json`, `.gcp-deploy/config-state.json`, or local
        `gcp-deploy.json`).
    *   **Existing Project**: If `.gcp-deploy/deployment-config.json` is already
        present in the workspace, **read and use it immediately without asking
        the developer to re-configure it and without running `git pull`**
        (avoiding unnecessary network or credential prompt delays).
2.  **Explicit Prompt / Workspace Context Parameters**:
    *   If `.gcp-deploy/deployment-config.json` does not exist locally, but the
        required deployment parameters (`project_id`, `region`, and target
        resource name) are already explicitly provided in the user prompt or
        workspace context (`GEMINI.md`, `CLAUDE.md`, or `AGENTS.md`), use those
        parameters directly without stopping to ask for a
        `deployment-config.json` Git repository URL.
3.  **New Project Onboarding**:
    *   Otherwise, if no configuration state exists in the workspace, ask the
        developer **once**:

        > *"Please provide the Git repository URL (GitHub, GitLab, Bitbucket,
        > or your source control provider) containing your organization's
        > `deployment-config.json` (or let me know if you want to generate one
        > from your GCP project or configure parameters manually)."*
    *   Once fetched or generated, save the file to
        `.gcp-deploy/deployment-config.json` (and `./deployment-config.json`
        when generating a new config), record the repository URL in
        `.gcp-deploy/config-state.json`, and ensure `.gcp-deploy/` is ignored in
        `.gitignore` and `.dockerignore` so future prompts in the project
        automatically reuse it.

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

## 2. Pulling `deployment-config.json` Across Source Control Providers

Detect the Git provider from the repository URL (HTTPS or SSH) and retrieve
`deployment-config.json` using the methods below.

### Method A: Universal Git Sparse Checkout (Works Across All Source Control Providers — GitHub, GitLab, Bitbucket, and Any Git Host)

This universal method works with **any Git source control provider** (public or
private). Always pass `GIT_TERMINAL_PROMPT=0` so `git` never blocks on an
interactive prompt if local credentials are not configured:

```bash
mkdir -p .gcp-deploy
rm -rf .gcp-deploy/config-repo
GIT_TERMINAL_PROMPT=0 git clone --depth 1 --filter=blob:none --sparse "<GIT_REPO_URL>" .gcp-deploy/config-repo
git -C .gcp-deploy/config-repo sparse-checkout set deployment-config.json
cp .gcp-deploy/config-repo/deployment-config.json .gcp-deploy/deployment-config.json
```

*(If a specific branch or tag `<REF>` is specified, pass `--branch <REF>` to
`git clone`.)*

### Method B: Private Repo Retrieval via Google Cloud Developer Connect Token (GitHub, GitLab, Bitbucket)

If the configuration repository is private and local Git credentials are not
configured in the terminal (`GIT_TERMINAL_PROMPT=0 git clone` fails with an
authentication error), fetch a short-lived read token from Google Cloud
Developer Connect (creating the repository link first if needed) and clone with
`sparse-checkout`:

```bash
PROJECT_ID=$(gcloud config get-value project 2>/dev/null)
REGION=${REGION:-us-central1}
# Find existing connection and repo link (or create the repo link if missing)
CONNECTION_ID=$(gcloud developer-connect connections list --location="$REGION" --project="$PROJECT_ID" --format="value(name.basename())" --limit=1 --quiet)
REPO_LINK_ID=$(gcloud developer-connect connections git-repository-links list --connection="$CONNECTION_ID" --location="$REGION" --project="$PROJECT_ID" --filter="cloneUri:<GIT_REPO_URL>" --format="value(name.basename())" --limit=1 --quiet)
TOKEN=$(gcloud developer-connect connections git-repository-links fetch-read-token "$REPO_LINK_ID" --connection="$CONNECTION_ID" --location="$REGION" --project="$PROJECT_ID" --format="value(token)" --quiet)

# Pass token via in-memory Git HTTP header (x-access-token for GitHub, oauth2 for GitLab, x-token-auth for Bitbucket)
# so the secret is never written to .git/config on disk or exposed on the process command line
if echo "<GIT_REPO_URL>" | grep -qi "gitlab"; then
  GIT_USER="oauth2"
elif echo "<GIT_REPO_URL>" | grep -qi "bitbucket"; then
  GIT_USER="x-token-auth"
else
  GIT_USER="x-access-token"
fi
AUTH_HEADER="Authorization: Basic $(printf '%s:%s' "$GIT_USER" "$TOKEN" | base64 | tr -d '\n')"
rm -rf .gcp-deploy/config-repo
GIT_TERMINAL_PROMPT=0 GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0="$AUTH_HEADER" \
  git clone --depth 1 --filter=blob:none --sparse "<GIT_REPO_URL>" .gcp-deploy/config-repo
git -C .gcp-deploy/config-repo sparse-checkout set deployment-config.json
cp .gcp-deploy/config-repo/deployment-config.json .gcp-deploy/deployment-config.json
rm -rf .gcp-deploy/config-repo
```

### Method C: Provider-Specific CLI & Raw HTTP Fallbacks

If direct single-file retrieval is preferred over `git clone`:

#### 1. GitHub (`github.com` or GitHub Enterprise)

*   **Via GitHub CLI (`gh`)** *(handles private repos automatically)*:

    ```bash
    gh api "repos/<OWNER>/<REPO>/contents/deployment-config.json?ref=<BRANCH>" \
      -H "Accept: application/vnd.github.raw" > .gcp-deploy/deployment-config.json
    ```
*   **Via Raw HTTPS**:

    ```bash
    curl -sSfL ${GITHUB_TOKEN:+-H "Authorization: Bearer $GITHUB_TOKEN"} \
      "https://raw.githubusercontent.com/<OWNER>/<REPO>/<BRANCH>/deployment-config.json" \
      -o .gcp-deploy/deployment-config.json
    ```

#### 2. GitLab (`gitlab.com` or Self-Managed GitLab)

*   **Via GitLab CLI (`glab`)** *(handles private repos automatically; replace
    `/` in `<GROUP>/<PROJECT>` with `%2F`)*:

    ```bash
    glab api "projects/<URL_ENCODED_PROJECT_PATH>/repository/files/deployment-config.json/raw?ref=<BRANCH>" \
      > .gcp-deploy/deployment-config.json
    ```
*   **Via GitLab REST API / Raw HTTPS**:

    ```bash
    curl -sSfL ${GITLAB_TOKEN:+-H "PRIVATE-TOKEN: $GITLAB_TOKEN"} \
      "https://<GITLAB_HOST>/<GROUP>/<PROJECT>/-/raw/<BRANCH>/deployment-config.json" \
      -o .gcp-deploy/deployment-config.json
    ```

#### 3. Bitbucket (`bitbucket.org` or Bitbucket Data Center)

*   **Via Bitbucket Cloud API / Raw HTTPS**:

    ```bash
    curl -sSfL ${BITBUCKET_TOKEN:+-H "Authorization: Bearer $BITBUCKET_TOKEN"} \
      "https://api.bitbucket.org/2.0/repositories/<WORKSPACE>/<REPO_SLUG>/src/<BRANCH>/deployment-config.json" \
      -o .gcp-deploy/deployment-config.json
    ```

    *(Or with Bitbucket App Password: `curl -sSfL -u
    "$BITBUCKET_USERNAME:$BITBUCKET_APP_PASSWORD"
    "https://bitbucket.org/<WORKSPACE>/<REPO_SLUG>/raw/<BRANCH>/deployment-config.json"
    -o .gcp-deploy/deployment-config.json`)*

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

## 3. Generating `deployment-config.json` from Enabled GCP Services or User-Specified Services

When the user asks to **generate a deployment configuration file** based on:

*   The services enabled in their GCP environment (e.g., *"Generate a deployment
    configuration file based on the services enabled in my GCP environment"*),
    OR
*   A specific subset of services (e.g., *"Generate a deployment configuration
    file that utilizes Cloud Run, Artifact Registry, Developer Connect, and
    Cloud Build"*):

### Step 1: Discover Active GCP Services and Existing CI/CD Resources

Run a single batched shell snippet to inspect enabled APIs and discover existing
Artifact Registry repositories, Developer Connect connections, Cloud Run
services, and GKE clusters:

```bash
export CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:google-cicd-deploy)"
PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project 2>/dev/null)}"
REGION="${REGION:-us-central1}"

# 1. List enabled CI/CD & runtime APIs
ENABLED_APIS=$(gcloud services list --enabled --project="$PROJECT_ID" \
  --filter="config.name:(run.googleapis.com OR container.googleapis.com OR artifactregistry.googleapis.com OR cloudbuild.googleapis.com OR developerconnect.googleapis.com OR binaryauthorization.googleapis.com)" \
  --format="value(config.name)" --quiet 2>/dev/null || true)

# 2. Discover existing Artifact Registry Docker repositories
AR_REPO=$(gcloud artifacts repositories list --project="$PROJECT_ID" --location="$REGION" \
  --filter="format:DOCKER" --format="value(name.basename())" --limit=1 --quiet 2>/dev/null || true)

# 3. Discover existing Developer Connect connection
DEVCONNECT_ID=$(gcloud developer-connect connections list --project="$PROJECT_ID" --location="$REGION" \
  --format="value(name.basename())" --limit=1 --quiet 2>/dev/null || true)

# 4. Discover existing GKE cluster (if container.googleapis.com is enabled)
GKE_CLUSTER=$(gcloud container clusters list --project="$PROJECT_ID" --region="$REGION" \
  --format="value(name)" --limit=1 --quiet 2>/dev/null || true)
```

### Step 2: Populate and Persist `deployment-config.json`

1.  **Include Only Requested / Enabled Runtime & CI/CD Sections**:
    *   Always include `active_runtime`, `default_environment`,
        `fail_on_push_error`, and `common_gcp_settings` (`project_id`,
        `region`).
    *   Include `cloud_run` (`dev` and `prod`) when `run.googleapis.com` is
        enabled or Cloud Run is requested. Set `active_runtime` to `"Cloud Run"`
        if Cloud Run is the primary runtime.
    *   Include `gke` (`dev` and `prod`) when `container.googleapis.com` is
        enabled or GKE is requested (if the user explicitly requests *only*
        Cloud Run, Artifact Registry, Developer Connect, and Cloud Build, you
        may either omit `gke` or leave `active_runtime: "Cloud Run"`).
    *   Include `developer_connect_and_cloud_build` when
        `cloudbuild.googleapis.com` or `developerconnect.googleapis.com` is
        enabled or requested, populating `connection_id` with the discovered
        `$DEVCONNECT_ID` (or `"my-devconnect-connection"` default) and
        `service_account` with
        `projects/${PROJECT_ID}/serviceAccounts/cloudbuild-runner@${PROJECT_ID}.iam.gserviceaccount.com`.
2.  **Save to Both Workspace Locations**:
    *   Write the generated JSON to both `./deployment-config.json` and
        `./.gcp-deploy/deployment-config.json` so subsequent deployment commands
        in the same session or repository immediately pick it up.

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

## 4. `deployment-config.json` Schema (Aligned with Local Skill Config Prototype)

The `.gcp-deploy/deployment-config.json` file (as well as any root-level
`./deployment-config.json` or local `gcp-deploy.json` workspace alias, which use
this identical JSON schema) maps 1-to-1 to the 4 configuration sections in the
CI/CD integration prototype:

1.  **Runtime Selection & Common Settings** (`active_runtime`,
    `default_environment`, `fail_on_push_error`, `common_gcp_settings`)
2.  **Runtime: Google Cloud Run Configuration** (`cloud_run.dev`,
    `cloud_run.prod`)
3.  **Runtime: Google Kubernetes Engine (GKE) Configuration** (`gke.dev`,
    `gke.prod`)
4.  **Developer Connect & Cloud Build Configuration** (`build_mode`,
    `developer_connect`, `cloud_build_trigger`)

```json
{
  "active_runtime": "Cloud Run",
  "default_environment": "dev",
  "fail_on_push_error": true,
  "common_gcp_settings": {
    "project_id": "my-gcp-project",
    "region": "us-central1"
  },
  "cloud_run": {
    "dev": {
      "project_id": "my-gcp-project",
      "region": "us-central1",
      "artifact_registry": "us-central1-docker.pkg.dev/my-gcp-project/my-app-images-dev",
      "service_name": "<app-name>-dev",
      "public_access": true,
      "container_port": 8080
    },
    "prod": {
      "project_id": "my-gcp-project",
      "region": "us-central1",
      "artifact_registry": "us-central1-docker.pkg.dev/my-gcp-project/my-app-images-prod",
      "service_name": "<app-name>-prod",
      "public_access": false,
      "container_port": 8080,
      "require_confirmation": true,
      "binary_authorization": "default",
      "binary_authorization_policy": "prod-policy"
    }
  },
  "gke": {
    "dev": {
      "project_id": "my-gcp-project",
      "cluster_location": "us-central1",
      "cluster_name": "my-gke-cluster-dev",
      "namespace": "dev",
      "artifact_registry": "us-central1-docker.pkg.dev/my-gcp-project/my-app-images-dev",
      "manifest_path": "./kubernetes-manifests/"
    },
    "prod": {
      "project_id": "my-gcp-project",
      "cluster_location": "us-central1",
      "cluster_name": "my-gke-cluster-prod",
      "namespace": "prod",
      "artifact_registry": "us-central1-docker.pkg.dev/my-gcp-project/my-app-images-prod",
      "manifest_path": "./release/kubernetes-manifests.yaml",
      "require_confirmation": true
    }
  },
  "developer_connect_and_cloud_build": {
    "build_mode": "Developer Connect + Cloud Build",
    "developer_connect": {
      "location": "us-central1",
      "connection_id": "my-devconnect-connection"
    },
    "cloud_build_trigger": {
      "project_id": "my-gcp-project",
      "region": "us-central1",
      "service_account": "projects/my-gcp-project/serviceAccounts/cloudbuild-runner@my-gcp-project.iam.gserviceaccount.com",
      "default_branch": "^main$",
      "auto_run_trigger": true
    }
  }
}
```

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

## 5. Agent Execution Rules

When `deployment-config.json` is loaded or generated, enforce the following 8
execution rules:

1.  **Runtime Determination**:
    *   If `active_runtime` is set to `"Cloud Run"` or `"GKE"` (and not
        overridden by the user prompt), use that target directly without asking.
    *   If set to `"prompt"`, ask the user: *"Would you like to deploy to Cloud
        Run or GKE?"*
2.  **Environment Determination & Auto-Population**:
    *   Use the environment specified in the user's prompt (`dev` or `prod`). If
        unspecified, use `default_environment` (or if only one environment
        exists in `deployment-config.json`, default to that environment;
        otherwise prompt the user).
    *   Once the runtime (`cloud_run` or `gke`) and environment (`dev` or
        `prod`) are determined, **automatically populate all parameters from
        that section without asking the user** for project ID, region, Artifact
        Registry URI, service/cluster name, namespace, manifest path, or
        container port.
    *   When `require_confirmation` is `true` (always enforced for `prod`),
        always require explicit user confirmation before deploying to `prod`
        unless the user prompt already explicitly confirms `prod` deployment.
3.  **Deployment Target Naming**:
    *   Derive `<app-name>` from the Git repository name
        (`git remote get-url origin`) or current directory name, and apply the
        configured environment pattern (e.g., `<app-name>-dev` or
        `<app-name>-prod`).
4.  **Artifact Registry Push Enforcement**:
    *   When `fail_on_push_error` is `true` (default), pushing the image to the
        configured `artifact_registry` URI is mandatory. If the push fails for
        any reason (authentication, permissions, network, or Cloud Build
        errors), **immediately fail the deployment and report the error to the
        user**. Never bypass Artifact Registry by falling back to external or
        public registries (such as Docker Hub).
5.  **Developer Connect & Cloud Build Enforcement**:

    *   Whenever `build_mode` is `"Developer Connect + Cloud Build"` (or
        `"developer-connect"`) and deploying from the user's own source control
        repository (**GitHub**, **GitLab**, **Bitbucket**, or any supported Git
        provider), **do NOT build locally using Docker CLI** and **do NOT check
        or worry about unpublished local branches**—always use the **default
        branch in the remote source control repository**.
    *   Determine the remote repository's default branch universally across any
        Git provider (even for private repos with no local clone) via Developer
        Connect's read token + `git ls-remote --symref`:

        ```bash
        TOKEN=$(gcloud developer-connect connections git-repository-links fetch-read-token <REPO_LINK_ID> \
          --connection=<CONNECTION_ID> --location=<REGION> --project=<PROJECT_ID> --format="value(token)" --quiet 2>/dev/null || true)
        if [ -n "$TOKEN" ]; then
          AUTH_HEADER="Authorization: Basic $(printf 'x-access-token:%s' "$TOKEN" | base64 | tr -d '\n')"
          DEFAULT_BRANCH=$(GIT_TERMINAL_PROMPT=0 GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0="$AUTH_HEADER" \
            git ls-remote --symref "<GIT_REPO_URI>" HEAD 2>/dev/null | awk '/^ref:/ {sub("refs/heads/", "", $2); print $2}')
        else
          DEFAULT_BRANCH=$(GIT_TERMINAL_PROMPT=0 git ls-remote --symref "<GIT_REPO_URI>" HEAD 2>/dev/null | awk '/^ref:/ {sub("refs/heads/", "", $2); print $2}')
        fi
        ```

        *(Only fall back to `default_branch` in `deployment-config.json` with
        `^` and `$` stripped if the remote `HEAD` ref cannot be resolved.)*
    *   Automatically link the repository to Developer Connect using
        `gcloud developer-connect connections git-repository-links create` under
        the configured `developer_connect.connection_id`.
    *   Create or run the Cloud Build trigger using
        `gcloud builds triggers create developer-connect` (or
        `gcloud beta builds triggers create developer-connect`) and
        `gcloud builds triggers run` with the pre-configured dedicated
        `cloud_build_trigger.service_account`:

        *   **Mandatory `CLOUD_LOGGING_ONLY`**: Always include
            `options: { logging: CLOUD_LOGGING_ONLY }` in the Cloud Build
            configuration when using a dedicated `--service-account`.
        *   **Check Remote Branch for `cloudbuild.yaml` & `Dockerfile`**:
            Inspect
            `git ls-tree "origin/${DEFAULT_BRANCH}" cloudbuild.yaml Dockerfile`.
            If `cloudbuild.yaml` or `Dockerfile` is not committed on
            `origin/${DEFAULT_BRANCH}`, use
            `--inline-config=<INLINE_CLOUDBUILD_YAML>` (with
            `options: { logging: CLOUD_LOGGING_ONLY }` and inline `Dockerfile`
            creation if needed) so the trigger succeeds on the first run.
        *   **Use Remote Default Branch & Strip Regex Anchors for
            `triggers run`**: When creating a trigger, pass
            `--branch-pattern="^${DEFAULT_BRANCH}$"`. When calling `gcloud
            builds triggers run <TRIGGER_ID> --branch="${DEFAULT_BRANCH}"`,
            always pass the literal default branch name without `^` or `$` regex
            anchors.
        *   **Batch CLI Execution**: Combine Artifact Registry check/create,
            Developer Connect repo link check/create, and Cloud Build trigger
            check/create/run into a single shell script without calling
            `gcloud help` first.
    *   Use the resulting Artifact Registry image for subsequent Cloud Run or
        GKE deployments.
    *   For 3rd-party public sample repositories (which are outside the user's
        Developer Connect permissions), clone and build directly.
6.  **Secret Leak Interception & Secret Manager Enforcement**:

    *   Before building or packaging any image, scan the workspace for `.env*`,
        `*.pem`, `*.key`, `*credentials*.json`, and hardcoded secrets in
        `Dockerfile` (`ENV`/`ARG`) or Kubernetes manifests.
    *   Ensure secret files are added to `.dockerignore` and `.gcloudignore`,
        remove hardcoded secrets from `Dockerfile`/manifests, and recommend or
        configure **Google Cloud Secret Manager** (`--set-secrets` on Cloud Run
        or Secret Manager CSI driver / secret references on GKE).
7.  **Automatic Agent Registry Registration for AI Agents & MCP Servers**:

    *   Inspect the codebase (`requirements.txt`, `pyproject.toml`,
        `package.json`, `agent.py`, `mcp_server.py`) before deploying.
    *   If the workload is an **AI Agent** (`google-adk`, `langchain`,
        `langgraph`, `crewai`, `autogen`) or **MCP Server** (`mcp`, `fastmcp`,
        `@modelcontextprotocol/sdk`):
        *   Enable `agentregistry.googleapis.com` (`gcloud services enable
            agentregistry.googleapis.com --project=<PROJECT_ID> --quiet`).
        *   On **Cloud Run**, deploy with `gcloud beta run deploy` using
            `--functional-type=agent --identity-type=agent-identity` (for AI
            agents) or `--functional-type=mcp-server` (for MCP servers) and
            verify discovery via `gcloud agent-registry agents list` or
            `gcloud agent-registry mcp-servers list`
            (`--location=<REGION> --project=<PROJECT_ID>`).
        *   On **GKE**, add
            `metadata.labels["registry.gke.io/functional-type"]: "AGENT"` (or
            `"MCP_SERVER"`),
            `metadata.annotations["apphub.cloud.google.com/functional-type"]:
            "AGENT"` (or `"MCP_SERVER"`), and
            `spec.template.metadata.annotations["iam.gke.io/spiffe-identity-type"]:
            "agent-identity"` to the Kubernetes `Deployment`.
8.  **SBOM Generation on Image Build & Binary Authorization Enforcement on Cloud
    Run `prod`**:

    *   After pushing a container image to Artifact Registry, resolve its
        `@sha256:...` digest and export its SPDX SBOM using `gcloud artifacts
        sbom export --uri="<IMAGE_URI>@<DIGEST>" --project=<PROJECT_ID>`.
    *   When deploying to `cloud_run.prod` with
        `"binary_authorization": "default"`:
        *   Pass `--binary-authorization=default` to `gcloud run deploy`.
        *   Before deploying to `prod`, evaluate the Binary Authorization policy
            via `gcloud beta container binauthz policy evaluate
            "${BINARY_AUTHZ_POLICY:-prod-policy}" --platform=cloudRun
            --project=<PROJECT_ID> --image="<IMAGE_URI>@<DIGEST>" --format=yaml`
            and check existing attestations via
            `gcloud container binauthz attestations list
            --artifact-url="https://<IMAGE_URI>@<DIGEST>"
            --project=<PROJECT_ID>`. If `verdict: CONFORMANT` and an attestor
            signature is required, sign the digest via
            `gcloud beta container binauthz attestations sign-and-create
            --artifact-url="https://<IMAGE_URI>@<DIGEST>"`; if
            `verdict: NON_CONFORMANT`, do NOT sign and explain the failing SLSA
            provenance or vulnerability check.
how_to_write_dockerfile.md 13.6 KB
# Comprehensive Guide to Writing Dockerfiles

This document is a detailed guideline for writing professional-grade Dockerfiles
for Google Cloud Run and Google Kubernetes Engine (GKE).

## Table of Contents

-   [1. Core Principles: Thinking in Layers](#1-core-principles-thinking-in-layers)
    (Lines 16-32)
-   [2. General Best Practices](#2-general-best-practices) (Lines 34-53)
-   [3. Multi-Stage Builds (The Gold Standard)](#3-multi-stage-builds-the-gold-standard)
    (Lines 57-179)
-   [4. Recommended Base Images](#4-recommended-base-images) (Lines 183-304)
-   [5. Summary Checklist](#5-summary-checklist) (Lines 308-327)

## 1. Core Principles: Thinking in Layers

A Docker image is a stack of read-only layers. Each instruction (`RUN`, `COPY`,
`ADD`) creates a new layer.

*   **Optimize the Cache:** Order instructions from **least frequent to most
    frequent change**.
*   *Bad:* Copying all source code, then running `npm install`. (Cache busts on
    every code change).
*   *Good:* Copy `package.json`, run `install`, *then* copy source code.
*   *Install dependencies first:* For all languages, install dependencies before
    copying source code. This leverages Docker's layer caching.

*   **Combine RUN commands:** Use `&&` and line breaks (`\`) to group related
    commands (e.g.,
    `apt-get update && apt-get install -y ... && rm -rf /var/lib/apt/lists/*`)
    to keep the layer count and image size down.

## 2. General Best Practices

*   **Sort Multi-line arguments:** When writing RUN commands with multiple
    arguments, sort them alphabetically to improve readability and
    maintainability.
*   **COPY vs ADD:** Always use `COPY`. Use `ADD` only if you need to
    auto-extract a local `.tar` file into the image.
*   **Use `.dockerignore` (and `.gcloudignore`):** Create `.dockerignore` and
    `.gcloudignore` to exclude `node_modules`, `.git`, `.gcp-deploy/`, logs, and
    secret files (`.env*`, `*.pem`, `*.key`, `*credentials*.json`) from being
    sent to the build context. Never bake secrets into `ENV` or `ARG`
    instructions; inject them at runtime via Google Cloud Secret Manager
    (`--set-secrets`).
*   **Run as Non-Root:** By default, containers run as root. For production,
    create a user with a UID above 10,000 to prevent host-escalation attacks.

```dockerfile
RUN groupadd -g 10001 appgroup && useradd -u 10000 -g appgroup appuser
USER appuser
```

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

## 3. Multi-Stage Builds (The Gold Standard)

Multi-stage builds allow you to use a heavy image (with compilers and build
tools) for the build process and a tiny image (just the runtime) for the final
production container. Always use multi stage builds when possible.

### Why use Multi-Stage?

1.  **Drastic Size Reduction:** Your final image won't contain compilers, header
    files, or build caches.
2.  **Security:** Fewer binaries in the final image mean a smaller attack
    surface.
3.  **Simplicity:** You don't need separate build scripts; the entire CI/CD
    pipeline is documented in one Dockerfile.

### 💡 Example 1: Node.js (Standard Production Pattern)

This pattern separates the `npm install` (with dev dependencies for building)
from the production runtime.

```dockerfile
# --- Stage 1: Build & Test ---
FROM node:22-bookworm AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci  # Clean install including dev dependencies
COPY . .
RUN npm run build

# --- Stage 2: Production Runtime ---
FROM node:22-bookworm-slim AS runtime
WORKDIR /app
# Only copy production dependencies and the built dist folder
COPY --from=builder /app/package*.json ./
RUN npm ci --only=production
COPY --from=builder /app/dist ./dist

ENV PORT=8080
EXPOSE 8080
USER node
CMD ["node", "dist/index.js"]
```

### 💡 Example 2: Go (Compiled to Distroless/Scratch)

For compiled languages like Go, Rust, or C++, the final image can be effectively
"empty" except for your binary.

```dockerfile
# --- Stage 1: Build ---
FROM golang:1.23-alpine AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
# Build a statically linked binary
RUN CGO_ENABLED=0 GOOS=linux go build -o /bin/app ./main.go

# --- Stage 2: Runtime ---
# Using Google's "distroless" for maximum security (no shell, no package manager)
FROM gcr.io/distroless/static-debian12
COPY --from=builder /bin/app /app
ENV PORT=8080
EXPOSE 8080
USER 1000:1000
ENTRYPOINT ["/app"]
```

### 💡 Example 3: Python Application (Cloud Run & GKE Ready)

```dockerfile
# --- Stage 1: Builder Stage ---
FROM python:3.12-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

# --- Stage 2: Final (Runtime) Stage ---
FROM python:3.12-slim AS final
WORKDIR /app
RUN groupadd -g 10001 appgroup && useradd -u 10000 -g appgroup appuser
COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
COPY --from=builder /app .

ENV PORT=8080
EXPOSE 8080
USER appuser
CMD ["python", "app.py"]
```

### 💡 Example 4: AI Agent or MCP Server (Python ADK / FastMCP / Uvicorn)

When containerizing an IDE-generated **AI Agent** (`google-adk`, `langchain`,
`langgraph`) or **MCP Server** (`fastmcp`, `mcp`), ensure the server binds to
`0.0.0.0:${PORT:-8080}` and never hardcodes API keys (`GEMINI_API_KEY`,
`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`) in the `Dockerfile`:

```dockerfile
# --- Stage 1: Builder Stage ---
FROM python:3.12-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

# --- Stage 2: Production Runtime ---
FROM python:3.12-slim AS runtime
WORKDIR /app
RUN groupadd -g 10001 appgroup && useradd -u 10000 -g appgroup appuser
COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
COPY --from=builder /app .

ENV PYTHONUNBUFFERED=1
ENV PORT=8080
EXPOSE 8080
USER appuser

# Bind to 0.0.0.0:$PORT for Cloud Run and GKE health probes
CMD ["sh", "-c", "uvicorn main:app --host 0.0.0.0 --port ${PORT:-8080}"]
```

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

## 4. Recommended Base Images

### Generic Base Image suggestions

*   For programming languages use their official base image.
*   Use latest version of the language specific image as base image.
*   Review project config files to identify required runtime version:
    *   When a runtime version is specified, use that version for the base
        image.
    *   If no minimum version is specified, use a recent stable version of the
        runtime.

### Google Cloud Run Specific Base Images

If you are deploying to **Google Cloud Run**, you can leverage advanced features
for security and maintenance.

#### Base Image for Cloud Run Automatic Updates

Google Cloud can automatically patch security vulnerabilities in your base image
if you follow the **"Scratch Pattern"**.

1.  In your Dockerfile, copy your app onto a `FROM scratch` image.
2.  Deploy to Cloud Run using the `--base-image` flag.

**Dockerfile for Cloud Run Automatic Updates:**

```dockerfile
FROM node:24-slim AS builder
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=production
COPY . .

# Final stage: Start from scratch (Cloud Run will inject the OS/Runtime layers)
FROM scratch
WORKDIR /workspace
# Note: chown 33:33 is a common pattern for the 'www-data' user in Google's stacks
COPY --from=builder --chown=33:33 /usr/src/app/ ./
USER 33:33
CMD [ "node", "index.js" ]
```

#### Recommended Base Images (Stacks)

A base image serves as the starting foundation for container-based development.
You build your application by layering necessary libraries, binaries, and
configuration files on top of this image. Google Cloud's buildpacks publish
these images with various configurations for system packages and languages.

##### Key Guidelines

*   **Hosting**: Base images are hosted in every region where the Artifact
    Registry is available.
*   **Updates**: Security and maintenance updates are released routinely.
    Depending on your environment (e.g., Cloud Run functions) and configuration,
    these updates can be applied automatically or manually.
*   **URI Format**: To use a base image, you reference it using a specific URI
    structure which you can customize based on your location and requirements:
    `REGION-docker.pkg.dev/serverless-runtimes/STACK/runtimes/RUNTIME_ID`

**Customization Steps** You need to replace the specific portions of the URI
with your own values:

*   **REGION**: Replace with your preferred region (e.g., us-central1).
*   **STACK**: Replace with your preferred operating system stack (e.g.,
    google-24).
*   **RUNTIME_ID**: Replace with the specific ID for your language runtime
    (e.g., python313 or nodejs24). Detailed list of runtime ids is below:

Runtime IDs and environment details (mostly Ubuntu 22.04 or 18.04, with some
newer Ubuntu 24.04 options) for the following languages:

| Language  | Runtime     | Generation       | Environment  | Runtime ID |
| :-------- | :---------- | :--------------- | :----------- | :--------- |
| Node.js   | Node.js 24  | 2nd gen          | Ubuntu 24.04 | nodejs24   |
| Node.js   | Node.js 22  | 1st gen, 2nd gen | Ubuntu 22.04 | nodejs22   |
| Node.js   | Node.js 20  | 1st gen, 2nd gen | Ubuntu 22.04 | nodejs20   |
| Node.js   | Node.js 18  | 1st gen, 2nd gen | Ubuntu 22.04 | nodejs18   |
| Node.js   | Node.js 16  | 1st gen, 2nd gen | Ubuntu 18.04 | nodejs16   |
| Node.js   | Node.js 14  | 1st gen, 2nd gen | Ubuntu 18.04 | nodejs14   |
| Node.js   | Node.js 12  | 1st gen, 2nd gen | Ubuntu 18.04 | nodejs12   |
| Node.js   | Node.js 10  | 1st gen, 2nd gen | Ubuntu 18.04 | nodejs10   |
| Node.js   | Node.js 8   | 1st gen, 2nd gen | Ubuntu 18.04 | nodejs8    |
| Node.js   | Node.js 6   | 1st gen, 2nd gen | Ubuntu 18.04 | nodejs6    |
| Python    | Python 3.14 | 2nd gen          | Ubuntu 24.04 | python314  |
| Python    | Python 3.13 | 2nd gen          | Ubuntu 22.04 | python313  |
| Python    | Python 3.12 | 1st gen, 2nd gen | Ubuntu 22.04 | python312  |
| Python    | Python 3.11 | 1st gen, 2nd gen | Ubuntu 22.04 | python311  |
| Python    | Python 3.10 | 1st gen, 2nd gen | Ubuntu 22.04 | python310  |
| Python    | Python 3.9  | 1st gen, 2nd gen | Ubuntu 18.04 | python39   |
| Python    | Python 3.8  | 1st gen, 2nd gen | Ubuntu 18.04 | python38   |
| Python    | Python 3.7  | 1st gen          | Ubuntu 18.04 | python37   |
| Go        | Go 1.25     | 2nd gen          | Ubuntu 22.04 | go125      |
| Go        | Go 1.24     | 2nd gen          | Ubuntu 22.04 | go124      |
| Go        | Go 1.23     | 2nd gen          | Ubuntu 22.04 | go123      |
| Go        | Go 1.22     | 2nd gen          | Ubuntu 22.04 | go122      |
| Go        | Go 1.21     | 1st gen, 2nd gen | Ubuntu 22.04 | go121      |
| Go        | Go 1.20     | 1st gen, 2nd gen | Ubuntu 22.04 | go120      |
| Go        | Go 1.19     | 1st gen, 2nd gen | Ubuntu 22.04 | go119      |
| Go        | Go 1.18     | 1st gen, 2nd gen | Ubuntu 22.04 | go118      |
| Go        | Go 1.16     | 1st gen, 2nd gen | Ubuntu 18.04 | go116      |
| Go        | Go 1.13     | 1st gen, 2nd gen | Ubuntu 18.04 | go113      |
| Go        | Go 1.11     | 1st gen, 2nd gen | Ubuntu 18.04 | go111      |
| Java      | Java 25     | 2nd gen          | Ubuntu 24.04 | java25     |
| Java      | Java 21     | 2nd gen          | Ubuntu 22.04 | java21     |
| Java      | Java 17     | 1st gen, 2nd gen | Ubuntu 22.04 | java17     |
| Java      | Java 11     | 1st gen, 2nd gen | Ubuntu 18.04 | java11     |
| Ruby      | Ruby 3.4    | 2nd gen          | Ubuntu 22.04 | ruby34     |
| Ruby      | Ruby 3.3    | 1st gen, 2nd gen | Ubuntu 22.04 | ruby33     |
| Ruby      | Ruby 3.2    | 1st gen, 2nd gen | Ubuntu 22.04 | ruby32     |
| Ruby      | Ruby 3.0    | 1st gen, 2nd gen | Ubuntu 18.04 | ruby30     |
| Ruby      | Ruby 2.7    | 1st gen, 2nd gen | Ubuntu 18.04 | ruby27     |
| Ruby      | Ruby 2.6    | 1st gen, 2nd gen | Ubuntu 18.04 | ruby26     |
| PHP       | PHP 8.4     | 2nd gen          | Ubuntu 22.04 | php84      |
| PHP       | PHP 8.3     | 2nd gen          | Ubuntu 22.04 | php83      |
| PHP       | PHP 8.2     | 1st gen, 2nd gen | Ubuntu 22.04 | php82      |
| PHP       | PHP 8.1     | 1st gen, 2nd gen | Ubuntu 18.04 | php81      |
| PHP       | PHP 7.4     | 1st gen, 2nd gen | Ubuntu 18.04 | php74      |
| .NET Core | .NET Core 8 | 2nd gen          | Ubuntu 22.04 | dotnet8    |
| .NET Core | .NET Core 6 | 1st gen, 2nd gen | Ubuntu 22.04 | dotnet6    |
| .NET Core | .NET Core 3 | 1st gen, 2nd gen | Ubuntu 18.04 | dotnet3    |

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

## 5. Summary Checklist

Feature        | Best Practice
-------------- | -------------
**Base Image** | Use official, versioned, slim, or distroless images.
**Layers**     | Combine `RUN` commands; copy dependencies before source code.
**Security**   | Prefer not to run as `root`; never include secrets/ENV keys in Dockerfile.
**Size**       | Use **Multi-Stage builds** to strip out build-time bloat.
**Cloud Run**  | Listen on `0.0.0.0:${PORT:-8080}`; optionally use runtime base images.
**Metadata**   | Use `LABEL` to provide contact and versioning info.

#### Sources:

*   https://cloud.google.com/run/docs/configuring/services/automatic-base-image-updates
*   https://cloud.google.com/docs/buildpacks/base-images
*   https://cloud.google.com/run/docs/configuring/services/runtime-base-images
*   https://cloud.google.com/run/docs/building/containers
*   https://codelabs.developers.google.com/developing-containers-with-dockerfiles
*   https://docs.docker.com/get-started/docker-concepts/building-images/writing-a-dockerfile/
*   https://docs.docker.com/get-started/docker-concepts/building-images/multi-stage-builds/
sample-deployment-config.json 2.0 KB
{
  "active_runtime": "Cloud Run",
  "default_environment": "dev",
  "fail_on_push_error": true,
  "common_gcp_settings": {
    "project_id": "my-gcp-project",
    "region": "us-central1"
  },
  "cloud_run": {
    "dev": {
      "project_id": "my-gcp-project",
      "region": "us-central1",
      "artifact_registry": "us-central1-docker.pkg.dev/my-gcp-project/my-app-images-dev",
      "service_name": "<app-name>-dev",
      "public_access": true,
      "container_port": 8080
    },
    "prod": {
      "project_id": "my-gcp-project",
      "region": "us-central1",
      "artifact_registry": "us-central1-docker.pkg.dev/my-gcp-project/my-app-images-prod",
      "service_name": "<app-name>-prod",
      "public_access": false,
      "container_port": 8080,
      "require_confirmation": true,
      "binary_authorization": "default",
      "binary_authorization_policy": "prod-policy"
    }
  },
  "gke": {
    "dev": {
      "project_id": "my-gcp-project",
      "cluster_location": "us-central1",
      "cluster_name": "my-gke-cluster-dev",
      "namespace": "dev",
      "artifact_registry": "us-central1-docker.pkg.dev/my-gcp-project/my-app-images-dev",
      "manifest_path": "./kubernetes-manifests/"
    },
    "prod": {
      "project_id": "my-gcp-project",
      "cluster_location": "us-central1",
      "cluster_name": "my-gke-cluster-prod",
      "namespace": "prod",
      "artifact_registry": "us-central1-docker.pkg.dev/my-gcp-project/my-app-images-prod",
      "manifest_path": "./release/kubernetes-manifests.yaml",
      "require_confirmation": true
    }
  },
  "developer_connect_and_cloud_build": {
    "build_mode": "Developer Connect + Cloud Build",
    "developer_connect": {
      "location": "us-central1",
      "connection_id": "my-devconnect-connection"
    },
    "cloud_build_trigger": {
      "project_id": "my-gcp-project",
      "region": "us-central1",
      "service_account": "projects/my-gcp-project/serviceAccounts/cloudbuild-runner@my-gcp-project.iam.gserviceaccount.com",
      "default_branch": "^main$",
      "auto_run_trigger": true
    }
  }
}

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