Installation

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

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

Install with the gh extension
gh skills-hub install agent-platform-deploy

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

Download and extract to your repository:

.github/skills/agent-platform-deploy/

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

Skill Files (9)

SKILL.md 20.6 KB
---
name: agent-platform-deploy
metadata:
  version: "1.0.6"
  category: AiAndMachineLearning
description: >-
  Deploy open models or custom weights from Model Garden to Agent Platform
  endpoints, check the status of an in-progress deployment operation, or clean
  up resources by undeploying models and deleting endpoints. Use when asked to
  actively deploy a model, list the Model Garden CATALOG of available models,
  check if a specific model is deployable
  (`gcloud ai model-garden models list-deployment-config`), query deployment
  cost, troubleshoot deployment errors (like quota limits), or undeploy/clean
  up endpoints. Also use when copying and deploying a 1P Tuned Model. Don't
  use for pure listing/discovery questions of the form "is X deployed?",
  "list my endpoints", or "which regions have models running?" — for those
  use `agent-platform-endpoint-management`. Don't use for running model evaluations
  (use `agent-platform-eval-flywheel` skill).
---

# Agent Platform Model Garden Deploy Skill

This skill provides instructions for deploying Open Models from Agent Platform
Model Garden to endpoints, and subsequently undeploying them to clean up
resources.

## Attribution

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

```text
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:agent-platform-deploy)"
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:agent-platform-deploy)
```

## 1P Tuned Model Copy & Deployment

If you need to copy a **1P (First-Party) Tuned Model** from a source project to
a destination region or project and deploy it to a newly created endpoint, refer
to the
[1P Tuned Model Copy & Deployment Guide](references/copy_deploy_guide.md).

## Safety & Confirmation Tiers (CRITICAL)

Before executing any commands on behalf of the user, you MUST adhere to the
following safety tiers based on the action requested:

1.  **Tier R: Read-only (`list`, `describe`, `list-deployment-config`)**
    *   **Rule**: No confirmation needed. You may execute these commands
        immediately to gather information for the user.
2.  **Tier M: Mutating & Reversible (`deploy`, `undeploy-model`)**
    *   **Rule**: This requires explicit user confirmation. You MUST present a
        clear dry-run confirmation card containing:

        1.  Exact proposed `gcloud` command code block (`gcloud ai model-garden
            models deploy ... --asynchronous`).
        2.  Model identifier, destination project ID, and target region.
        3.  Machine type and accelerator configuration.
        4.  Estimated hourly cost ($/hr).
        5.  Endpoint display name.
        6.  Explicit confirmation prompt asking the user to approve before
            execution.
        You MUST wait for their explicit confirmation before executing. For
        `undeploy-model`, you MUST first verify that the endpoint and deployed
        model exist; if `describe` or `list` returns a 404 or empty result, you
        MUST halt and inform the user rather than attempting undeployment.
    *   **Same-turn restriction**: Do not run the command in the same turn as
        presenting the confirmation prompt. End your turn after asking and wait
        for the user's reply; only execute after explicit approval. Printing a
        preview and then calling the tool before the user can answer does not
        count as obtaining confirmation.
3.  **Tier D: Destructive & Irreversible (`delete`)**
    *   **Rule**: This requires **explicit typed confirmation**. You MUST output
        a text message explaining the irreversible nature of endpoint or model
        deletion and asking the user to type "I confirm" or "Yes, delete it"
        before executing the deletion command.

> [!IMPORTANT]
>
> **Always Output Complete Text Response (NEVER Emit Empty Text)**: After
> executing any tool call (such as `gcloud ai model-garden models deploy`,
> `gcloud ai endpoints delete`, `gcloud ai endpoints list`, or status checks),
> you MUST formulate and return a complete, informative textual response to the
> user. Explicitly report the operation name, endpoint name/ID, error message,
> or list of resources. **NEVER finish a turn with empty text or silence**.

## 1. Prerequisites

Before deploying, ensure you have the correct project and region set. The
commands below use placeholder variables `PROJECT_ID` and `LOCATION_ID`.

Ensure you are authenticated:

```bash
gcloud auth login
gcloud auth application-default login
gcloud config set project $PROJECT_ID
```

## 2. Discovering Deployable Models

You can list models available in Model Garden and check if they can be
self-deployed.

```bash
gcloud ai model-garden models list
```

To see what machine types and accelerators are supported for a specific model,
pass a `MODEL_ID` you obtained from the `models list` output above. Substitute
`<PUBLISHER>/<FAMILY>@<VERSION-ID>` below with the exact string from the catalog
output — the placeholder is deliberately not a real model ID:

```bash
gcloud ai model-garden models list-deployment-config \
    --model="<PUBLISHER>/<FAMILY>@<VERSION-ID>"
```

> [!NOTE] Some models, especially Hugging Face models, might require a Hugging
> Face Access Token for deployment.

> [!TIP] **Model Recommendation Instructions:** Whenever you are about to name a
> specific model version in a response, do NOT recommend from memory. This
> applies in all of the following situations — not just direct deploy requests:
>
> *   The user asks to deploy a model without naming one.
> *   You are volunteering a next-step suggestion after a `list`, `describe`, or
>     `undeploy` operation (e.g. "Would you like me to deploy `<model>` to this
>     endpoint?").
> *   The user asks a general "what should I use?" / "what's a good model for
>     X?" question.
> *   You are filling in a `MODEL_ID` value in an example command you are
>     showing the user (as opposed to a placeholder like
>     `<PUBLISHER>/<FAMILY>@<VERSION-ID>`).
>
> New model versions ship frequently and older ones may be deprecated, so
> training-corpus knowledge of which models exist is unreliable. Follow this
> procedure:
>
> 1.  **Clarify the use case** if it isn't already clear from context (task
>     type, quality vs. latency vs. cost priorities, hardware/quota constraints,
>     license constraints). Skip if the user has already given enough signal.
> 2.  **Query the live catalog** with `gcloud ai model-garden models list`.
>     Narrow with `--filter` when appropriate (e.g. `--filter="name~gemma"`,
>     `--filter="name~llama"`, `--filter="name~qwen"`,
>     `--filter="name~deepseek"`). Never name a specific model version to the
>     user until you have seen it in the catalog output for this project.
> 3.  **Pick the latest generally-available version** in the family that fits
>     the use case. When multiple size variants exist, pick the one that matches
>     the user's hardware/cost tolerance. Prefer a newer major version over an
>     older one unless it is marked preview/experimental and the user explicitly
>     asked for a stable option.
> 4.  **Verify the exact model ID is deployable** with `gcloud ai model-garden
>     models list-deployment-config --model="<publisher>/<family>@<version>"`
>     before naming it in your response.
> 5.  **Cite the model ID verbatim** in your recommendation, exactly as it
>     appears in the catalog. Do not paraphrase to a family label ("Gemma",
>     "Llama").
>
> The `MODEL_ID` values in the §3 examples below are intentionally
> non-substantive placeholders (`<PUBLISHER>/<FAMILY>@<VERSION-ID>`). Do NOT
> replace them with a remembered model name for a user-facing recommendation —
> always re-run steps 2-4 first, then cite the exact string from the catalog.

