Installation

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

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

Install with the gh extension
gh skills-hub install google-cicd-release-orchestration

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

Download and extract to your repository:

.github/skills/google-cicd-release-orchestration/

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

Skill Files (12)

SKILL.md 16.3 KB
---
name: google-cicd-release-orchestration
metadata:
  version: "1.0.0"
  category: DevOps
description: >-
  Use this skill when you need to design Cloud Deploy delivery pipelines or manage releases for applications deploying to Cloud Run or Google Kubernetes Engine (GKE). This skill encodes best practices for multi-environment deployment, deployment strategies (like canary), and release management (including rollbacks and automations). Always activate this skill for these tasks to ensure robust and consistent configuration.
  DO NOT use for single-step direct deployments to Cloud Storage, Cloud Run, or GKE without Cloud Deploy (use `google-cicd-deploy`), end-to-end CI/CD source-to-build trigger architecture design (use `google-cicd-pipeline-design`), or Terraform HCL infrastructure provisioning (use `google-cicd-terraform`).
---

# Cloud Deploy Pipelines

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

## Overview

This skill encompasses the entire lifecycle of Cloud Deploy for a user, from
designing and creating delivery pipelines to managing releases and debugging
release failures.

**All** Workflows require the `clouddeploy.googleapis.com` API to be enabled.

