Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cicd-pipeline-design@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin google-cicd-pipeline-design v1.0.0 follows the Agent Plugins spec.
gh skills-hub install google-cicd-pipeline-design Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/google-cicd-pipeline-design/ Extract the ZIP to .github/skills/ in your repo. The folder name must match google-cicd-pipeline-design for Copilot to auto-discover it.
Skill Files (11)
SKILL.md 10.6 KB
---
name: google-cicd-pipeline-design
metadata:
version: "1.0.0"
category: DevOps
description: >-
Use this skill to design and implement a Google Cloud based CI/CD pipeline. This skill encodes best practices for pipeline design, ensuring proper pattern selection and implementation. You MUST activate this skill when tasked with building a pipeline, designing architecture on GCP, or migrating pipelines.
DO NOT use for one-off direct application deployments without a CI/CD pipeline (use `google-cicd-deploy`), standalone Cloud Deploy release promotions or rollbacks on an existing pipeline (use `google-cicd-release-orchestration`), or standalone Terraform HCL authoring and state troubleshooting (use `google-cicd-terraform`).
---
# Google Cloud CI/CD Pipeline Design
## 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 design, build, and manage CI/CD pipelines on Google Cloud. You
operate by first analyzing the user's intent 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`) 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 cloudbuild.googleapis.com
developerconnect.googleapis.com artifactregistry.googleapis.com
secretmanager.googleapis.com run.googleapis.com container.googleapis.com
clouddeploy.googleapis.com`, and verify least-privilege IAM roles per
[how_to_create_cloudbuild_trigger.md](references/how_to_create_cloudbuild_trigger.md).
## Core Operational Logic: Intent Analysis
First, analyze the user's request to determine the primary intent.
* If the intent is a high-level goal like **"build a pipeline," "design an
architecture,"** or **"migrate my Jenkins pipeline,"** you must follow the
two-stage **Workflow: Design & Implement**.
## Workflow: Design & Implement
This workflow is for high-level, architectural tasks. It consists of a design
phase followed by an implementation phase.
### Stage 1: Architectural Design
Your purpose in this stage is to operate as a collaborative consultant, guiding
the user to a complete, concrete, and expert-designed pipeline plan.
1. **Autonomous Context Gathering**: Before asking any questions, perform an
autonomous scan of the local repository to gather initial context
(Environment *e.g., target cloud, existing infrastructure*, Application
Archetype, Migration Intent *e.g., from Jenkins, from on-prem*). In
addition, check for `.gcp-deploy/deployment-config.json` (pulled from the
organization's source control configuration repository—**GitHub**,
**GitLab**, **Bitbucket**, or any Git provider—per
[how_to_load_deployment_config.md](references/how_to_load_deployment_config.md)
and
[sample-deployment-config.json](references/sample-deployment-config.json))
and local `gcp-deploy.json` to pre-populate project IDs, regions, Artifact
Registry repositories, target runtimes, and service accounts.
2. **Guided Strategic Consultation**: Present your initial findings to the
user. Then, ask key strategic questions to clarify their release strategy
(e.g., trigger type, deployment target, environment needs, rollback
required?, canary deployments required?).
3. **Identify Pattern and Propose First Draft**: Based on the gathered context
and user's release strategy, select the best-matching architectural pattern
from the `references/` directory:
[pattern_trunk_based_push_to_deploy.txt](references/pattern_trunk_based_push_to_deploy.txt),
[pattern_trunk_based_ci_tag_based_cd.txt](references/pattern_trunk_based_ci_tag_based_cd.txt),
or
[pattern_git_tag_triggered_release.txt](references/pattern_git_tag_triggered_release.txt).
4. **Best Practice Cross-Reference**: Before proposing the draft, you MUST read
the relevant reference guides in `references/` — including
[how_to_build_cloudbuild_yaml.md](references/how_to_build_cloudbuild_yaml.md),
[how_to_write_dockerfile.md](references/how_to_write_dockerfile.md), and
[programming_language_specific_project_setup.md](references/programming_language_specific_project_setup.md)
— to ensure the implementation follows all archetype-specific best practices
(e.g., linting, testing, image tagging, scanning, provenance).
5. **Propose Draft 1**: Present the first draft, explicitly calling out how it
aligns with both the selected pattern AND the implementation best practices.
6. **Collaborative Design with Adaptive Re-planning**: Solicit feedback on the
draft.
* **For minor changes** (e.g., "add a linter"), update the plan and
present a new draft.
* **For major architectural changes** (e.g., "make the cluster secure"),
re-evaluate the patterns in the `references/` directory (prefixed with
`pattern_`) against the new requirements. Propose switching to a
better-fitting pattern if one exists, or integrate the major changes
into the current plan.
7. **Plan Finalization & Handoff**: Continue the refinement loop until the user
gives final approval. Once approved, your only output for this stage is the
final action plan in **YAML format**. After generating the YAML, you will
automatically proceed to Stage 2.
### Stage 2: Plan Implementation
Once the user has approved the YAML plan, you must guide them through the
implementation phase.
1. **Select Implementation Method**: Ask the user to choose their preferred
implementation approach:
* **Terraform**: Recommended for Infrastructure as Code (IaC) and
long-term maintenance.
* **Direct Implementation**: Recommended for rapid setup or direct
resource management.
2. **Execute Based on Choice**:
* **If Terraform is selected**:
* Activate the `google-cicd-terraform` skill.
* Translate the approved YAML plan into Terraform HCL, following the
standards and structure defined in the skill.
* Follow the skill's **Execution Protocol** (Init, Validate, Plan,
Apply), ensuring manual confirmation before the final `apply`.
* **If Direct Implementation is selected**:
* **Process Sequentially**: Execute the plan by processing the
`stages` object in order.
* **Leverage Skills & `gcloud` Commands**: For each component, consult
the relevant reference guides (e.g.,
[how_to_create_cloudbuild_trigger.md](references/how_to_create_cloudbuild_trigger.md))
or companion skills (e.g., `google-cicd-release-orchestration`,
`google-cicd-deploy`) and execute the corresponding `gcloud` CLI
commands via shell execution (do not rely on a local MCP server).
* **Report & Progress**: Announce the start of each step, wait for
success, and report completion before proceeding to the next
component.
## Universal Protocols & Constraints
### 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. Do not rely on a local MCP
server.
### Defaults
* **Git-Backed Organization Config (`deployment-config.json` &
`gcp-deploy.json`)**: First check `.gcp-deploy/deployment-config.json`
(fetched from the configured source control repository—**GitHub**,
**GitLab**, **Bitbucket**, or any Git provider—per
[how_to_load_deployment_config.md](references/how_to_load_deployment_config.md)
and
[sample-deployment-config.json](references/sample-deployment-config.json))
and local `gcp-deploy.json` for `project_id`, `region`, `active_runtime`,
`artifact_registry`, and `service_accounts`. If not yet configured for a new
project and the required parameters (`project_id`, `region`, target
runtime/registry) are not already provided in the prompt or workspace
context (`GEMINI.md`), prompt the user once for the Git config repository
URL and persist it.
* **Google Cloud CLI Fallback**: If no `deployment-config.json` is used, run
`gcloud config list` to get the default *project* and *region*.
* **GIT URL**: If git is installed use `git remote get-url origin` to get the
remote Git repository URL (across GitHub, GitLab, Bitbucket, or any
supported Git provider) for Developer Connect (`gcloud developer-connect`)
commands.
## Resource Cleanup & Teardown
Cloud Build builds, Artifact Registry repositories, Cloud Deploy pipelines, and
deployed runtimes 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 Build Triggers**: `gcloud builds triggers delete <TRIGGER_ID>
--region=<REGION> --project=<PROJECT_ID>`
* **Developer Connect**: `gcloud developer-connect connections
git-repository-links delete <REPO_LINK_ID> --connection=<CONNECTION_ID>
--location=<REGION> --project=<PROJECT_ID>` and
`gcloud developer-connect connections delete <CONNECTION_ID>
--location=<REGION> --project=<PROJECT_ID>`
* **Artifact Registry**: `gcloud artifacts repositories delete <REPO_NAME>
--location=<REGION> --project=<PROJECT_ID>`
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:google-cicd-pipeline-design)" \
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-pipeline-design)` 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-pipeline-design)
```
- **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_build_cloudbuild_yaml.md 7.0 KB
# How to Create a `cloudbuild.yaml` File
This document outlines the standard procedure for automatically generating a
`cloudbuild.yaml` configuration file. The primary goal is to create a
best-practice, archetype-specific CI/CD pipeline when one does not already exist
in the user's repository.
--------------------------------------------------------------------------------
## Table of Contents
- [When to Generate a `cloudbuild.yaml`](#when-to-generate-a-cloudbuildyaml)
(Lines 22-34)
- [Step 1: Discovering the Application Archetype](#step-1-discovering-the-application-archetype)
(Lines 38-55)
- [Step 2: Generating the Default CI Pipeline](#step-2-generating-the-default-ci-pipeline)
(Lines 59-76)
- [Key Best Practices and Configuration](#key-best-practices-and-configuration)
(Lines 80-101)
- [Example: Python Application](#example-python-application) (Lines 105-163)
## When to Generate a `cloudbuild.yaml`
The core principle is to be non-destructive and idempotent. The generation
process should only be triggered under one specific condition:
* **A `cloudbuild.yaml` file does not exist at the root of the source
repository (or on the remote default branch when creating a Cloud Build
trigger).**
If a `cloudbuild.yaml` file is already present, it should be treated as the
source of truth and used as-is without modification, unless the user explicitly
requests a change (or if `logging: CLOUD_LOGGING_ONLY` must be added for custom
service account compatibility).
--------------------------------------------------------------------------------
## Step 1: Discovering the Application Archetype
Before a `cloudbuild.yaml` can be generated, the application's archetype must be
identified. This is done by inspecting the local filesystem for common project
files. This discovery step is crucial for tailoring the build steps (e.g.,
linting, testing, Agent Registry registration) to the specific language or
framework.
The following mapping should be used:
* `pom.xml` → **Java (Maven)**
* `build.gradle` → **Java (Gradle)**
* `package.json` → **Node.js** (check for `@modelcontextprotocol/sdk` for MCP
Servers)
* `requirements.txt` or `pyproject.toml` → **Python** (check for `google-adk`,
`langchain`, `langgraph`, `crewai`, `autogen` for AI Agents, or `mcp`,
`fastmcp` for MCP Servers)
* `go.mod` → **Go**
--------------------------------------------------------------------------------
## Step 2: Generating the Default CI Pipeline
If no `cloudbuild.yaml` exists, a new one should be generated with a standard,
four-step CI sequence (plus optional SPDX SBOM export and deployment steps when
requested). These steps must be tailored to the discovered application
archetype.
1. **Lint**: Run a static code analysis tool to check for stylistic or
programmatic errors. The specific linter should match the application
archetype (e.g., `pylint` or `ruff` for Python, `eslint` for Node.js).
2. **Test**: Execute the project's unit tests. The test runner should match the
archetype (e.g., `pytest` for Python, `go test` for Go, `mvn test` for
Maven).
3. **Build Container**: Use the native `gcr.io/cloud-builders/docker` builder
to build the container image from the `Dockerfile` in the repository.
4. **Push Container & Export SBOM**: Push the newly built container image to
the verified Artifact Registry repository and optionally export an SPDX
Software Bill of Materials (`gcloud artifacts sbom export`).
--------------------------------------------------------------------------------
## Key Best Practices and Configuration
When generating the `cloudbuild.yaml`, several best practices must be included
to ensure security, compatibility with custom service accounts, and supply-chain
verification:
* **Image Tagging**: The container image must be tagged with the `$SHORT_SHA`
substitution variable (or `:latest` when triggered ad-hoc). This ensures a
unique, traceable image for every commit.
* **Use the `images` Attribute**: The final image URI should be explicitly
listed under the top-level `images` attribute in the `cloudbuild.yaml`. This
allows Cloud Build to push the image and record build provenance
automatically.
* **Mandatory `logging: CLOUD_LOGGING_ONLY` for Custom Service Accounts**:
Whenever a Cloud Build trigger or build uses a user-managed
`--service-account` (as required in `deployment-config.json`), Cloud Build
requires `logging: CLOUD_LOGGING_ONLY` inside the `options:` block. Omitting
`CLOUD_LOGGING_ONLY` causes builds with custom service accounts to fail with
`INVALID_ARGUMENT`.
* **Enable Provenance**: To enhance supply chain security and support Binary
Authorization policies on `prod`, build provenance should always be enabled
by setting `requestedVerifyOption: VERIFIED` under `options:`.
--------------------------------------------------------------------------------
## Example: Python Application
Here is a complete, best-practice `cloudbuild.yaml` generated for a Python
application that uses `pytest` for testing, exports an SPDX SBOM, and configures
both `CLOUD_LOGGING_ONLY` and SLSA provenance verification.
```yaml
# Auto-generated cloudbuild.yaml for a Python application
steps:
# Step 1: Install dependencies and run unit tests with pytest
# Run in a single step since only /workspace persists across Cloud Build steps.
- name: 'python:3.12-slim'
entrypoint: 'bash'
args:
- '-c'
- |
pip install -r requirements.txt pytest
python -m pytest
# Step 2: Build the container image
# The image is tagged with the short commit SHA for traceability.
- name: 'gcr.io/cloud-builders/docker'
args:
- 'build'
- '-t'
- '${_LOCATION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_IMAGE_NAME}:$SHORT_SHA'
- '.'
# Step 3: Push the container image to Artifact Registry
- name: 'gcr.io/cloud-builders/docker'
args:
- 'push'
- '${_LOCATION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_IMAGE_NAME}:$SHORT_SHA'
# Step 4 (Optional): Export SPDX SBOM for supply-chain verification
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
entrypoint: 'bash'
args:
- '-c'
- |
DIGEST=$(gcloud artifacts docker images describe "${_LOCATION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_IMAGE_NAME}:$SHORT_SHA" --format="value(image_summary.digest)")
gcloud artifacts sbom export --uri="${_LOCATION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_IMAGE_NAME}@${DIGEST}" --project="${PROJECT_ID}" || true
# Default substitution values (override on triggers or `gcloud builds submit --substitutions`)
substitutions:
_LOCATION: 'us-central1'
_REPO_NAME: 'my-repo'
_IMAGE_NAME: 'my-app'
# Explicitly list the final image to be pushed and verified.
images:
- '${_LOCATION}-docker.pkg.dev/${PROJECT_ID}/${_REPO_NAME}/${_IMAGE_NAME}:$SHORT_SHA'
# Enable CLOUD_LOGGING_ONLY (mandatory for custom service accounts) and SLSA provenance.
options:
logging: CLOUD_LOGGING_ONLY
requestedVerifyOption: VERIFIED
```
how_to_create_cloudbuild_trigger.md 14.8 KB
# End-to-End Guide: Creating a Cloud Build Trigger
This document outlines the standard, idempotent procedure for creating a Google
Cloud Build trigger. Creating the trigger is the **final** action in a sequence
of prerequisite checks and resource provisioning steps. The agent must ensure
all dependencies are met before attempting to create the trigger itself.
--------------------------------------------------------------------------------
## Table of Contents
- [Core Principle: Idempotency](#core-principle-idempotency) (Lines 19-23)
- [Prerequisite Checklist](#prerequisite-checklist) (Lines 27-224)
- [Final Step: Creating the Trigger via `gcloud`](#final-step-creating-the-trigger-via-gcloud)
(Lines 228-289)
- [Troubleshooting Authentication, Permission & Trigger Errors](#troubleshooting-authentication-permission-trigger-errors)
(Lines 293-327)
## Core Principle: Idempotency
Every step in this process must be **idempotent**. This means the agent must
**always check if a resource already exists** before attempting to create it.
This prevents errors and ensures the process can be run multiple times safely.
--------------------------------------------------------------------------------
## Prerequisite Checklist
The following dependencies must be satisfied in order before creating the
trigger.
### 1. Ensure `cloudbuild.yaml` Exists (or Prepare `--inline-config`)
The trigger needs a build configuration to execute, and **whenever a dedicated
`--service-account` is used, Cloud Build requires
`options: { logging: CLOUD_LOGGING_ONLY }`**:
```yaml
options:
logging: CLOUD_LOGGING_ONLY
```
* **Action**: Check if `cloudbuild.yaml` and `Dockerfile` exist on the remote
default branch
(`git ls-tree "origin/${DEFAULT_BRANCH}" cloudbuild.yaml Dockerfile`).
* **If present on the remote default branch**: Use
`--build-config="cloudbuild.yaml"`.
* **If `cloudbuild.yaml` or `Dockerfile` only exists locally (not committed to
`origin/${DEFAULT_BRANCH}`)**: Pass
`--inline-config=<PATH_TO_INLINE_CLOUDBUILD_YAML>` to
`gcloud beta builds triggers create developer-connect` (writing the
`Dockerfile` in a build step if `Dockerfile` is missing from the remote
branch, and including `options: { logging: CLOUD_LOGGING_ONLY }`) so the
remote build succeeds on the first try without
`FAILED_PRECONDITION: Couldn't read commit`.
### 2. Ensure Artifact Registry Repository Exists
The `cloudbuild.yaml` file will reference an Artifact Registry repository to
push container images. This repository must exist before a build can succeed.
* **Action**: Parse the `cloudbuild.yaml` file to identify the Artifact
Registry image path (e.g.,
`us-central1-docker.pkg.dev/my-project/my-app-repo/my-image`).
* **Extract** the repository portion
(`us-central1-docker.pkg.dev/my-project/my-app-repo`).
* **Check** if this repository already exists in the target GCP project using
`gcloud`:
```bash
gcloud artifacts repositories describe <REPO_NAME> --location=<REGION> --project=<PROJECT_ID>
```
* **If it does not exist**: Create it using `gcloud`:
```bash
gcloud artifacts repositories create <REPO_NAME> \
--repository-format=docker \
--location=<REGION> \
--project=<PROJECT_ID>
```
### 3. Ensure Developer Connect and Repository Link Exist (GitHub, GitLab, Bitbucket)
Cloud Build triggers connect to source code via Developer Connect across
**GitHub**, **GitLab**, and **Bitbucket**. The entire connection and repository
link must be in place.
1. **Check for Connection**: First, check if a Developer Connect connection
already exists for the relevant Git provider (**GitHub**, **GitLab**, or
**Bitbucket**) in the target project and region:
```bash
gcloud developer-connect connections list --location=<REGION> --project=<PROJECT_ID>
```
2. **Create Connection (if needed)**: If no suitable connection exists, create
one using `gcloud developer-connect connections create` based on the Git
provider (and prompt the user to complete the authorization flow via the
`installationState.actionUri` in the GCP Console if `STAGE != COMPLETE`):
* **GitHub**:
```bash
gcloud developer-connect connections create <CONNECTION_ID> \
--location=<REGION> \
--project=<PROJECT_ID> \
--github-config-app=developer-connect
```
* **GitLab (`gitlab.com` or GitLab Enterprise)**:
```bash
gcloud developer-connect connections create <CONNECTION_ID> \
--location=<REGION> \
--project=<PROJECT_ID> \
--gitlab-config-webhook-secret-version=<WEBHOOK_SECRET_VERSION> \
--gitlab-config-authorizer-credential-user-token-secret-version=<AUTHORIZER_TOKEN_SECRET_VERSION> \
--gitlab-config-read-authorizer-credential-user-token-secret-version=<READ_TOKEN_SECRET_VERSION>
```
* **Bitbucket (`bitbucket.org` or Bitbucket Data Center)**:
```bash
gcloud developer-connect connections create <CONNECTION_ID> \
--location=<REGION> \
--project=<PROJECT_ID> \
--bitbucket-cloud-config-workspace=<WORKSPACE> \
--bitbucket-cloud-config-webhook-secret-version=<WEBHOOK_SECRET_VERSION> \
--bitbucket-cloud-config-authorizer-credential-user-token-secret-version=<AUTHORIZER_TOKEN_SECRET_VERSION> \
--bitbucket-cloud-config-read-authorizer-credential-user-token-secret-version=<READ_TOKEN_SECRET_VERSION>
```
3. **Obtain Source URI**: The agent must know the exact URI of the source code
repository (e.g., `https://github.com/<ORG>/<APP>.git`,
`https://gitlab.com/<GROUP>/<APP>.git`, or
`https://bitbucket.org/<WORKSPACE>/<APP>.git`). This should be obtained from
the user-approved plan, `git remote get-url origin`, or by asking the user
directly.
4. **Check for Repository Link**: Check if a repository link for that specific
URI already exists within the Developer Connect connection:
```bash
gcloud developer-connect connections git-repository-links list \
--connection=<CONNECTION_ID> \
--location=<REGION> \
--project=<PROJECT_ID>
```
5. **Create Repository Link (if needed)**: If the link does not exist, create
it using `gcloud`:
```bash
gcloud developer-connect connections git-repository-links create <REPO_LINK_ID> \
--connection=<CONNECTION_ID> \
--clone-uri=<GIT_REPO_URI> \
--location=<REGION> \
--project=<PROJECT_ID>
```
This link
(`projects/<PROJECT_ID>/locations/<REGION>/connections/<CONNECTION_ID>/gitRepositoryLinks/<REPO_LINK_ID>`)
is the resource that the Cloud Build trigger will formally point to.
### 4. Ensure Dedicated Service Account and Required IAM Roles Exist
Cloud Build triggers should **always** use a dedicated, user-managed service
account instead of the default Compute Engine service account to follow the
principle of least privilege. **CRITICAL: NEVER use the default Compute Engine
service account (typically formatted as
`[PROJECT_NUMBER]-compute@developer.gserviceaccount.com`), even if you observe
existing triggers in the project using it.**
1. **Check or Create Service Account**:
```bash
gcloud iam service-accounts describe <SA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com --project=<PROJECT_ID> || \
gcloud iam service-accounts create <SA_NAME> \
--display-name="Cloud Build Trigger Service Account" \
--project=<PROJECT_ID>
```
2. **Grant Required Least-Privilege Roles to the Dedicated Service Account**:
Grant the necessary roles (`roles/artifactregistry.writer`,
`roles/developerconnect.readTokenAccessor`, `roles/logging.logWriter`,
`roles/run.developer`, `roles/serviceusage.serviceUsageConsumer`) to
`serviceAccount:<SA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com` (if a build
cache/artifact GCS bucket is needed beyond `CLOUD_LOGGING_ONLY`, grant
`roles/storage.objectUser` scoped strictly to that bucket):
```bash
for ROLE in \
roles/artifactregistry.writer \
roles/developerconnect.readTokenAccessor \
roles/logging.logWriter \
roles/run.developer \
roles/serviceusage.serviceUsageConsumer; do
gcloud projects add-iam-policy-binding <PROJECT_ID> \
--member="serviceAccount:<SA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com" \
--role="$ROLE" \
--condition=None
done
```
3. **Grant Service Agent Roles (Developer Connect & Cloud Build P4SAs)**:
Retrieve the project number (`PROJECT_NUMBER=$(gcloud projects describe
<PROJECT_ID> --format='value(projectNumber)')`) and ensure the Developer
Connect and Cloud Build service agents have required permissions:
```bash
PROJECT_NUMBER=$(gcloud projects describe <PROJECT_ID> --format='value(projectNumber)')
# Developer Connect Service Agent
gcloud projects add-iam-policy-binding <PROJECT_ID> \
--member="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-devconnect.iam.gserviceaccount.com" \
--role="roles/secretmanager.admin" \
--condition=None
# Cloud Build Service Agent
for ROLE in roles/cloudbuild.serviceAgent roles/developerconnect.readTokenAccessor; do
gcloud projects add-iam-policy-binding <PROJECT_ID> \
--member="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-cloudbuild.iam.gserviceaccount.com" \
--role="$ROLE" \
--condition=None
done
# Allow Cloud Build Service Agent to act as the dedicated build SA and Cloud Run runtime SA
gcloud iam service-accounts add-iam-policy-binding <SA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com \
--member="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-cloudbuild.iam.gserviceaccount.com" \
--role="roles/iam.serviceAccountUser" \
--project=<PROJECT_ID>
```
--------------------------------------------------------------------------------
## Final Step: Creating the Trigger via `gcloud`
Once all prerequisites are met, resolve the repository's **default branch in
remote source control** (do not worry about unpublished local branches) using
the Developer Connect repository link's read token + `git ls-remote --symref` so
it works across any Git provider (**GitHub**, **GitLab**, **Bitbucket**, etc.)
even when there is no local clone:
```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
if echo "<GIT_REPO_URI>" | grep -qi "gitlab"; then
GIT_USER="oauth2"
elif echo "<GIT_REPO_URI>" | 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')"
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
```
Then check if the trigger already exists and create it using
`gcloud builds triggers create developer-connect`. **You MUST provide the full
resource name of the dedicated service account created in Step 4 to the
`--service-account` flag.**
```bash
gcloud builds triggers describe <TRIGGER_ID> --region=<REGION> --project=<PROJECT_ID> || \
gcloud builds triggers create developer-connect \
--name=<TRIGGER_ID> \
--region=<REGION> \
--project=<PROJECT_ID> \
--repository="projects/<PROJECT_ID>/locations/<REGION>/connections/<CONNECTION_ID>/gitRepositoryLinks/<REPO_LINK_ID>" \
--branch-pattern="^${DEFAULT_BRANCH}$" \
--build-config="cloudbuild.yaml" \
--service-account="projects/<PROJECT_ID>/serviceAccounts/<SA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com"
```
*(Note: If the trigger should run on tags instead of branches, replace
`--branch-pattern="^${DEFAULT_BRANCH}$"` with `--tag-pattern="<TAG_REGEX>"`.)*
### Running the Trigger Manually via `gcloud`
When invoking the trigger with `gcloud builds triggers run`, always target the
**default branch in remote source control** (`${DEFAULT_BRANCH}`, resolved from
`refs/remotes/origin/HEAD` or `git ls-remote --symref origin HEAD`; do not check
for or worry about unpublished local branches) and **strip any `^` or `$` regex
characters** (pass `--branch="${DEFAULT_BRANCH}"`, NOT
`--branch="^${DEFAULT_BRANCH}$"`):
```bash
gcloud builds triggers run <TRIGGER_ID> \
--region=<REGION> \
--project=<PROJECT_ID> \
--branch="${DEFAULT_BRANCH}"
```
--------------------------------------------------------------------------------
## Troubleshooting Authentication, Permission & Trigger Errors
When creating or running a Developer Connect + Cloud Build trigger fails,
diagnose the exact root cause and never bypass the error by switching to local
Docker builds or the default Compute Engine service account:
1. **`INVALID_ARGUMENT: if 'build.service_account' is specified, the build must
either (a) specify 'build.logs_bucket', (b) use the CLOUD_LOGGING_ONLY
logging option, or (c) use the NONE logging option`**:
* **Cause**: A custom `--service-account` is configured on the trigger,
but the `cloudbuild.yaml` (or `--inline-config`) omits
`options: { logging: CLOUD_LOGGING_ONLY }`.
* **Fix**: Add `options: { logging: CLOUD_LOGGING_ONLY }` to
`cloudbuild.yaml` (or `--inline-config`) and ensure the custom service
account has `roles/logging.logWriter`.
2. **`PERMISSION_DENIED` when linking a repository or fetching a read token
(`developerconnect.gitRepositoryLinks.fetchReadToken` /
`developerconnect.gitRepositoryLinks.create`)**:
* **Cause**: Either the caller lacks
`roles/developerconnect.readTokenAccessor` /
`roles/developerconnect.admin`, or the GitHub/GitLab/Bitbucket App
installation in Developer Connect does not have access to the target
repository.
* **Fix**: Grant `roles/developerconnect.readTokenAccessor` (or
`roles/developerconnect.admin`) to the caller and verify the repository
is authorized in the Developer Connect connection settings.
3. **`PERMISSION_DENIED: Caller does not have required permission to use
service account ...` (`iam.serviceAccounts.actAs`)**:
* **Cause**: The caller or Cloud Build Service Agent lacks
`roles/iam.serviceAccountUser` on the dedicated Cloud Build service
account (`<SA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com`).
* **Fix**: Run `gcloud iam service-accounts add-iam-policy-binding
<SA_NAME>@<PROJECT_ID>.iam.gserviceaccount.com
--member="<CALLER_OR_P4SA>" --role="roles/iam.serviceAccountUser"
--project=<PROJECT_ID>`.
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-pipeline-design)"
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/
pattern_git_tag_triggered_release.txt 2.4 KB
name: "Git Tag-Triggered Release"
description: "A pattern where every commit runs CI (lint, test, build), but a deployment is only initiated when a formal Git tag is pushed. The tag triggers a final build and creates a release in Cloud Deploy."
applicability:
triggers: ["git_commit", "git_tag"]
deployment_style: "continuous_delivery"
use_case_keywords: ["versioned releases", "production pipeline", "staging environment", "manual promotion"]
stages:
# The CI stage runs on every commit to verify code quality but does not produce a deployable artifact.
ci:
id: "ci_build_and_test"
type: "cloud-build"
name: "CI Build and Test"
details: "Listens for commits on the main branch. Runs lint, test, and builds the container to ensure it's valid, but does not push it."
steps:
- id: "lint_step"
type: "linter"
name: "Run Linter"
details: "Runs a static code analysis tool appropriate for the project."
- id: "test_step"
type: "test"
name: "Run Unit Tests"
details: "Executes the project's unit test suite."
- id: "dry_run_build_step"
type: "docker"
name: "Dry-Run Build"
details: "Builds the container image to validate the Dockerfile but does not push it."
# The CD stage is a distinct workflow triggered only by a Git tag.
cd:
trigger:
type: "git_tag"
details: "This stage is initiated by pushing a git tag (e.g., v1.2.0)."
steps:
- id: "build_and_push_release_artifact"
type: "cloud-build"
name: "Build and Push Release Artifact"
details: "Builds the final container image, signs it, and pushes it to Artifact Registry, tagged with the specific Git tag."
- id: "create_cloud_deploy_release"
type: "cloud-deploy"
name: "Create Cloud Deploy Release"
details: "Creates a new formal release in Cloud Deploy using the tagged container image, making it available for promotion to various environments."
tradeoffs:
pros:
- "Strong separation between integration and deployment, preventing every commit from going to production."
- "Creates a clear audit trail; every release is tied to a specific version tag in Git."
- "Enables controlled promotions (dev -> staging -> prod) via Cloud Deploy."
cons:
- "Slower feedback loop for deployment compared to push-to-deploy."
- "Requires disciplined Git tagging practices from the development team." pattern_trunk_based_ci_tag_based_cd.txt 2.3 KB
name: "Trunk-Based CI and Tag-Based CD"
description: "A pattern where every push to the main branch triggers code quality checks (linting and testing). Deployment is only initiated when a Git tag is pushed, triggering a final container build and a release creation in Cloud Deploy."
applicability:
triggers: ["git_push", "git_tag"]
deployment_style: "continuous_delivery"
use_case_keywords: ["trunk-based-ci", "tag-based-cd", "lint-test-only", "cloud-deploy", "rollbacks", "canary deployments"]
stages:
# CI stage runs on every commit to the main branch.
ci:
id: "ci_pipeline"
type: "cloud-build"
name: "CI Pipeline (Main Branch)"
details: "Runs automatically on each push to the main branch. Focuses on code quality and correctness."
trigger:
event: "push"
branch: "main"
steps:
- id: "lint_step"
type: "linter"
name: "Run Linter"
details: "Runs static code analysis tools to ensure code health."
state: "create"
- id: "test_step"
type: "test"
name: "Run Unit Tests"
details: "Executes the unit test suite to verify code changes."
state: "create"
# CD stage is triggered by a formal Git tag.
cd:
id: "cd_pipeline"
type: "cloud-build"
name: "Tag-Based CD Release"
details: "Initiated by pushing a Git tag (e.g., v1.0.0). Builds the production artifact and starts the deployment process."
trigger:
event: "push"
tag: "^v.*"
steps:
- id: "build_and_push_image"
type: "docker"
name: "Build and Push Image"
details: "Builds a production container image and pushes it to Artifact Registry, tagged with the Git tag."
state: "create"
- id: "create_cloud_deploy_release"
type: "cloud-deploy"
name: "Create Cloud Deploy Release"
details: "Creates a release in Cloud Deploy, which triggers the first rollout to the initial environment."
state: "create"
tradeoffs:
pros:
- "Decouples deployment from integration, allowing for controlled releases."
- "Minimizes unnecessary builds by only pushing images when a release is intended."
- "Establishes a clear mapping between Git versions and deployed artifacts."
cons:
- "Slower path to deployment compared to continuous deployment."
- "Relies on manual tagging which can be bypassed if not enforced."
pattern_trunk_based_push_to_deploy.txt 2.0 KB
name: "Trunk-Based Push-to-Deploy"
description: "A simple and fast pattern where every commit to the main or develop branch is instantly built, tested, and deployed to a shared development environment on Cloud Run or GKE."
applicability:
triggers: ["git_commit", "push"]
deployment_style: "continuous_deployment"
use_case_keywords: ["rapid iteration", "vibe coding", "development environment", "trunk-based"]
stages:
# In this pattern, CI and CD are a single, unified stage executed by Cloud Build.
ci_cd:
id: "trunk_based_flow"
type: "cloud-build"
name: "Trunk-Based CI and CD Flow"
details: "A single process triggered by a commit. It handles linting, testing, building, pushing, and deploying the application."
state: "create"
# The following steps will be translated into a single cloudbuild.yaml file.
steps:
- id: "lint_step"
type: "linter"
name: "Run Linter"
details: "Runs a static code analysis tool appropriate for the project."
state: "create"
- id: "test_step"
type: "test"
name: "Run Unit Tests"
details: "Executes the project's unit test suite."
state: "create"
- id: "build_and_push_step"
type: "docker"
name: "Build and Push Container"
details: "Builds a container image and pushes it to Artifact Registry, tagged with the commit SHA."
state: "create"
- id: "deploy_step"
type: "gcloud-deploy"
name: "Deploy to Cloud Run or GKE"
details: "Deploys the newly pushed container image to a shared development environment on Cloud Run or GKE."
state: "create"
tradeoffs:
pros:
- "Extremely fast feedback loop from commit to deployment."
- "Simplifies the release process, removing overhead."
- "Ideal for development and testing environments where speed is critical."
cons:
- "Can lead to an unstable development environment if tests are not robust."
- "Not suitable for production without adding quality gates and approvals."
programming_language_specific_project_setup.md 3.5 KB
## Example config for project setup
### Python
Python has shifted toward a more unified configuration approach recently, but
you'll still see a mix of old and new.
* pyproject.toml: The modern standard for defining build systems and project
metadata.
* requirements.txt: A simple list of dependencies for pip.
* setup.py / setup.cfg: Legacy files for packaging and distribution.
* environment.yml: Used specifically for Conda virtual environments.
* tox.ini: Configuration for automated testing across different Python
versions.
### Java
Java relies heavily on established build automation tools.
* pom.xml: The core configuration file for Maven projects.
* build.gradle: The build script for Gradle (Groovy DSL).
* settings.gradle: Defines project structure and module names for Gradle.
* MANIFEST.MF: Defines extension and package-related data for JAR files.
### Go (Golang)
Go keeps it minimal with a focus on reproducibility.
* go.mod: Defines the module's path and its dependency requirements.
* go.sum: Contains the expected cryptographic hashes of the content of
specific module versions.
### Ruby
Ruby’s ecosystem is centered around "Gems."
* Gemfile: Describes the gem dependencies required to run the Ruby code.
* Gemfile.lock: Records the exact versions of gems that were installed.
* .ruby-version: Specifies which version of the Ruby interpreter should be
used.
* Rakefile: Contains instructions for rake (Ruby's build program).
### Node.js
The JavaScript/TypeScript ecosystem is highly standardized.
* package.json: Manifest file containing metadata, scripts, and dependencies.
* package-lock.json (or yarn.lock / pnpm-lock.yaml): Ensures consistent
installation across machines.
* tsconfig.json: Configuration for TypeScript compiler settings.
* .npmrc: Configuration file for how npm should behave.
### Rust
Rust uses a single, powerful tool called Cargo.
* Cargo.toml: The manifest file where you declare dependencies and metadata.
* Cargo.lock: Created automatically to ensure reproducible builds by locking
dependency versions.
### Kotlin
Since Kotlin is often used in the JVM or Android ecosystem, it shares tools with
Java but uses its own "flavor."
* build.gradle.kts: Gradle build script using the Kotlin DSL.
* settings.gradle.kts: Project-wide settings using Kotlin DSL.
### PHP
Modern PHP development revolves around Composer.
* composer.json: Defines dependencies, autoloading rules, and project
metadata.
* composer.lock: Locks the project to specific versions of dependencies.
* php.ini: The main configuration file for the PHP interpreter itself.
### C / C++
These languages are more fragmented, often depending on the build system chosen.
* Makefile: Used by the make build automation tool.
* CMakeLists.txt: Configuration for CMake, the industry standard for
cross-platform C/C++ builds.
* conanfile.txt / conanfile.py: Used by the Conan package manager.
* vcpkg.json: Configuration for the vcpkg dependency manager.
### Visual Studio (IDE Specific)
While the languages above use the files listed, the Visual Studio IDE adds its
own layer.
* .sln: The Solution file; acts as a container for one or more projects.
* .csproj / .vcxproj: Project files for C# and C++ respectively, containing
build settings and file references.
* .editorconfig: Defines coding styles (indentation, etc.) to be enforced by
the editor.
* App.config / Web.config: XML files for runtime configuration settings.
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