## 2.1 Region Availability Check (Gemini + LoRA only)

> **Retired model guard**: Legacy `gemini-2.5-*` models (such as
> `gemini-2.5-flash`, `gemini-2.5-pro`, and `gemini-2.5-flash-lite`) are
> retired. Never probe or recommend them; inform the user that the requested
> `gemini-2.5-*` model is retired and suggest active supported models such as
> `gemini-3.8-flash` or `gemini-3.5-flash-lite`.
>
> For active first-party Gemini or LoRA deploys, you must verify region
> availability before proceeding. Load the full instructions with
> `load_skill_resource(skill_name='agent-platform-deploy',
> file_path='references/region_availability.md')`.
>
> **Skip this** for open-weights models (Gemma, Llama, DeepSeek, Qwen) and for
> Gemini-tuned models — they have no per-region publisher endpoint restriction.
> Go straight to §3.

## 3. Deploying a Model

> [!WARNING] Deploying models, especially large ones, consumes significant
> compute resources and incurs costs.
>
> 1.  You **MUST** compute an hourly $ estimate for the requested
>     `--machine-type` before proposing a deploy. Try each source below in
>     order, falling through to the next on any failure:
>
>     -   Run `scripts/calculate_cost.py`. The accelerator type and count are
>         fixed per machine type in Model Garden and derived automatically.
>         Example:
>
>         ```bash
>         python3 scripts/calculate_cost.py \
>             --machine-type=g2-standard-48
>         ```
>
>         If the script exits non-zero (unknown `--machine-type` — a routine
>         state for machines in the Model Garden catalog but not yet in the
>         price snapshot, e.g. A4/B200 today), fall through to the next source.
>         Do NOT invent a number.
>
>     -   Fall back to
>         [Agent Platform prediction pricing](https://cloud.google.com/products/gemini-enterprise-agent-platform/pricing?hl=en#prediction-and-explanation)
> if no source above produced a
>         number. Read the accelerator + hourly rate directly off that page and
>         cite the URL in the estimate you present to the user.
>
> 2.  You **MUST** present this cost estimation to the user and warn them that
>     this is the **list price**, which may differ from their actual bill due to
>     potential discounts, reservations, or non-`us-central1` regions.
> 3.  You **MUST ALWAYS** request explicit confirmation from the user agreeing
>     to the estimated cost before executing any `deploy` command.

To deploy a model, use the `deploy` command. It is highly recommended to use the
`--asynchronous` flag for long-running deployments, and then poll the status if
necessary.

> [!IMPORTANT]
>
> -   **Cost Pushback & Hardware Renegotiation**: If the user pushes back on
>     cost (e.g., "That is too expensive, can you try a smaller
>     configuration?"), or requests an invalid or unsupported hardware
>     combination (e.g. `g2-standard-48g` with 4x H100 GPUs), explain the
>     constraint or invalidity clearly, check `list-deployment-config` to
>     identify the supported alternative (e.g., `g2-standard-24` with 2x L4 or
>     `g2-standard-12` with 1x L4), compute its cost estimate with a single
>     query, and **immediately render a complete Tier M dry-run confirmation
>     card** for that recommended configuration in the same response.
> -   **Region Failover & Quota Exhaustion**: When a deployment fails due to
>     quota or capacity in the requested region (e.g. `QUOTA_EXCEEDED` or
>     `RESOURCE_EXHAUSTED`), identify an alternative supported region (e.g.
>     `us-east4` or `us-east1`), compute its cost estimate with a single query,
>     and **immediately render a complete Tier M dry-run confirmation card with
>     the new `--region` and exact command in the same response**. State the
>     alternative region directly without making unverified capacity claims.
> -   **Efficient Tool Execution (No Redundant Calls)**: Do NOT execute
>     redundant `models list`, `list-deployment-config`, or `--help` commands if
>     the model ID, region, or hardware configuration are already known or
>     resolved. Run each discovery command strictly once.
> -   **Single Status Check & Response Formatting (CRITICAL)**:
>     -   When initiating an asynchronous deployment (`gcloud ai model-garden
>         models deploy ... --asynchronous`), the command output immediately
>         returns the operation name. **Formulate and return your textual
>         confirmation response with the operation name and endpoint display
>         name immediately**. Do NOT call `operations describe` in the same turn
>         as deployment initiation.
>     -   When the user explicitly asks to check deployment status (e.g.,
>         "Please check to see the status of the deployment" or "Can you check
>         if the deployment has finished?"):
>         -   **NEVER run `sleep` commands, `while` loops, or repeated polling
>             calls**.
>         -   Execute `gcloud ai operations describe <OPERATION_NAME>`, the full
>             operation name the deploy command printed, **strictly ONCE**.
>         -   **ALWAYS output a full textual response** reporting the operation
>             status (e.g. "The deployment operation
>             `projects/.../operations/...` is currently in progress / running
>             (created at `...`). Asynchronous model deployment typically takes
>             10–15 minutes to complete").
>         -   Only proceed with sending a test prediction if the status check
>             confirms the endpoint is already serving and ready.
> -   **Alphanumeric Project ID**: Always specify the alphanumeric Project ID
>     (e.g. `my-gcp-project`) for `--project`, NOT the numeric project number
>     (e.g. `123456789012`). If given a numeric project number and its Project
>     ID is not available, pass the number inside a fully-qualified resource
>     name, e.g. `gcloud ai endpoints list
>     --region=projects/123456789012/locations/us-central1`, or as a positional
>     resource, `gcloud ai endpoints describe
>     projects/123456789012/locations/us-central1/endpoints/<ENDPOINT_ID>
>     --region=us-central1`. If `gcloud ai` still refuses because `core/project`
>     is set to a project number, ask the user for the Project ID rather than
>     retrying.
> -   **Valid User-Specified Hardware Priority**: When the user specifies an
>     explicit, valid hardware configuration (e.g. `g2-standard-96` with 8
>     `NVIDIA_L4` GPUs, or `g2-standard-12` with 1 `NVIDIA_L4` GPU), honor that
>     requested configuration for the dry-run preview and cost estimation rather
>     than overriding it with default recommendations. However, if the requested
>     configuration is **invalid or unsupported** (e.g. mismatched GPU count
>     such as `g2-standard-12` with 2 L4 GPUs, or non-existent machine shapes),
>     follow the **Cost Pushback & Hardware Renegotiation** rule above: explain
>     the invalidity clearly, identify the supported alternative (e.g.
>     `g2-standard-24` with 2 L4 GPUs), calculate its cost, and immediately
>     present the confirmation card for the valid alternative.
> -   **Endpoint Display Name**: If the user specifies or requests an endpoint
>     name or display name (e.g. `'usersim-gemma-eval-...'`), you MUST always
>     include `--endpoint-display-name="<NAME>"` in the `deploy` command.

### Example: Deploying an open-weights model from Model Garden

Here is a typical bash script to deploy a model. You can run this block
directly.

```bash
#!/bin/bash
# Example script to deploy an open-weights model from Model Garden.
#
# NOTE: MODEL_ID below is a PLACEHOLDER, not a real model ID. Substitute it
# with a value from a live `gcloud ai model-garden models list` (see §2)
# before running this script, and do NOT quote the placeholder back to the
# user as a recommended model.
#
# IMPORTANT FOR deploy_config["command"]: when building the curl command for
# the deploy confirmation card, inline ALL values as literals — do NOT leave
# ${PROJECT_ID}, ${LOCATION_ID}, or ${PUBLISHER_MODEL} as shell variables.
# The server rejects commands with unresolved variables at render time.
# The only allowed substitution is $(gcloud auth print-access-token).

PROJECT_ID=$(gcloud config get-value project)
# `gcloud ai` needs the alphanumeric Project ID, not the project number.
: "${PROJECT_ID:?no project ID is set; ask the user for the Project ID}"
LOCATION_ID="us-central1" # Recommended default region
# Replace placeholder with exact ID from `gcloud ai model-garden models list`:
MODEL_ID="<PUBLISHER>/<FAMILY>@<VERSION-ID>"

echo "Deploying model $MODEL_ID to project $PROJECT_ID in $LOCATION_ID..."

# Hardware params can be omitted to select recommended default config.
# Comprehensive command with supported parameters:
gcloud ai model-garden models deploy \
    --project=$PROJECT_ID \
    --region=$LOCATION_ID \
    --model=$MODEL_ID \
    --machine-type="g2-standard-12" \
    --accelerator-type="NVIDIA_L4" \
    --accelerator-count=1 \
    --endpoint-display-name="my-open-model-deployment" \
    --asynchronous

echo "Deployment initiated asynchronously."
```

With `--asynchronous` the command prints the full operation name,
`projects/<PROJECT>/locations/<REGION>/operations/<OP_ID>`. Pass that to §4: a
bare `<OP_ID>` works only when gcloud has a project.

-   Include `--hugging-face-access-token="<HF_TOKEN>"` when deploying gated
    Hugging Face models that require authentication.
-   Include `--reservation-affinity` (e.g. `none` or
    `reservation-affinity-type=specific-reservation,...`) if using reserved
    compute.

### 1P Tuned Model Cross-Region Copy and Deployment

> For the detailed tuned model copy and deployment workflow, load
> `load_skill_resource(skill_name='agent-platform-deploy',
> file_path='references/copy_deploy_guide.md')`. That guide covers the execution
> sequence, tier assignments for copy/deploy/delete commands, hardware
> renegotiation, test prediction verification, and the in-progress operation
> lock.

## 4. Checking Deployment Status

When you deploy a model asynchronously using the `--asynchronous` flag, the
`deploy` command returns an operation name. Pass the full name to check the
ongoing status of the deployment.

```bash
gcloud ai operations describe YOUR_OPERATION_NAME
```

> [!IMPORTANT]
>
> **Single Status Check Only (No Sleep / Polling Loops)**: Model deployment
> operations take 10–30 minutes. NEVER run `sleep` commands (e.g. `sleep 45 &&
> ...`) or loop `operations describe` repeatedly in a turn. Run `gcloud ai
> operations describe` **strictly ONCE**. If `done` is not true, immediately
> return the operation name and in-progress status to the user and explain that
> deployment takes 10–15 minutes.

Note: Large models (roughly 20B+ parameters) may take 15-20 minutes to fully
deploy and start serving.

### Verifying Deployment

If the model is successfully deployed, verify by making a prediction call to
test. Because Model Garden models are often deployed to Dedicated Endpoints, you
shouldn't use `gcloud ai endpoints predict`. Instead, you must fetch the
endpoint's dedicated DNS name and send a `curl` request.

> [!TIP] Ask the user to try using their own prompt to see the results.
> Otherwise use the default.

Use the following script:

```bash
#!/bin/bash
PROJECT_ID=$(gcloud config get-value project)
: "${PROJECT_ID:?no gcloud project is set; ask the user for the Project ID}"
LOCATION_ID="us-central1"
ENDPOINT_ID="YOUR_ENDPOINT_ID"
PROMPT=${1:-"Explain quantum computing in simple terms."}

echo "Fetching dedicated Endpoint DNS..."
ENDPOINT_URL=$(gcloud ai endpoints describe $ENDPOINT_ID \
    --project=$PROJECT_ID \
    --region=$LOCATION_ID \
    --format="value(dedicatedEndpointDns)")

if [ -z "$ENDPOINT_URL" ]; then
    echo "Error: Could not retrieve dedicated endpoint URL for $ENDPOINT_ID."
    exit 1
fi

echo "Sending prediction request to $ENDPOINT_URL..."

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  "https://${ENDPOINT_URL}/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION_ID}/endpoints/${ENDPOINT_ID}/chat/completions" \
  -d '{
    "model": "'"$ENDPOINT_ID"'",
    "messages": [
      {
        "role": "user",
        "content": "'"$PROMPT"'"
      }
    ]
  }'

```

## 5. Undeploying and Cleaning Up

> For the full undeploy and cleanup procedure (find endpoint, undeploy model,
> delete endpoint, delete model), load
> `load_skill_resource(skill_name='agent-platform-deploy',
> file_path='references/undeploy_guide.md')`.

> [!WARNING] Failing to undeploy a model will result in continuous charges for
> the allocated compute resources, even if you are not sending prediction
> requests. Always clean up after testing.

## 6. Troubleshooting

> For troubleshooting quota/resource exhausted errors and hardware fallback,
> load `load_skill_resource(skill_name='agent-platform-deploy',
> file_path='references/troubleshooting.md')`.
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:agent-platform-deploy)" \
    gcloud <command> [flags]
    ```

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

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
    server, include the `agent-skills/1.0` and `skill:agent-platform-deploy`
    tokens in the `User-Agent` header. If a `User-Agent` header is already
    specified, append the attribution suffix 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:

    ```text
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:agent-platform-deploy)
    ```

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

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
copy_deploy_guide.md 10.7 KB
# Agent Platform 1P Tuned model copy and deployment

> [!NOTE]
> **1P Specific**: This guide and its automated workflows are specifically
> designed for **1P (First-Party) Tuned Models** on Agent Platform.

In tuned model tuning and inferencing, Eng need to copy a tuned model to other
regions or projects and deploy it to a newly created endpoint to test. Eng can
benefit from the endpoint creation, model deployment and verification automation
with minimal user input and intervention.

The tasks can be described as follows:

-   `[]` Configure `gcloud` profile for prod environment.
-   `[]` Add IAM policy binding for P4SA (Service Agent) to the source project
-   `[]` Copy the tuned model to the destination project
-   `[]` Wait for copy operation to complete
-   `[]` Create a new shared endpoint
-   `[]` Deploy copied model to the endpoint
-   `[]` Wait for model deployment to complete
-   `[]` Test the endpoint with test prompts

## Step 0: Env selection and preparation

Ensure the foundational environment is ready before proceeding.
If user is copying model in different region, skip the P4SA setup section.

### 0.0 Pick a development environment & Confirm Destination Context

-   **CRITICAL: Ask for Confirmation.** You MUST present a clear confirmation
    prompt to confirm the development
    environment (e.g., `prod`), destination project (`dest-proj`), and region
    (`us-central1`) with the user. You MUST halt execution and wait for the
    user's explicit confirmation response before running any `gcloud` or `curl`
    commands. If you are generating a script for the user instead of running
    commands live, you MUST explicitly include a note in your response
    explaining that confirming the development environment (e.g., prod) and
    destination context with the user is required before running the script
    live.
-   Execute the following command to set the global variable.
    `export ENV="prod"`

### 0.1 Authentication & Project Context

-   Check if `gcloud` CLI is installed. If it is not installed, prompt the user for permission to install it before proceeding.
-   Verify `gcloud auth list`. If not authenticated, run `gcloud auth login`.
-   Execute the following command to set the global variable.
    `export PROJECT_ID=${PROJECT_ID} REGION=${REGION}`
-   Check if ${USER_EMAIL} have value (the full account email), or ask user to
    set one.

### 0.2 GCloud CLI setup

-   use `scripts/config_gcloud_cli.sh ${ENV} ${PROJECT_ID} ${REGION} ${USER_EMAIL}`

### 0.3 P4SA Setup

#### 0.3.0 Goal

To copy a model from source project ${SOURCE_PROJECT} to the destination project
${PROJECT_ID}, and ${REGION}, follow

https://docs.cloud.google.com/gemini-enterprise-agent-platform/machine-learning/model-registry/copy-model, add the

P4SA of the destination project as a new principal to the source project and
assign the Vertex AI Service Agent role to it.

#### 0.3.1 P4SA selection

-   Get project number ${PROJECT_NUMBER} using gcloud:
    `gcloud projects describe ${PROJECT_ID} --format="value(projectNumber)"`
-   Destination project P4SA:
    `service-${PROJECT_NUMBER}@gcp-sa-aiplatform.iam.gserviceaccount.com`

#### 0.3.2 P4SA assignment

-   The ${MODEL} to copy should in format of
    `projects/${SOURCE_PROJECT}/locations/${SOURCE_REGION}/models/${MODEL_ID}`

-   Get source project name `${SOURCE_PROJECT}` from the model to copy.

-   Check IAM binding: if destination project `${P4SA}` exists and has
    `Vertex AI Service Agent` role. Sample command:

    ```bash
    gcloud projects get-iam-policy ${SOURCE_PROJECT} \
    --flatten="bindings[].members" \
    --format="table(bindings.role)" \
    --filter="bindings.members:service-${PROJECT_NUMBER}@gcp-sa-aiplatform.iam.gserviceaccount.com"
    ```

-   If not, add it with the sample command, save and wait for 2 minutes.

    ```bash
    gcloud projects add-iam-policy-binding ${SOURCE_PROJECT} \
    --member="serviceAccount:service-${PROJECT_NUMBER}@gcp-sa-aiplatform.iam.gserviceaccount.com" \
    --role="roles/aiplatform.serviceAgent"
    ```

-   If failed, try to add user's account to destination project.

    ```bash
    gcloud projects add-iam-policy-binding ${DEST_PROJECT_ID} \
    --member="user:${USER_EMAIL}" --role="roles/aiplatform.admin"
    ```

-   If failed again, prompt user to do it.

## Step 1: Verify the source model exists and valid

```bash
curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" ${ENDPOINT}/ui/${MODEL}
```

## Step 2: Copy source model to destination project

If user is copying to different project and different region, try copy the model
to the desired region in the source project first, then copy across project.

### Step 2.0 Verify the iam binding exists

Make sure the destination project P4SA is added to source project as
`roles/aiplatform.serviceAgent` before proceeding.

### Step 2.1 Run copy model command and poll for LRO completion

Copying a model is a Long-Running Operation (LRO). You MUST capture the
operation ID from the initial `models:copy` response and implement a polling
loop to check the operation status over time. You MUST NOT proceed to create
the endpoint until the operation status is `done: true` and contains the
copied model metadata. If the copy operation fails (e.g., with
`403 PERMISSION_DENIED` or `error`), you MUST halt execution immediately and
report the exact error to the user.

```bash
# 1. Start Copy Operation
COPY_RESP=$(curl -s -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json; charset=utf-8" -d '{ "sourceModel":"'"${MODEL}"'"}' "${ENDPOINT}/v1/projects/${PROJECT_ID}/locations/${REGION}/models:copy")
echo "Copy response: $COPY_RESP"
OPERATION_ID=$(echo "$COPY_RESP" | grep -o '"name": "[^"]*' | grep -o '[^"]*$')

if [ -z "$OPERATION_ID" ]; then
    echo "Error: Failed to initiate model copy. Response: $COPY_RESP"
    exit 1
fi

echo "Polling copy operation: $OPERATION_ID..."
while true; do
    OP_STATUS=$(curl -s -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" "${ENDPOINT}/v1/${OPERATION_ID}")
    IS_DONE=$(echo "$OP_STATUS" | grep -o '"done": true')
    HAS_ERROR=$(echo "$OP_STATUS" | grep -o '"error":')

    if [ -n "$HAS_ERROR" ]; then
        echo "Error during model copy: $OP_STATUS"
        exit 1
    fi

    if [ -n "$IS_DONE" ]; then
        echo "Model copy completed successfully!"
        MODEL_COPY=$(echo "$OP_STATUS" | grep -o '"model": "[^"]*' | grep -o '[^"]*$' | head -n 1)
        break
    fi
    echo "Copy in progress... waiting 10 seconds."
    sleep 10
done
```

### Step 2.2 Run describe model command

Get the copied model ${MODEL_COPY} from the LRO polling output. Describe it.

```bash
curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" ${ENDPOINT}/ui/${MODEL_COPY}
```

## Step 3: Create an endpoint

Prompt user `Creating a Public Shared endpoint in selected region: ${REGION}`.
Ask the user desired endpoint display name ${NAME}, prefer
`${<publisher_model_id>-tuned}` like "gemini-3.8-flash-tuned", default is
`copy-tuned`. If user wants to create a Dedicated Endpoint, say function to be
add.

```bash
gcloud ai endpoints create --region=${REGION} --display-name=${NAME}
gcloud ai endpoints list --region=${REGION}   --filter=display_name=${NAME}
```

Get the created endpoint id ${NEW_ENDPOINT}, it should be in format of
`projects/${PROJECT_NUMBER}/locations/${REGION}/endpoints/${NEW_ENDPOINT_ID}`.

## Step 4: Deploy the model to the endpoint

```bash
curl -X POST -H "Content-Type: application/json" \
 -H "Authorization: Bearer $(gcloud auth print-access-token)" \
 "${ENDPOINT}/v1/${NEW_ENDPOINT}:deployModel" \
 -d "{\"deployedModel\": {\"model\": \"${MODEL_COPY}\", \"displayName\": \"${NAME}\"}}"
```

Get the deploy model operation ${OPERATION} status.

`curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)"
${ENDPOINT}/ui/${OPERATION}`

Once operation is done, check the endpoint status.

```bash
gcloud ai endpoints describe ${NEW_ENDPOINT}
```

## Step 5: Send a request and verify the endpoint

```bash
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)"  -H "Content-Type: application/json" ${ENDPOINT}/v1/${NEW_ENDPOINT}:generateContent -d '{  "contents":  {    "role": "USER",   "parts" : { "text" : "Hello world" }  },}'
```

## Workflow-Specific Safety Rules

The system instruction's Tier M/D confirmation gates apply to every mutating
command in this workflow. The rules below cover behaviors specific to the 1P
tuned model copy-and-deploy flow that are not in the system instruction.

1.  **Tier Assignments**: `gcloud ai models copy`, `gcloud ai endpoints create`,
    and `gcloud ai endpoints deploy-model` are **Tier M** (mutating,
    reversible). `gcloud ai endpoints delete` and `gcloud ai models delete` are
    **Tier D** (destructive, irreversible). The Tier M dry-run preview card for
    this workflow must include: development environment, source model ID,
    destination project and region, endpoint display name, and exact proposed
    commands.

2.  **Hardware Renegotiation / Error Recovery**: If deployment fails with a 500
    error or quota error, note that tuned Gemini models can only be deployed to
    shared public endpoints (dedicated GPU hardware cannot host tuned Gemini
    models).

3.  **Verification with Test Prediction**: When requested to send a test
    prediction:

    -   If the endpoint is still provisioning or not yet serving, explain that
        deployment is currently in progress and report the operation ID.
    -   If ready, execute the test prediction request to the dedicated endpoint
        DNS and return the response verbatim.

4.  **In-Progress Operation Lock**: When the user requests cleanup while a
    deployment is still provisioning, explicitly state that teardown is
    **BLOCKED by the in-progress operation lock** on the endpoint until
    provisioning completes. Present the Tier D confirmation prompt so the user
    can approve cleanup for when the operation finishes.

## Clean Up

Prompt asking whether or not user want to clean up each resources created during
execution.

### 1. Endpoint

If user want to delete the created endpoint, undeploy the model first, then
delete the endpoint

```bash
gcloud ai endpoints undeploy-model ${NEW_ENDPOINT} --deployed-model-id=${DEPLOYED_MODEL_ID} --region=${REGION}
gcloud ai endpoints delete ${NEW_ENDPOINT} --region=${REGION}
```

### 2. Model

```bash
gcloud ai models delete ${MODEL_COPY}
```

### 3. Env variables

Only execute these commands after confirm use does no want to or already
finished clean up copied model and endpoint.

```bash
gcloud config configurations delete ${ENV}-cdmodel
unset MODEL_COPY
unset MODEL
unset NEW_ENDPOINT
unset ENDPOINT
unset PROJECT_ID
unset PROJECT_NUMBER
unset ENV
unset REGION
unset OPERATION
unset NAME
```
region_availability.md 4.1 KB
# Region Availability Check for Publisher Endpoints

> [!NOTE] **Skip this section** if the user is deploying an open-weights model
> from Model Garden (Gemma, Llama, DeepSeek, Qwen, or any user-supplied weights)
> or a Gemini-tuned model — i.e. anything served via `gcloud ai model-garden
> models deploy` (§3) onto a dedicated endpoint. These have no per-region
> publisher endpoint restriction.
> The real failure modes for an unusual region are (a) the requested
> accelerator/machine type isn't offered in that region, or (b) the project has
> no quota — both surface as a clean error at deploy time before any resources
> are provisioned (§3's cost-confirm gate catches them). Go straight to §3.
>
> **Apply this section** only if the user is asking to serve a first-party
> managed Gemini model (`google/gemini-*`) via a publisher endpoint whose
> regional availability varies.

> [!WARNING] **Retired Legacy Models (Do NOT Probe or Recommend)**: Legacy
> Gemini 2.5 models (such as `gemini-2.5-flash`, `gemini-2.5-pro`, and
> `gemini-2.5-flash-lite`) are retired. If the user asks to deploy or check
> regional availability (including for a LoRA adapter) on a retired
> `gemini-2.5-*` base model, **STOP immediately — do NOT run any
> `:generateContent` or `gcloud` probe against the retired model and do NOT
> recommend it**. Instead, inform the user that the requested `gemini-2.5-*`
> model is retired and suggest active supported models such as
> `gemini-3.8-flash` or `gemini-3.5-flash-lite`.

Before responding to any deploy request that names a specific region for an
active first-party managed Gemini model (`google/gemini-*`), you **MUST** verify
the model is actually available in that region by making a live API call. Do not
rely on Google Search, training-corpus knowledge, or publisher documentation for
availability claims — regional availability changes frequently and grounded text
can be stale or wrong.

Probe only the exact model and region the user asked about. Do not probe other
models as a "control" — you cannot infer anything about model A's availability
from model B's status, because a different model may itself be unavailable in
the reference region for unrelated reasons.

For first-party publisher models (`google/*`), probe with a real
`:generateContent` call using a minimal valid payload. This probe is
agent-executed in the sandbox — do not ask the user to run it manually:

```bash

curl -sS -o /dev/null -w "%{http_code}\n" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://${LOCATION_ID}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION_ID}/publishers/google/${MODEL_ID}:generateContent" \
    -d "{\"contents\":{\"role\":\"user\",\"parts\":{\"text\":\"${PROBE_TEXT:-hi}\"}}}"

```

For LoRA adapters deployed on top of a first-party Gemini base model, probe the
**base model** in the target region using the same `:generateContent` call above
with `${MODEL_ID}` set to the base (e.g. `gemini-3.8-flash`). The adapter cannot
serve in a region where its base model isn't available. This does not apply to
Gemini Tuning models, which are deployed via a different path and have no
publisher-endpoint region restriction.

Interpret the probe result and act:

-   **200** — model is available in that region. Proceed with the deploy.
-   **404** — model is not available in that region. STOP. Tell the user plainly
    that the model isn't offered in that region and list the regions where it is
    available (from `gcloud ai model-garden models list
    --filter="name~${MODEL_NAME}"` without `--region`). Do not silently switch
    regions. Do not proceed to write deploy code or SDK initialization for the
    unsupported region. Do not run additional "control" probes to double-check
    the 404 — the target-region probe is authoritative.
-   **Any other outcome** (permission denied, quota, transient failure, etc.) —
    do not conclude the model is available or unavailable. Explain the
    underlying cause in plain language (e.g. "your account doesn't have access
    to this project's Vertex AI API — enable it in the console or switch
    projects") and the concrete next action.
troubleshooting.md 1.0 KB
# Troubleshooting

## Deployment Failure: Quota or Resource Exhausted

If your deployment fails (or stays in an error state) due to `QUOTA_EXCEEDED` or
`RESOURCE_EXHAUSTED` errors, the specific hardware requested (e.g., `NVIDIA_L4`
or `g2-standard-24`) is either not available in your chosen region or exceeds
your project's quota limits.

**Solution:** Look closely at the error message returned. It will often
recommend an alternative region or machine type that currently has availability.
**Ask the user for confirmation** to retry the deployment using the suggested
`--region` or `--machine-type` parameters.

> [!WARNING] If the alternative suggestions involve changing the machine type or
> accelerator, you **MUST** recalculate the estimated cost by re-running
> `scripts/calculate_cost.py` with the new params (see the cost-estimation step
> in SKILL.md §3), warn the user about list prices versus actual billing, and
> get their explicit confirmation for the new cost before retrying the
> deployment.
undeploy_guide.md 2.1 KB
# Undeploying and Cleaning Up

To stop incurring charges, you must undeploy the model from the endpoint. This
is a multi-step process if you don't already have the exact endpoint and
deployed model IDs.

## Example: Finding and Undeploying a Model

Here is a bash script demonstrating how to find the IDs and undeploy the model.

```bash
#!/bin/bash
# Example script to undeploy a model

PROJECT_ID=$(gcloud config get-value project)
: "${PROJECT_ID:?no gcloud project is set; ask the user for the Project ID}"
LOCATION_ID="us-central1"
# The model ID used during deployment.
# It is usually easiest to find via `gcloud ai models list`.

# 1. Find the Endpoint ID
echo "Listing endpoints in ${LOCATION_ID}:"
gcloud ai endpoints list --project=${PROJECT_ID} --region=${LOCATION_ID}

# (Assuming you extracted ENDPOINT_ID from the above output)
# ENDPOINT_ID="your_endpoint_id"

# 2. Find the Deployed Model ID
echo "Listing models in ${LOCATION_ID} to find model description:"
gcloud ai models list --project=${PROJECT_ID} --region=${LOCATION_ID}

# (Assuming you found the specific MODEL_ID)
# MODEL_ID="your_model_id"
# gcloud ai models describe ${MODEL_ID} \
#     --project=${PROJECT_ID} --region=${LOCATION_ID}
# (Extract the deployedModelId from the output)
# DEPLOYED_MODEL_ID="your_deployed_model_id"

# 3. Undeploy
echo "Undeploying model ${DEPLOYED_MODEL_ID} from endpoint ${ENDPOINT_ID}..."
gcloud ai endpoints undeploy-model ${ENDPOINT_ID} \
    --project=${PROJECT_ID} \
    --region=${LOCATION_ID} \
    --deployed-model-id=${DEPLOYED_MODEL_ID}

echo "Model undeployed."

# 4. Delete Endpoint
echo "Deleting endpoint ${ENDPOINT_ID}..."
gcloud ai endpoints delete ${ENDPOINT_ID} \
    --project=${PROJECT_ID} \
    --region=${LOCATION_ID} \
    --quiet
echo "Endpoint deleted."

# 5. Delete Model
echo "Deleting model ${MODEL_ID}..."
gcloud ai models delete ${MODEL_ID} \
    --project=${PROJECT_ID} \
    --region=${LOCATION_ID} \
    --quiet
echo "Model deleted."
```

> [!WARNING] Failing to undeploy a model will result in continuous charges for
> the allocated compute resources, even if you are not sending prediction
> requests. Always clean up after testing.
usage.md 0.4 KB
# Sample Prompts

* User prompt:

```
I want to use `prod` as development environment.
copy the tuned model `projects/${PROJECT_NUMBER}/locations/${REGION}/models/${MODEL_ID}`
to project `${DEST_PROJECT_ID}`
in region `us-central1`
and deploy it to a newly created shared endpoint.
All use name `gemini-3.8-flash-tuned`
and then test the endpoint with a few prompts.
```
scripts/
calculate_cost.py 6.2 KB
"""Estimate the hourly deployment cost for a Model Garden deployment.

Sandbox-executable Python script that computes an hourly $ estimate for a
`gcloud ai model-garden models deploy` invocation, given `--machine-type`.

Prices are hardcoded from live `CostEstimationService.CalculateEstimate`
RPC responses (autopush blade, us-central1) captured on LAST_UPDATED.
Machine type → GPU count → hourly $ is a fixed mapping in Model Garden's
`deployment_machine_specs` config, so each machine_type has exactly one
valid pairing and one price. Actual bill may differ due to region,
discounts, reservations, or subsequent SKU repricing.

This is a stopgap; the long-term plan is to have the root agent call
`CostEstimationService.CalculateEstimate` directly (which resolves live
SKUs via Cloud Billing) and pass the result into the sandbox. See design
doc referenced in the CL description.
"""

import argparse
import datetime
import sys

LAST_UPDATED = "2026-07-08"

# Threshold beyond which LAST_UPDATED is treated as stale enough to warn
# the caller loudly. `SKILL.md` §3.2 requires the agent to present the
# script's estimate to the user, so a silently-stale table would quote
# outdated prices with the same confidence as fresh ones. 90 days is a
# quarter — long enough to survive a refresh gap, short enough to catch a
# forgotten refresh before it becomes materially wrong.
_STALENESS_THRESHOLD_DAYS = 90

# Machine type → (accelerator_type, accelerator_count, hourly_$_us_central1)
# in USD. Verified against CostEstimationService.CalculateEstimate. Every
# entry ships as a fixed bundle from Model Garden's deployment_machine_specs;
# users cannot override the accelerator pairing per machine type.
_MACHINE_SPECS = {
    # A3
    "a3-ultragpu-8g": ("NVIDIA_H200_141GB", 8, 96.0156),
    "a3-megagpu-8g": ("NVIDIA_H100_MEGA_80GB", 8, 106.6547),
    "a3-highgpu-8g": ("NVIDIA_H100_80GB", 8, 101.0074),
    "a3-highgpu-4g": ("NVIDIA_H100_80GB", 4, 50.5037),
    "a3-highgpu-2g": ("NVIDIA_H100_80GB", 2, 25.2518),
    "a3-highgpu-1g": ("NVIDIA_H100_80GB", 1, 12.6259),
    "a3-edgegpu-8g": ("NVIDIA_H100_80GB", 8, 101.0074),
    # A2 Ultra (A100 80GB)
    "a2-ultragpu-8g": ("NVIDIA_A100_80GB", 8, 46.2548),
    "a2-ultragpu-4g": ("NVIDIA_A100_80GB", 4, 23.1274),
    "a2-ultragpu-2g": ("NVIDIA_A100_80GB", 2, 11.5637),
    "a2-ultragpu-1g": ("NVIDIA_A100_80GB", 1, 5.7818),
    # A2 Standard (Tesla A100)
    "a2-megagpu-16g": ("NVIDIA_TESLA_A100", 16, 64.1021),
    "a2-highgpu-8g": ("NVIDIA_TESLA_A100", 8, 33.7960),
    "a2-highgpu-4g": ("NVIDIA_TESLA_A100", 4, 16.8980),
    "a2-highgpu-2g": ("NVIDIA_TESLA_A100", 2, 8.4490),
    "a2-highgpu-1g": ("NVIDIA_TESLA_A100", 1, 4.2245),
    # G4 (RTX Pro 6000)
    "g4-standard-384": ("NVIDIA_RTX_PRO_6000", 8, 41.4007),
    "g4-standard-192": ("NVIDIA_RTX_PRO_6000", 4, 20.7004),
    "g4-standard-96": ("NVIDIA_RTX_PRO_6000", 2, 10.3502),
    "g4-standard-48": ("NVIDIA_RTX_PRO_6000", 1, 5.1751),
    # G2 (L4)
    "g2-standard-96": ("NVIDIA_L4", 8, 9.2055),
    "g2-standard-48": ("NVIDIA_L4", 4, 4.6028),
    "g2-standard-32": ("NVIDIA_L4", 1, 1.9951),
    "g2-standard-24": ("NVIDIA_L4", 2, 2.3014),
    "g2-standard-16": ("NVIDIA_L4", 1, 1.3196),
    "g2-standard-12": ("NVIDIA_L4", 1, 1.1507),
    "g2-standard-8": ("NVIDIA_L4", 1, 0.9818),
    "g2-standard-4": ("NVIDIA_L4", 1, 0.8129),
}


def calculate_hourly_cost(machine_type: str) -> tuple[str, int, float]:
  """Returns the (accelerator_type, count, hourly_$) for a machine type.

  Args:
    machine_type: e.g. "g2-standard-48".

  Returns:
    Tuple of (accelerator_type, accelerator_count, hourly_$_us_central1).

  Raises:
    KeyError: machine_type not in the price table.
  """
  return _MACHINE_SPECS[machine_type]


if __name__ == "__main__":
  parser = argparse.ArgumentParser(
      description="Estimate hourly deployment cost for a Model Garden deploy."
  )
  # No `choices=` here on purpose. `_MACHINE_SPECS` is a hand-maintained
  # price snapshot and Model Garden's `deployment_machine_specs` catalog
  # drifts independently — a machine_type present in the catalog but
  # absent here is a routine, expected state (e.g. A4/B200 today, pending
  # a snapshot refresh). `argparse` with `choices=` would reject it with
  # an unactionable usage dump; the explicit check below reports it in a
  # form the caller can act on and lets the SKILL.md fallback (§3(c),
  # pricing page URL) fire when the machine is unknown to this table.
  parser.add_argument(
      "--machine-type",
      required=True,
      help="Machine type, e.g. g2-standard-48.",
  )
  parser.add_argument(
      "--hours",
      required=False,
      type=float,
      default=1.0,
      help="Duration in hours for the total. Defaults to 1.",
  )
  args = parser.parse_args()

  if args.machine_type not in _MACHINE_SPECS:
    supported = ", ".join(sorted(_MACHINE_SPECS.keys()))
    print(
        f"Error: unknown machine type: {args.machine_type}. This table"
        f" covers: {supported}. If the machine is in Model Garden's catalog"
        " but not here, fall back to the pricing page (see SKILL.md §3(c)).",
        file=sys.stderr,
    )
    sys.exit(1)

  accel_type, accel_count, hourly = calculate_hourly_cost(args.machine_type)

  # Warn loudly when the snapshot is older than the staleness threshold, so
  # the agent (per SKILL.md §3.2) can relay this to the user instead of
  # quoting outdated numbers with false confidence.
  age_days = (
      datetime.date.today() - datetime.date.fromisoformat(LAST_UPDATED)
  ).days
  if age_days > _STALENESS_THRESHOLD_DAYS:
    print(
        f"WARNING: price snapshot is {age_days} days old"
        f" (>{_STALENESS_THRESHOLD_DAYS} days threshold;"
        f" LAST_UPDATED={LAST_UPDATED}). Refresh LAST_UPDATED and"
        " _MACHINE_SPECS before quoting these numbers.",
        file=sys.stderr,
    )

  total = hourly * args.hours
  print(f"Machine type:       {args.machine_type}")
  print(f"Accelerator:        {accel_count} x {accel_type}")
  print(f"Hourly estimate:    ${hourly:.4f}/hr")
  print(f"Duration:           {args.hours} hr")
  print(f"Total estimate:     ${total:.2f}")
  print()
  print(f"NOTE: List price in us-central1 as of {LAST_UPDATED}, verified")
  print("against CostEstimationService. Actual bill may differ due to")
  print("region, discounts, or reservations.")
config_gcloud_cli.sh 1.3 KB
#!/bin/bash

ENV=${1:-$ENV}
PROJECT_ID=${2:-$PROJECT_ID}
REGION=${3:-$REGION}
USER_EMAIL=${4:-$USER_EMAIL}

if [[ -z "${PROJECT_ID}" ]]; then
    echo "Error: PROJECT_ID is not set (neither as an argument nor as an environment variable)."
    exit 1
fi

# This script writes core/project, and `gcloud ai *` refuses a numeric one.
if [[ "${PROJECT_ID}" =~ ^[0-9]+$ ]]; then
    echo "Error: PROJECT_ID is a project number; pass the alphanumeric Project ID."
    exit 1
fi

if [[ -z "${USER_EMAIL}" ]]; then
    echo "Error: USER_EMAIL is not set (neither as an argument nor as an environment variable)."
    exit 1
fi

if [[ -z "${ENV}" ]]; then
    ENV="prod"
fi

if [[ -z "${REGION}" ]]; then
    echo "Error: REGION is not set (neither as an argument nor as an environment variable)."
    exit 1
fi

echo "PROJECT_ID: ${PROJECT_ID}"
echo "Account: ${USER_EMAIL}"
echo "Env: ${ENV}"
echo "Region: ${REGION}"
if ! gcloud config configurations describe "${ENV}-cdmodel" > /dev/null 2>&1; then
  gcloud config configurations create "${ENV}-cdmodel"
  gcloud config set core/project "${PROJECT_ID}"
  gcloud config set compute/region "${REGION}"
  gcloud config set account "${USER_EMAIL}"
fi

gcloud config configurations activate ${ENV}-cdmodel

# gcloud config configurations delete prod-cdmodel

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