## 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`, `skaffold`, 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 clouddeploy.googleapis.com cloudbuild.googleapis.com
    artifactregistry.googleapis.com run.googleapis.com container.googleapis.com
    monitoring.googleapis.com`, and verify target IAM roles per
    [iam-permissions.md](references/iam-permissions.md).

## Workflow: Designing a Pipeline

This workflow provides steps for designing a Cloud Deploy `DeliveryPipeline`.

### Constraints & Rules

1.  **NO PLACEHOLDERS**: Never generate YAML with placeholders like
    `<PROJECT_ID>`. Ask the user for values first.
2.  **Context First**: Always check existing files and conversation context
    before asking.
3.  **Step-by-Step**: Perform the steps one at a time. The goal is to guide the
    user through designing a delivery pipeline.

### Step 0: Prerequisites

**Required Context**: Before generating ANY configuration for this workflow,
first check `.gcp-deploy/deployment-config.json` (pulled from the organization's
source control config 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 automatically populate the values below. Ask the
user strictly for any information still missing:

-   **Project ID**: The Google Cloud project ID for the Cloud Deploy resources.
-   **Region**: The region for the Cloud Deploy resources (e.g., `us-central1`).
-   **Application Name**: The name of the application that will be deployed. Use
    the application name to generate the names of the Cloud Deploy resources,
    such as `DeliveryPipeline` and `Target` resources.
-   **Runtime**: Either Cloud Run or Google Kubernetes Engine (GKE).
    -   **If Cloud Run**: The Cloud Run project and location.
    -   **If GKE**: The GKE cluster name.

### Step 1: Define the target environments

1.  Identify the number of deployment environments (e.g., dev, staging,
    production).
2.  Identify if promotions should require user approval.
3.  Define each of the deployment environments as Cloud Deploy `Target`
    resources in a `clouddeploy.yaml` file.
    -   Use [configure-targets.md](references/configure-targets.md) as a
        reference when generating the resource YAML.
    -   Always prefix target IDs with the application name provided by the user
        (e.g., `[app-name]-[env]`) to prevent resource name collisions when
        multiple applications are deployed to different environments. For
        example, if the user wants to deploy an application named "hello-world"
        to test and prod environments, then use "hello-world-test" and
        "hello-world-prod" as the `Target` IDs.

### Step 2: Define the delivery pipeline

1.  Identify whether the user wants to use a canary deployment strategy for any
    of the target environments.
2.  Define the Cloud Deploy `DeliveryPipeline` in the `clouddeploy.yaml` file.
    -   Use [configure-pipelines.md](references/configure-pipelines.md) as a
        reference when generating the resource YAML.
    -   Use application name as the `DeliveryPipeline` ID.

### Step 3: Define automations

1.  Identify whether the user wants to automatically rollback if any failures
    occur during the rollout.
2.  **If the user specified multiple deployment environments in the previous
    step**
    -   Identify if they want automatic promotions between deployment
        environments.
3.  **If the user specified a canary deployment strategy in the previous step**
    -   Identify if they want to automatically advance the rollout through the
        phases after a wait period.
4.  Define the Cloud Deploy `Automation` resources in the `clouddeploy.yaml`
    file.
    -   Use [configure-automations.md](references/configure-automations.md) as a
        reference when generating the resource YAML.

### Step 4: Validate the clouddeploy.yaml file

Ensure that the `clouddeploy.yaml` file is valid. See
https://docs.cloud.google.com/deploy/docs/config-files.md.txt for the schema.

### Step 5: Create the delivery pipeline

Run the following command to create the Cloud Deploy `DeliveryPipeline` and
associated resources, using the values collected in Step 0:

```bash
gcloud deploy apply --file=clouddeploy.yaml --region=<REGION> --project=<PROJECT_ID>
```

### Step 6: Create a skaffold.yaml file and runtime manifests

**Required Context**: Before generating a `skaffold.yaml` file, you **MUST**
know if the user has manifests for the runtime they are deploying to.

1.  **If the user does not have runtime manifests**: Generate some basic ones
    based on the runtime.
    -   **If Cloud Run**: Generate a Cloud Run manifest. Use
        [basic-cloudrun-manifests.md](references/basic-cloudrun-manifests.md) as
        a reference.
    -   **If GKE**: Generate a Kubernetes `Deployment` and `Service` manifest.
        Use [basic-k8s-manifests.md](references/basic-k8s-manifests.md) as a
        reference.
2.  Create a `skaffold.yaml` file required to create a Cloud Deploy `Release`
    for the `DeliveryPipeline`.
    -   Use [configure-skaffold.md](references/configure-skaffold.md) as a
        reference when generating the `skaffold.yaml` file.
    -   **For multi-environment pipelines**: You must define a Skaffold profile
        for each Cloud Deploy target environment, named to match the target ID
        exactly. Do NOT use generic names like 'staging' or 'prod' for profile
        names unless they match the target IDs.

### Step 7: Setup IAM permissions

Use [iam-permissions.md](references/iam-permissions.md) as a reference to set up
the necessary IAM permissions based on the `DeliveryPipeline` defined.

## Workflow: Add Google Observability Alert Policy Analysis to a Pipeline

Cloud Deploy integrates with Google Cloud Observability to provide metrics
analysis when deploying an application. When the application is deployed, Cloud
Deploy will monitor alert policies defined in Google Cloud Observability for any
incidents that were triggered after the application was deployed.

This feature can be used alongside automation to enable automatic rollbacks if
the application deployment triggers alert policies.

This section covers how to update the user's `DeliveryPipeline` to leverage this
feature.

### Constraints & Rules

A `DeliveryPipeline` MUST already be defined or being designed in the current
context.

### Step 0: Prerequisites

Cloud Deploy **requires** the Google Cloud Observability alerting policies to be
defined before they can be referenced in the `DeliveryPipeline`.

1.  Prompt the user whether they have existing alerting policies defined for the
    application. **DO NOT** assume that existing alerting policies are
    applicable to the application being deployed.
2.  If the user does not have alerting policies defined for the application,
    help the user generate them.
    -   **If Cloud Run**: Use
        [basic-cloudrun-alerts.md](references/basic-cloudrun-alerts.md) as a
        reference.

### Step 1: Update the pipeline definition

1.  Identify the duration for which the metrics analysis should run after the
    application is deployed (e.g., 30 minutes).
2.  Identify which alerting policies Cloud Deploy should monitor for incidents.
3.  Update the `DeliveryPipeline` definition in the `clouddeploy.yaml` file to
    include analysis configuration.
    -   Use [configure-pipelines.md](references/configure-pipelines.md) as a
        reference when updating the `DeliveryPipeline` definition.

### Step 2: Validate the clouddeploy.yaml file

Ensure that the `clouddeploy.yaml` file is valid. See
https://docs.cloud.google.com/deploy/docs/config-files.md.txt for the schema.

### Step 3: Apply the pipeline changes

Run the following command to update the Cloud Deploy `DeliveryPipeline`:

```bash
gcloud deploy apply --file=clouddeploy.yaml --region=<REGION> --project=<PROJECT_ID>
```

### Step 4: Setup IAM permissions

Use [iam-permissions.md](references/iam-permissions.md) as a reference to set up
the necessary IAM permissions for analysis.

## Release Management

This section covers the various aspects of managing Cloud Deploy `Release`
resources.

### Constraints & Rules

In order to manage releases, a `DeliveryPipeline` MUST already be defined and
configured in Cloud Deploy. Determine whether a delivery pipeline is defined by
checking for a `clouddeploy.yaml` file and checking if the resources exist in
Cloud Deploy or ask the user directly.

**Required Context**:

-   **Project ID**: The Google Cloud project ID of the `DeliveryPipeline`.
-   **Region**: The region of the `DeliveryPipeline` (e.g., `us-central1`).
-   **Delivery Pipeline ID**: The `DeliveryPipeline` ID.

### Create a release

**Use case**: The user wants to deploy a new version of their application.

**Required Context**: Before creating a `Release`, you **MUST** know whether the
users runtime manifests are using a placeholder for the container image and the
value of the placeholder. This is **CRITICAL** for build artifact substitution
in Cloud Deploy. Check the users runtime manifests or ask the user directly. See
examples in
[basic-cloudrun-manifests.md](references/basic-cloudrun-manifests.md) and
[basic-k8s-manifests.md](references/basic-k8s-manifests.md).

Run the following command to create a `Release` for the `DeliveryPipeline`:

```bash
gcloud deploy releases create release-$DATE-$TIME --delivery-pipeline=<DELIVERY_PIPELINE_ID> --region=<REGION> --project=<PROJECT_ID>
```

If the user is leveraging build artifact substitution with a placeholder in the
image field of the runtime manifests then use the `--images` flag:

```bash
gcloud deploy releases create release-$DATE-$TIME --delivery-pipeline=<DELIVERY_PIPELINE_ID> --region=<REGION> --project=<PROJECT_ID> --images <IMAGE_PLACEHOLDER>=<IMAGE_URI>
```

**CRITICAL**: If the `skaffold.yaml` is not in the current directory, use the
`--source` flag to specify the directory where the `skaffold.yaml` file is
located.

Reference documentation for `gcloud deploy releases create`:
https://docs.cloud.google.com/sdk/gcloud/reference/deploy/releases/create.md.txt.

### Promote a release

**Use case**: The user wants to promote the application to the next target
environment in the `DeliveryPipeline` progression sequence.

Run the following command to promote a `Release` to the next target in the
`DeliveryPipeline` progression sequence:

```bash
gcloud deploy promote --release=<RELEASE_ID> --delivery-pipeline=<DELIVERY_PIPELINE_ID> --region=<REGION> --project=<PROJECT_ID>
```

**TIP**: Use a short <RELEASE_ID> since the command will auto-generate a
`Rollout` ID (with a 63 character limit) in the format:
`<RELEASE_ID>-to-<TARGET_ID>`.

Reference documentation for `gcloud deploy releases promote`:
https://docs.cloud.google.com/sdk/gcloud/reference/deploy/releases/promote.md.txt.

### Monitor a release

**Use case**: Monitor the status of a release across a `DeliveryPipeline`.

Monitoring a release across a `DeliveryPipeline` consists of checking the status
of both the `Release` resource and its child `Rollout` resource(s). Always
ensure that the `Release` has completed successfully before checking the status
of the `Rollout`.

### Troubleshoot

#### Release failed

Get the release to determine which of the target renders failed and inspect the
failure message and failure cause. Additionally the target renders contain a
Cloud Build reference where the target render was executed. Retrieve the build
logs to determine the root cause of the failure.

#### Rollout failed

Get the rollout to determine which of the jobs failed and inspect the failure
message and failure cause. Additionally the `Rollout` contains a Cloud Build
reference where the failed job was executed. Retrieve the build logs to
determine the root cause of the failure.

*   **Binary Authorization (`BinAuthz`) Failure Interpretation on Promotion to
    Production**: If a rollout or promotion to `prod` fails because Binary
    Authorization blocked the image (e.g., Cloud Run
    `BinaryAuthorizationCheckFailed` or GKE
    `imagepolicywebhook.image-policy.k8s.io` admission denial), automatically
    inspect and interpret the Binary Authorization evaluation results for the
    user:

    1.  Check Cloud Audit Logs for the exact BinAuthz denial reason:

        ```bash
        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.  Inspect the active Binary Authorization policy and platform policies
        (`gcloud container binauthz policy export --project=<PROJECT_ID>` and
        `gcloud beta container binauthz policy list --platform=<cloudRun|gke>
        --project=<PROJECT_ID>`), and if a platform policy is used, evaluate it
        against the image digest (`gcloud beta container binauthz policy
        evaluate <POLICY_ID> --platform=<cloudRun|gke> --project=<PROJECT_ID>
        --image=<DIGEST_URI>`).
    3.  Cross-check existing attestations (`gcloud container binauthz
        attestations list --artifact-url="https://<DIGEST_URI>"
        --project=<PROJECT_ID>`) and Artifact Analysis provenance/vulnerability
        findings (`gcloud artifacts docker images describe <DIGEST_URI>
        --show-provenance --show-package-vulnerability --project=<PROJECT_ID>`).
    4.  Clearly explain which policy rule, missing attestation
        (`<ATTESTOR_NAME>`), provenance check, or CVE severity threshold blocked
        the promotion and provide actionable remediation steps.

## Resource Cleanup & Teardown

Cloud Deploy pipelines, staging Cloud Storage buckets, Cloud Build executions,
and target Cloud Run / GKE 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:

*   **Delivery Pipeline & Targets**: `gcloud deploy delete
    --file=clouddeploy.yaml --force --region=<REGION> --project=<PROJECT_ID>`
    (or `gcloud deploy delivery-pipelines delete <DELIVERY_PIPELINE_ID> --force
    --region=<REGION> --project=<PROJECT_ID>`)
*   **Alerting Policies**: `gcloud alpha monitoring policies delete <POLICY_ID>
    --project=<PROJECT_ID>`
references/
attribution.md 1.9 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand, with the metrics environment variable. Set it inline on each
    command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:google-cicd-release-orchestration)" \
    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-release-orchestration)` 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-release-orchestration)
    ```

-   **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.
basic-cloudrun-alerts.md 3.4 KB
# Basic Alerting Policies for Cloud Run

This document provides examples for generating Google Cloud Observability
Alerting Policies for Cloud Run.

The examples in this file use placeholders between `<` and `>`, e.g.
`<SERVICE_NAME>`. Replace these placeholders with the actual values when
generating the JSON.

The Alert Policy Schema is defined at
https://docs.cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.alertPolicies.

## Table of Contents

*   [Cloud Run Service](#cloud-run-service) (Lines 19-107)
    *   [High Error Rate](#high-error-rate) (Lines 21-68)
    *   [Latency](#latency) (Lines 70-107)

## Cloud Run Service

### High Error Rate

This alerting policy monitors the percentage of 5xx server errors relative to
total traffic for a specific Cloud Run service.

*   **Metric (Ratio)**:
    *   **Numerator**: `run.googleapis.com/request_count` filtered for `5xx`
        response codes.
    *   **Denominator**: `run.googleapis.com/request_count` (total requests).
*   **Aggregation**: Uses `ALIGN_RATE` over a 1-minute period (`60s`) for both
    numerator and denominator.
*   **Threshold**: Triggered if the ratio (5xx errors / total requests) exceeds
    **0.05 (5%)** (`thresholdValue: 0.05`) for a duration of 5 minutes (`300s`).

```json
{
  "displayName": "<SERVICE_NAME> 5xx Error Rate > 5%",
  "conditions": [
    {
      "displayName": "5xx Error Ratio > 5%",
      "conditionThreshold": {
        "filter": "resource.type = \"cloud_run_revision\" AND resource.labels.service_name = \"<SERVICE_NAME>\" AND metric.type = \"run.googleapis.com/request_count\" AND metric.labels.response_code_class = \"5xx\"",
        "denominatorFilter": "resource.type = \"cloud_run_revision\" AND resource.labels.service_name = \"<SERVICE_NAME>\" AND metric.type = \"run.googleapis.com/request_count\"",
        "aggregations": [
          {
            "alignmentPeriod": "60s",
            "perSeriesAligner": "ALIGN_RATE"
          }
        ],
        "denominatorAggregations": [
          {
            "alignmentPeriod": "60s",
            "perSeriesAligner": "ALIGN_RATE"
          }
        ],
        "comparison": "COMPARISON_GT",
        "duration": "300s",
        "trigger": {
          "count": 1
        },
        "thresholdValue": 0.05
      }
    }
  ],
  "combiner": "OR",
  "enabled": true
}
```

### Latency

This alerting policy monitors the 95th percentile (p95) of request latencies for
a specific Cloud Run service.

*   **Metric**: `run.googleapis.com/request_latencies` (Distribution metric)
*   **Aggregation**: Uses `ALIGN_PERCENTILE_95` over a 1-minute period (`60s`)
    to calculate the p95 latency.
*   **Threshold**: Triggered if the p95 latency exceeds **1 second (1000 ms)**
    (`thresholdValue: 1000`) for a duration of 10 minutes.

```json
{
  "displayName": "<SERVICE_NAME> p95 Latency > 1s",
  "conditions": [
    {
      "displayName": "p95 Latency > 1s",
      "conditionThreshold": {
        "filter": "resource.type = \"cloud_run_revision\" AND resource.labels.service_name = \"<SERVICE_NAME>\" AND metric.type = \"run.googleapis.com/request_latencies\"",
        "aggregations": [
          {
            "alignmentPeriod": "60s",
            "perSeriesAligner": "ALIGN_PERCENTILE_95"
          }
        ],
        "comparison": "COMPARISON_GT",
        "duration": "600s",
        "trigger": {
          "count": 1
        },
        "thresholdValue": 1000
      }
    }
  ],
  "combiner": "OR",
  "enabled": true
}
```
basic-cloudrun-manifests.md 2.2 KB
# Basic Cloud Run manifests

This document provides examples for generating Cloud Run resource manifests that
are used with Cloud Deploy to deploy to Cloud Run. The Cloud Run YAML reference
is available at: https://docs.cloud.google.com/run/docs/reference/yaml/v1.

The examples in this file use placeholders between `<` and `>`, e.g.
`<SERVICE_NAME>`. Replace these placeholders with the actual values when
generating the YAML.

Cloud Deploy performs build artifact substitutions on the image field so a
placeholder like `app-image` is used. When a Cloud Deploy `Release` is created
the user supplies the actual image and associates it with the `app-image` key.

## Cloud Run Service (Standard / Dev)

```yaml
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: <SERVICE_NAME>
spec:
  template:
    spec:
      containers:
      - image: app-image
        ports:
        - containerPort: 8080
```

## Cloud Run Service (Production with Binary Authorization)

When deploying to a production Cloud Run target (`prod`) with Binary
Authorization enabled (`"binary_authorization": "default"` in
`deployment-config.json`), include the `run.googleapis.com/binary-authorization`
annotation:

```yaml
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: <SERVICE_NAME>
  annotations:
    run.googleapis.com/binary-authorization: default
spec:
  template:
    spec:
      containers:
      - image: app-image
        ports:
        - containerPort: 8080
```

## Cloud Run Service (AI Agent or MCP Server with Agent Registry Auto-Registration)

When deploying an **AI Agent** (`functional-type: agent`) or **MCP Server**
(`functional-type: mcp-server`), include the Agent Registry auto-registration
labels in `metadata.labels`:

```yaml
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: <SERVICE_NAME>
  labels:
    functional-type: agent # Or mcp-server
    agent-registry-auto-register: "true"
spec:
  template:
    spec:
      containers:
      - image: app-image
        ports:
        - containerPort: 8080
```

## Cloud Run Worker Pool

```yaml
apiVersion: run.googleapis.com/v1
kind: WorkerPool
metadata:
  name: <WORKER_POOL_NAME>
spec:
  template:
    spec:
      containers:
      - image: app-image
```
basic-k8s-manifests.md 2.2 KB
# Basic Kubernetes manifests

This document provides examples for generating Kubernetes `Deployment` and
`Service` resource manifests that are used with Cloud Deploy to deploy to GKE.

The examples in this file use placeholders between `<` and `>`, e.g.
`<DEPLOYMENT_NAME>`. Replace these placeholders with the actual values when
generating the YAML.

Cloud Deploy performs build artifact substitutions on the image field so a
placeholder like `app-image` is used. When a Cloud Deploy `Release` is created
the user supplies the actual image and associates it with the `app-image` key.

## Kubernetes Deployment (Standard Web Service)

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: <DEPLOYMENT_NAME>
  labels:
    app: <APPLICATION_NAME>
spec:
  replicas: 1
  selector:
    matchLabels:
      app: <APPLICATION_NAME>
  template:
    metadata:
      labels:
        app: <APPLICATION_NAME>
    spec:
      containers:
      - name: <APPLICATION_NAME>
        image: app-image
        ports:
        - containerPort: 8080
```

## Kubernetes Deployment (AI Agent or MCP Server with Agent Registry Discovery)

When deploying an **AI Agent** (`"AGENT"`) or **MCP Server** (`"MCP_SERVER"`) to
GKE, include the Agent Registry functional-type label, App Hub annotation, and
SPIFFE identity annotation:

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: <DEPLOYMENT_NAME>
  labels:
    app: <APPLICATION_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: <APPLICATION_NAME>
  template:
    metadata:
      labels:
        app: <APPLICATION_NAME>
      annotations:
        iam.gke.io/spiffe-identity-type: "agent-identity"
    spec:
      containers:
      - name: <APPLICATION_NAME>
        image: app-image
        ports:
        - containerPort: 8080
```

## Kubernetes Service

```yaml
apiVersion: v1
kind: Service
metadata:
  name: <SERVICE_NAME>
  labels:
    app: <APPLICATION_NAME>
spec:
  selector:
    app: <APPLICATION_NAME>
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080
  type: LoadBalancer
```
configure-automations.md 5.0 KB
# Configure Automations

This document provides examples for configuring Cloud Deploy `Automation`
resources. The examples are in YAML format and are intended to be used with the
`gcloud deploy apply` command to create or update the resource. Use these
examples if it fits the users requirements.

The examples in this file use placeholders between `<` and `>`, e.g.
`<AUTOMATION_ID>`. Replace these placeholders with the actual values when
generating the YAML.

**CRITICAL**:

-   The `metadata.name` field for an `Automation` resource is made up of the
    `DeliveryPipeline` ID and the `Automation` ID, separated by a forward slash.
    For example, if the `DeliveryPipeline` ID is "hello-world" and the
    `Automation` ID is "promote" then the `metadata.name` field should be
    "hello-world/promote".
-   Automations **require** a dedicated least-privilege service account with
    `roles/clouddeploy.operator` (never use the default Compute Engine SA):

```
clouddeploy-automation@<PROJECT_ID>.iam.gserviceaccount.com
```

## Table of Contents

-   [Automatic Rollbacks](#automatic-rollbacks) (Lines 37-83)
-   [Automatic Rollbacks with Retry](#automatic-rollbacks-with-retry) (Lines
    85-108)
-   [Automatic Promotions on a Schedule](#automatic-promotions-on-a-schedule)
    (Lines 110-131)
-   [Automatic Promotion after a Delay](#automatic-promotion-after-a-delay)
    (Lines 133-153)
-   [Automatic Canary Advance](#automatic-canary-advance) (Lines 155-174)

## Automatic Rollbacks

This `Automation` will rollback for any `Target` in the `DeliveryPipeline`
progression sequence if any job in the `Rollout` fails.

The `*` in the `selector.targets.id` field means that this `Automation` will
apply to all `Target` resources in the `DeliveryPipeline`.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: Automation
metadata:
  name: <PIPELINE_ID>/<AUTOMATION_ID>
serviceAccount: clouddeploy-automation@<PROJECT_ID>.iam.gserviceaccount.com
selector:
  targets:
  - id: "*"
rules:
- repairRolloutRule:
    id: "repair-rule"
    repairPhases:
    - rollback: {}
```

Automatic rollbacks can be triggered for a subset of `Rollout` jobs. For
example, if the user wants to rollback only if the `deploy` or `analysis` job
fail, the `Automation` would be defined as follows:

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: Automation
metadata:
  name: <PIPELINE_ID>/<AUTOMATION_ID>
serviceAccount: clouddeploy-automation@<PROJECT_ID>.iam.gserviceaccount.com
selector:
  targets:
  - id: "*"
rules:
- repairRolloutRule:
    id: "repair-rule"
    jobs: ["deploy", "analysis"]
    repairPhases:
    - rollback: {}
```

The possible values include: `predeploy`, `deploy`, `postdeploy`, `verify`, and
`analysis`.

## Automatic Rollbacks with Retry

This `Automation` will attempt to retry the failed `Rollout` job up to 3 times
with a 1 minute wait between attempts. If the `Rollout` still fails after the
retries then it will be rolled back.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: Automation
metadata:
  name: <PIPELINE_ID>/<AUTOMATION_ID>
serviceAccount: clouddeploy-automation@<PROJECT_ID>.iam.gserviceaccount.com
selector:
  targets:
  - id: "*"
rules:
- repairRolloutRule:
    id: "repair-rule"
    repairPhases:
    - retry:
        attempts: 3
        wait: 1m
    - rollback: {}
```

## Automatic Promotions on a Schedule

This `Automation` will automatically promote a release to the next `Target` in
the `DeliveryPipeline` progression sequence every Monday at 12:00 PM New York
time.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: Automation
metadata:
  name: <PIPELINE_ID>/<AUTOMATION_ID>
serviceAccount: clouddeploy-automation@<PROJECT_ID>.iam.gserviceaccount.com
selector:
  targets:
  - id: <FROM_TARGET_ID>
rules:
- timedPromoteReleaseRule:
    id: "timed-promote-rule"
    schedule: "0 12 * * 1" # Cron format.
    timeZone: "America/New_York" # IANA format.
    destinationTargetId: "@next" # promote to the next `Target` in the `DeliveryPipeline` progression sequence.
```

## Automatic Promotion after a Delay

This `Automation` will automatically promote a release to the next `Target` in
the `DeliveryPipeline` after 3 hours has passed since the release was rolled out
to the previous `Target`.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: Automation
metadata:
  name: <PIPELINE_ID>/<AUTOMATION_ID>
serviceAccount: clouddeploy-automation@<PROJECT_ID>.iam.gserviceaccount.com
selector:
  targets:
  - id: <FROM_TARGET_ID>
rules:
- promoteReleaseRule:
    id: "promote-rule"
    wait: 3h
    destinationTargetId: "@next" # promote to the next `Target` in the `DeliveryPipeline` progression sequence.
```

## Automatic Canary Advance

This `Automation` will automatically advance through each phase of a canary
`Rollout` for a specific `Target` after 1 hour has passed since the previous
phase completed.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: Automation
metadata:
  name: <PIPELINE_ID>/<AUTOMATION_ID>
serviceAccount: clouddeploy-automation@<PROJECT_ID>.iam.gserviceaccount.com
selector:
  targets:
  - id: <TARGET_ID>
rules:
- advanceRolloutRule:
    id: "advance-rule"
    wait: 1h
```
configure-pipelines.md 5.7 KB
# Configure Delivery Pipelines

This document provides examples for configuring Cloud Deploy `DeliveryPipeline`
resources. The examples are in YAML format and are intended to be used with the
`gcloud deploy apply` command to create or update the resource. Use these
examples if it fits the users requirements.

The examples in this file use placeholders between `<` and `>`, e.g.
`<PIPELINE_ID>`. Replace these placeholders with the actual values when
generating the YAML.

## Table of Contents

-   [Pipeline with a single target](#pipeline-with-a-single-target) (Lines
    23-37)
-   [Pipeline with multiple targets](#pipeline-with-multiple-targets) (Lines
    39-56)
-   [Pipeline with the canary deployment strategy](#pipeline-with-the-canary-deployment-strategy)
    (Lines 58-115)
-   [Pipeline with Google Observability metrics analysis (Cloud Run)](#pipeline-with-google-observability-metrics-analysis-cloud-run)
    (Lines 117-189)

## Pipeline with a single target

This is the minimal `DeliveryPipeline` that can be defined. It only contains a
single target.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: DeliveryPipeline
metadata:
 name: <PIPELINE_ID>
serialPipeline:
 stages:
 - targetId: <TARGET_ID>
   profiles: [<TARGET_ID>]
```

## Pipeline with multiple targets

This `DeliveryPipeline` contains multiple targets in the progression sequence.
Cloud Deploy will deploy to the targets in the order they are listed in the
`stages` field.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: DeliveryPipeline
metadata:
 name: <PIPELINE_ID>
serialPipeline:
 stages:
 - targetId: <TARGET_ID1> # e.g. "Dev" target.
   profiles: [<TARGET_ID1>]
 - targetId: <TARGET_ID2> # e.g. "Production" target.
   profiles: [<TARGET_ID2>]
```

## Pipeline with the canary deployment strategy

The `percentages` field is a list of percentages to use for the canary
deployment strategy. For example, deploy 10% of traffic to the canary, then 50%,
before the stable phase. The `percentages` field **cannot** contain 100 since
that is assumed by the stable phase.

### Cloud Run

For Cloud Deploy to automatically handle canarying for Cloud Run the
`canary.runtimeConfig.cloudRun.automaticTrafficControl` field **must** be set to
`true`.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: DeliveryPipeline
metadata:
 name: <PIPELINE_ID>
serialPipeline:
  stages:
  - targetId: <TARGET_ID>
    profiles: [<TARGET_ID>]
    strategy:
      canary:
        runtimeConfig:
          cloudRun:
            automaticTrafficControl: true
        canaryDeployment:
          percentages: [10, 50]
```

### GKE

Cloud Deploy requires the Kubernetes `Deployment` and `Service` names to
automatically handle canarying for GKE. Check the local workspace for Kubernetes
manifests to determine the `Deployment` and `Service` names, or ask the user to
provide them. If the former, confirm with the user that the right `Deployment`
and `Service` were determined.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: DeliveryPipeline
metadata:
 name: <PIPELINE_ID>
serialPipeline:
  stages:
  - targetId: <TARGET_ID>
    profiles: [<TARGET_ID>]
    strategy:
      canary:
        runtimeConfig:
          kubernetes:
            serviceNetworking:
              service: <SERVICE_NAME>
              deployment: <DEPLOYMENT_NAME>
        canaryDeployment:
          percentages: [10, 50]
```

## Pipeline with Google Observability metrics analysis (Cloud Run)

The examples in this section leverage `labels` to filter the incidents for the
alert policies to only take into account the Cloud Run `Service` and `Revision`
that is being deployed. The `duration` is set to 30 minutes (`1800s`) to give
the alerting policies time to evaluate the metrics and potentially trigger
incidents.

### Standard deployment strategy with analysis

This `DeliveryPipeline` is configured to monitor a single Google Cloud
Observability alert policy for any incidents over a 30 minute (`1800s`) period
after the application has been deployed.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: DeliveryPipeline
metadata:
 name: <PIPELINE_ID>
serialPipeline:
  stages:
  - targetId: <TARGET_ID>
    profiles: [<TARGET_ID>]
    strategy:
      standard:
        analysis:
          duration: 1800s
          googleCloud:
            alertPolicyChecks:
            - id: alert-check-1
              alertPolicies:
              - projects/<PROJECT_ID>/alertPolicies/<ALERT_POLICY_ID>
              labels:
                service_name: '${{ render.metadata.cloud_run.service.id }}'
                revision_name: '${{ render.metadata.cloud_run.revision.id }}'
```

### Canary deployment strategy with analysis

This `DeliveryPipeline` is configured to monitor a single Google Cloud
Observability alert policy for any incidents over a 30 minute (`1800s`) period
after deploying in each phase of the `Rollout`. In this case Cloud Deploy will
monitor the alert policy after deploying 50% of the traffic to the new version
and after deploying 100% of the traffic to the new version during the stable
phase.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: DeliveryPipeline
metadata:
 name: <PIPELINE_ID>
serialPipeline:
  stages:
  - targetId: <TARGET_ID>
    profiles: [<TARGET_ID>]
    strategy:
      canary:
        runtimeConfig:
          cloudRun:
            automaticTrafficControl: true
        canaryDeployment:
          percentages: [50]
          analysis:
            duration: 1800s
            googleCloud:
              alertPolicyChecks:
              - id: alert-check-1
                alertPolicies:
                - projects/<PROJECT_ID>/alertPolicies/<ALERT_POLICY_ID>
                labels:
                  service_name: '${{ render.metadata.cloud_run.service.id }}'
                  revision_name: '${{ render.metadata.cloud_run.revision.id }}'
```
configure-skaffold.md 3.0 KB
# Configure Skaffold YAML

This document provides examples for configuring a `skaffold.yaml` file used when
creating a Cloud Deploy `Release` for a `DeliveryPipeline`.

**TIP**: Try not to deviate from these examples since most Skaffold
configuration is **not applicable** to Cloud Deploy. For example, the top-level
`build` stanza in a `skaffold.yaml` does nothing with Cloud Deploy.

## Table of Contents

-   [Deploy to Cloud Run](#deploy-to-cloud-run) (Lines 15-59)
-   [Deploy to GKE](#deploy-to-gke) (Lines 61-136)

## Deploy to Cloud Run

**CRITICAL** when deploying to Cloud Run:

-   **MUST** include the `cloudrun` deployer.
-   **ALWAYS** use `rawYaml` under `manifests` unless the user specifies
    otherwise.

Minimal `skaffold.yaml` file for deploying to Cloud Run. Requires a reference to
the Cloud Run manifest file that contains the Cloud Run resource.

```yaml
apiVersion: skaffold/v4beta13
kind: Config
deploy:
  cloudrun: {}
profiles:
- name: <TARGET_ID>
  manifests:
    rawYaml:
    - <MANIFEST_FILE_NAME>
```

### With different files per target

Uses different Cloud Run manifests for each `Target` in the `DeliveryPipeline`.
Since the Cloud Run resource name is defined within the manifest files, this is
generally the expected configuration when deploying to Cloud Run to multiple
`Target`s.

```yaml
apiVersion: skaffold/v4beta13
kind: Config
deploy:
  cloudrun: {}
profiles:
- name: <TARGET_ID_1>
  manifests:
    rawYaml:
    - <MANIFEST_FILE_NAME_1>
- name: <TARGET_ID_2>
  manifests:
    rawYaml:
    - <MANIFEST_FILE_NAME_2>
```

## Deploy to GKE

Minimal `skaffold.yaml` file for deploying to GKE. Requires a reference to the
Kubernetes manifests file that contains resources such as a `Deployment` and
`Service`.

```yaml
apiVersion: skaffold/v4beta13
kind: Config
deploy:
  kubectl: {}
profiles:
- name: <TARGET_ID>
  manifests:
    rawYaml:
    - <MANIFEST_FILE_NAME>
```

### With different files per target

Uses different Kubernetes manifests for each `Target` in the `DeliveryPipeline`.
This is useful when the Kubernetes resource configurations are not identical
across environments.

```yaml
apiVersion: skaffold/v4beta13
kind: Config
deploy:
  kubectl: {}
profiles:
- name: <TARGET_ID_1>
  manifests:
    rawYaml:
    - <MANIFEST_FILE_NAME_1>
- name: <TARGET_ID_2>
  manifests:
    rawYaml:
    - <MANIFEST_FILE_NAME_2>
```

### Helm chart

Minimal `skaffold.yaml` file for deploying to GKE when the Kubernetes resources
are defined in a Helm chart.

```yaml
apiVersion: skaffold/v4beta13
kind: Config
deploy:
  kubectl: {}
profiles:
- name: <TARGET_ID>
  manifests:
    helm:
      releases:
      - name: <APPLICATION_NAME>
        chartPath: <PATH_TO_HELM_CHART>
```

### Kustomize

Minimal `skaffold.yaml` file for deploying to GKE when the Kubernetes resources
are defined in Kustomization file.

```yaml
apiVersion: skaffold/v4beta13
kind: Config
deploy:
  kubectl: {}
profiles:
- name: <TARGET_ID>
  manifests:
    kustomize:
      paths:
      - <PATH_TO_KUSTOMIZE_DIR>
```
configure-targets.md 1.5 KB
# Configure Targets

This document provides examples for configuring Cloud Deploy `Target` resources.
The examples are in YAML format and are intended to be used with the
`gcloud deploy apply` command to create or update the resource. Use these
examples if it fits the users requirements.

The examples in this file use placeholders between `<` and `>`, e.g.
`<TARGET_ID>`. Replace these placeholders with the actual values when generating
the YAML.

## Cloud Run target

### Minimal Cloud Run target

Minimal Cloud Run `Target` only requires specifying the project and location of
the Cloud Run Service.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: Target
metadata:
  name: <TARGET_ID>
run:
  location: projects/<CLOUD_RUN_PROJECT_ID>/locations/<CLOUD_RUN_LOCATION>
```

### Require approval

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: Target
metadata:
  name: <TARGET_ID>
run:
  location: projects/<CLOUD_RUN_PROJECT_ID>/locations/<CLOUD_RUN_LOCATION>
requireApproval: true
```

## Google Kubernetes Engine (GKE) target

### Minimal GKE target

Minimal GKE `Target` only requires specifying the name of the GKE cluster.

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: Target
metadata:
  name: <TARGET_ID>
gke:
  cluster: projects/<CLUSTER_PROJECT_ID>/locations/<CLUSTER_LOCATION>/clusters/<CLUSTER_ID>
```

### Require approval

```yaml
apiVersion: deploy.cloud.google.com/v1
kind: Target
metadata:
  name: <TARGET_ID>
gke:
  cluster: projects/<CLUSTER_PROJECT_ID>/locations/<CLUSTER_LOCATION>/clusters/<CLUSTER_ID>
requireApproval: true
```
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-release-orchestration)"
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.
iam-permissions.md 3.0 KB
# IAM Permissions

This document provides insights into the IAM permissions required for Cloud
Deploy to operate based on the features enabled for the `DeliveryPipeline`.

## Execution Service Account

**MUST KNOW**: Provision and use a dedicated, user-managed execution service
account defined in the `Target` (or in `deployment-config.json`). **Never** use
the default Compute Engine service account
(`[PROJECT_NUMBER]-compute@developer.gserviceaccount.com`), which carries overly
broad privileges.

The execution service account **must always** have the following roles:

*   `roles/clouddeploy.jobRunner` (project level)
*   `roles/iam.serviceAccountUser` (scoped strictly on the target Cloud Run or
    GKE runtime service account, never project-wide)

### Runtime Permissions

If deploying to Cloud Run then `roles/run.developer` is **required**.

If deploying to GKE then `roles/container.developer` is **required**.

### Supply Chain Security & Binary Authorization Permissions (`prod` Targets)

If the target enforces Binary Authorization (`--binary-authorization=default` or
`run.googleapis.com/binary-authorization: default`) or verifies
attestations/SBOMs:

*   `roles/binaryauthorization.attestorsVerifier` (to verify attestor signatures
    against the policy)
*   `roles/containeranalysis.notes.occurrences.viewer` (to inspect vulnerability
    scans, SPDX SBOMs, and attestation occurrences)
*   `roles/artifactregistry.reader` (to pull images and inspect image digests)

### Agent Registry Permissions (AI Agents & MCP Servers)

If the workload registers or verifies AI Agents or MCP Servers in Google Cloud
Agent Registry (`agentregistry.googleapis.com`):

*   `roles/agentregistry.viewer` (to list and verify registered agents and MCP
    servers)
*   `roles/agentregistry.admin` (if explicitly managing Agent Registry entries
    or services)

### Analysis Permissions (Google Cloud Observability)

The following roles are **required**:

*   `roles/monitoring.alertViewer`
*   `roles/serviceusage.serviceUsageConsumer`

## Automation Service Account

**MUST KNOW**: The service account defined in the `Automation` resources.

The `Automation` service account **requires** the `roles/clouddeploy.operator`
role.

## Release Creator

The user or service account that creates a `Release` and `Rollout` **must**
have:

*   `roles/clouddeploy.releaser` (project or delivery-pipeline level)
*   `roles/iam.serviceAccountUser` scoped strictly on the Cloud Deploy execution
    service account (`gcloud iam service-accounts add-iam-policy-binding`)
*   `roles/storage.objectUser` scoped strictly on the Cloud Deploy staging
    bucket (`gs://<STAGING_BUCKET>`, never project-wide `roles/storage.admin`)

**TIP**: If the `Release` and `Rollout` is created by a Cloud Build trigger with
a custom service account (`cloud_build_trigger.service_account`), assign these
roles (plus `roles/logging.logWriter` with
`options: { logging: CLOUD_LOGGING_ONLY }`) to the custom Cloud Build service
account. See
https://docs.cloud.google.com/build/docs/cloud-build-service-account.md.txt for
more information.
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