references/cli-usage.md
# gcloud CLI Usage
This document provides reference information for installing, authorizing, and
configuring the Google Cloud SDK (`gcloud` CLI) in local and automated
environments.
## Installation
If the `gcloud` binary is not installed in the execution environment, refer to
the authoritative
[Google Cloud CLI Installation Guide](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)
for platform-specific installation instructions (Linux, macOS, Windows, package
managers, and container images).
### Component Management
The `gcloud components` command group manages optional CLI components (such as
additional tools, emulators, and language runtimes):
- **List available components:**
```bash
gcloud components list
```
- **Install a component:**
```bash
gcloud components install {component_id} --quiet
```
- **Update all installed components:**
```bash
gcloud components update --quiet
```
*(Note: If `gcloud` was installed via a system package manager like APT or DNF,
use the system package manager to install components instead of `gcloud
components install`.)*
## Authorization & Authentication
Authenticate the CLI with Google Cloud according to the operational environment:
- **User Account (Interactive):**
```bash
gcloud auth login
```
Follow the browser prompts to sign in and grant access.
- **User Account (Headless Flow):**
For environments without an accessible web browser (containers, remote SSH):
```bash
gcloud auth login --no-browser
```
Copy the generated URL, open it on another machine to complete sign-in, and
paste the authorization code back into the terminal.
- **Application Default Credentials (ADC):**
Configures credentials for client libraries and local applications:
```bash
gcloud auth application-default login
```
Append `--no-browser` in headless environments.
- **Service Account Key (Headless Automation):**
```bash
gcloud auth activate-service-account --key-file=path/to/key.json
```
*Security note: Restrict file permissions on JSON keys or prefer Workload
Identity / Impersonation.*
- **Service Account Impersonation (Preferred for Development & Agents):**
Allows a user identity to temporarily assume a service account identity
without storing long-lived private key files:
```bash
gcloud config set auth/impersonate_service_account {service_account_email}
```
Requires the `roles/iam.serviceAccountTokenCreator` role on the target
service account. This enforces least privilege and ensures audited access
under the target identity.
- **Workload Identity Federation:**
For CI/CD and external compute environments (GitHub Actions, AWS, on-prem),
authenticate using federated tokens without managing service account keys.
See
[Authorizing the gcloud CLI](https://docs.cloud.google.com/sdk/docs/authorizing.md.txt).
## Local Configuration Management
The `gcloud config` command group manages local configuration settings,
profiles, and default properties.
### Named Configurations
Configurations allow maintaining multiple isolated sets of properties (e.g.,
dev, staging, prod):
- **Create a new configuration:**
```bash
gcloud config configurations create {config_name}
```
- **List existing configurations:**
```bash
gcloud config configurations list
```
- **Activate a configuration:**
```bash
gcloud config configurations activate {config_name}
```
### Setting Common Properties
Properties set default values for flags across `gcloud` invocations:
- **Set active project:**
```bash
gcloud config set core/project {project_id}
```
- **Set default compute region and zone:**
```bash
gcloud config set compute/region {region}
gcloud config set compute/zone {zone}
```
- **View all active configuration properties:**
```bash
gcloud config list
```
references/mcp-usage.md
# Cloud CLI Remote MCP Server Usage
Google Cloud resources can be managed via the Model Context Protocol (MCP),
allowing AI agents to interact with Google Cloud using structured tool calls
rather than directly executing local shell commands.
MCP operations for `gcloud` are executed through the **Cloud CLI remote MCP
server** (backed by the Cloud CLI Execution API, `cloudcli.googleapis.com`).
## Server Endpoint & Tool Overview
- **Server Endpoint:** `https://cloudcli.googleapis.com/mcp`
- **Transport:** HTTP (JSON-RPC 2.0)
- **API Name:** Cloud CLI Execution API (`cloudcli.googleapis.com`)
- **Available Tool:** `run_gcloud_command`
The `run_gcloud_command` tool executes a single `gcloud` command securely in a
managed remote environment on behalf of the user.
## Client Configuration (`mcp_config.json`)
To connect an MCP client (such as Jetski) to the remote Cloud CLI MCP server,
configure the server entry in `mcp_config.json` with `authProviderType` set to
`"google_credentials"`:
```json
{
"mcpServers": {
"gcloud-remote": {
"serverUrl": "https://cloudcli.googleapis.com/mcp",
"authProviderType": "google_credentials"
}
}
}
```
> [!IMPORTANT] Specifying `"authProviderType": "google_credentials"` is
> mandatory. It instructs the MCP client to attach Application Default
> Credentials (ADC) with the `https://www.googleapis.com/auth/cloud-platform`
> OAuth scope. Omitting this field will cause the client to send unauthenticated
> requests, resulting in `401 Unauthorized` errors.
## Prerequisites & IAM Requirements
Before using the Cloud CLI remote MCP server, the target project and calling
identity must satisfy two mandatory prerequisites:
### 1. API Enablement
The Cloud CLI Execution API (`cloudcli.googleapis.com`) must be enabled on the
target project.
- **Via Google Cloud Console (No CLI required):**
1. Open the [Google Cloud Console](https://console.cloud.google.com/).
2. Navigate to **APIs & Services** --> **Library**.
3. Search for **Cloud CLI Execution API** (or open the
[Cloud CLI Execution API Library Page](https://console.cloud.google.com/apis/library/cloudcli.googleapis.com)).
4. Select the target project from the project dropdown.
5. Click **Enable**.
- **Via `gcloud` CLI:**
```bash
gcloud services enable cloudcli.googleapis.com --project={project_id}
```
### 2. IAM Roles & Permissions
- **MCP Access Role:** The caller identity must hold the **MCP Tool User**
role (`roles/mcp.toolUser`, which grants the `mcp.tools.call` permission) on
the target project.
- **Downstream Resource Roles:** The caller identity must also hold standard
IAM permissions on the underlying resources being queried or modified (e.g.,
`roles/compute.viewer`, `roles/run.developer`).
> [!CAUTION] If either the Cloud CLI Execution API is not enabled or the caller
> lacks the `roles/mcp.toolUser` role, the endpoint returns **`403 Forbidden`**
> during both tool discovery (`tools/list`) and tool invocation (`tools/call`).
## Tool Parameters
Calls to `run_gcloud_command` accept the following parameters:
- **`command`** (string, required): The full `gcloud` command line string to
execute (e.g., `"gcloud compute instances list --project={resource_project}
--format=json"`).
- **`project`** (string, required): The resource name of the Google Cloud
project hosting the Cloud CLI Execution API in the format
`"projects/{api_project}"` (e.g., `"projects/my-api-project"`).
- **`input_files`** (list of objects, optional): Files to provision in the
remote execution environment before running the command. Each item contains
a relative `path` and string `contents`.
> [!IMPORTANT] **API Host Project vs. Resource Project Context:**
>
> - The top-level **`project`** parameter (`"projects/{api_project}"`) is used
> **strictly for quota, billing, and API enablement** of the
> `cloudcli.googleapis.com` API itself. It does NOT set the project context
> for the command being executed.
> - For **project-scoped commands**, you MUST explicitly include
> `--project={resource_project}` within the `command` string. The target
> `{resource_project}` does NOT have to be the project hosting the Cloud CLI
> Execution API.
> - For **non-project-scoped commands** (such as billing or organization
> queries), you MUST include `--billing-project={billing_project}` in the
> `command` string if the underlying API requires a quota project.
### Example Invocations
#### 1. Basic Command Execution
```json
{
"command": "gcloud compute instances list --project=my-resource-project --format=json",
"project": "projects/my-cloudcli-api-project"
}
```
#### 2. Command with Input Files
```json
{
"command": "gcloud run services replace service-config.yaml --region=us-central1 --project=my-resource-project",
"project": "projects/my-cloudcli-api-project",
"input_files": [
{
"path": "service-config.yaml",
"contents": "apiVersion: serving.knative.dev/v1\nkind: Service\nmetadata:\n name: my-service\n..."
}
]
}
```
## Response Structure
The tool returns an execution response containing:
- `exit_code`: Numeric exit status of the command execution. **This is the
primary and authoritative indicator of command success or failure.**
- `stdout`: Standard output stream from the command.
- `stderr`: Standard error stream from the command.
- `output_files`: Any files generated by the command.
> [!NOTE] - **Exit Code Authority:** A command is successful if and only if
> `exit_code == 0`. A non-zero `exit_code` indicates failure.
>
> - **Informational `stderr` Output:** In `gcloud`, `stderr` frequently
> contains standard status messages, progress updates, and asynchronous
> tracking IDs (such as `--async` operation IDs) even when the command
> executes successfully (`exit_code == 0`). Agents MUST NOT assume a command
> failed merely because `stderr` is non-empty.
> - **Error Diagnosis:** If `exit_code != 0`, diagnostic error messages may
> appear in either `stderr` or `stdout`. Inspect both streams to understand
> the failure and formulate a correction.
## Prohibited & Unsupported Commands
The Cloud CLI remote MCP server operates in a sandboxed, non-interactive
environment. The following list shows a few example `gcloud` commands that
aren't supported (such as command groups that manage local machine
configuration, credentials, interactive shells, or metadata). This list is
non-exhaustive and subject to the addition or removal of commands without
notice:
- `gcloud auth` (Local authentication & credential management)
- `gcloud config` (Local CLI configuration profiles and properties)
- `gcloud iam service-accounts` (Service account management)
- `gcloud init` (Interactive setup wizard)
- `gcloud survey` (User feedback & surveys)
- `gcloud compute ssh` / `gcloud app instances ssh` (Interactive SSH shells)
## Safety & Execution Guidelines
- **Mandatory User Consent for Mutations:** Destructive or state-changing
commands (such as `create`, `delete`, `update`, or `patch`) modify or
destroy GCP resources. These commands must NOT be invoked autonomously
unless the user has explicitly authorized the action.
- **Asynchronous Operations (`--async`):** For long-running operations (such
as creating VM instances, GKE clusters, or database instances), always
append the `--async` flag in the `command` string to avoid execution
timeouts.
- **Data Reduction & Formatting:** Use `--format=json`, `--filter`, and
`--limit` in the `command` string to constrain output volume and prevent
context window bloat.
- **Non-Interactive Execution (`--quiet`):** Include `--quiet` (or `-q`) on
commands that might otherwise prompt for interactive user confirmation.
SKILL.md
---
name: gcloud
metadata:
category: CloudInfrastructureAndServices
description: >-
Provides safety-critical validation, guardrails, and data reduction for gcloud
CLI operations across Google Cloud Platform (GCP) services and infrastructure.
Use when planning, generating, constructing, proposing, describing, or
executing any gcloud CLI commands - including when answering questions about
gcloud syntax, or formatting flags. Don't use when writing Google Cloud
client library code or raw REST/gRPC API requests.
---
# gcloud CLI Skill for AI Agents
> [!CAUTION]
>
> ### MANDATORY PRE-CONDITION: EXPLICIT LEAF-LEVEL SYNTAX VALIDATION
>
> All pre-existing knowledge of `gcloud` commands, flags, flag values, and
> positional argument syntax is **stale and prone to hallucination**.
>
> NEVER propose command parameters, output flag options, execute commands, OR
> outline step-by-step plans for any `gcloud` task before validating leaf-level
> syntax via `gcloud help <command>` (or including leaf-level help lookup as a
> mandatory step in the plan).
>
> **Mandatory Action Rules**:
>
> 1. **Direct Execution & Code Generation**: **ALWAYS** invoke `gcloud help
> <leaf_command>` (e.g. `gcloud help compute instances create` or `gcloud
> help sql instances create`) before proposing or executing the final
> command syntax.
>
> 2. **Planning & Strategy Queries**: When asked for a plan, strategy, or next
> steps to achieve a user goal (e.g., *"What is your plan to accomplish
> X..."*), the response **MUST explicitly include running `gcloud help
> <leaf_command>`** as Step 1 of the plan before proposing flags or
> executing commands.
>
> 3. **Non-Transitive Validation**: Parent command group help (e.g. `gcloud
> help compute`) is not sufficient for leaf-level syntax validation.
> Validation must occur at the specific leaf subcommand level.
>
> 4. **FORBIDDEN Web Search Fallback**: NEVER use `search_web`, web search, or
> external documentation search tools for gcloud CLI syntax. `gcloud help
> <leaf_command>` is the **EXCLUSIVE** authorized authority for command
> syntax.
>
> 5. **User Flag & Project Preservation**: When proposing intermediate command
> steps, **ALWAYS** preserve all user-specified flags (including
> `--project=<project_id>`) in the proposed response text.
>
> 6. **Mandatory Plan Template**: When generating a plan, the response **MUST**
> copy this exact 4-step structure:
>
> - **Step 1**: Syntax Validation via `gcloud help <leaf_command>`
> - **Step 2**: Parameter Verification (confirming required and optional
> flags, and explicitly checking if the `--dry-run` or `--validate-only`
> flag is supported)
> - **Step 3**: Dry-Run Command Proposal (If `--dry-run` or
> `--validate-only` is supported, there MUST be a `--dry-run` or
> `--validate-only` invocation before the next step.)
> - **Step 4**: Command Proposal & Authorization (If the command is on the
> "Prohibited Operations" denylist, state that autonomous execution is
> forbidden, and the user MUST be explicitly asked for authorization to
> proceed. If the command is NOT on the denylist, propose or proceed
> with execution, while following *ALL* "Execution Constraints" below.)
This document provides essential guidelines and best practices for AI agents
interacting with the Google Cloud SDK (`gcloud` CLI). Following these rules is
critical to avoid hallucinated commands, flags, flag values, and positional
argument syntax, prevent destructive actions, and minimize context window usage.
## Execution Modes
AI agents can interact with Google Cloud resources in two primary ways:
- **Direct CLI Execution**: Executing `gcloud` commands directly in a local or
automated shell environment. See [CLI Usage](references/cli-usage.md) for
installation, authentication flows, and configuration management.
- **Model Context Protocol (MCP)**: Invoking structured tools via the Cloud
CLI remote MCP server (`run_gcloud_command`). See
[MCP Usage](references/mcp-usage.md) for tool schemas, parameter rules, and
server configuration.
## Core Principles
### 1. Explicit Command Validation (Mandatory)
* **Action**: **ALWAYS** call `gcloud help <command>` for the *exact* command
that is intended to be run (e.g., `gcloud help compute instances create`).
* **Verify**: Ensure the command, flags, flag values, and positional argument
syntax are valid for that specific leaf command before attempting execution
or presenting plans. Validation is not transitive from parent groups.
### 2. Data Reduction Strategies (Mandatory)
Minimize the volume of data returned by `gcloud` to save context window space
and reduce latency. DO NOT execute any `list` command without including at least
one data reduction flag (`--limit`, `--filter`, or `--format`).
* **Projection**: Use `--format="json(key1, key2, ...)"` to select only the
specific fields needed for the task. To understand the advanced projection
and formatting syntax, refer to `gcloud topic projections` and `gcloud topic
formats`.
* **Limiting**: Use `--limit=N` to cap the number of resources returned.
* **Filtering**: Use `--filter` to narrow down results server-side. Prioritize
`:` for pattern matching and never quote the right side of the colon. Treat
the entire filter flag as a singular string without quoting or escaping
characters. To study the filter expression syntax, refer to `gcloud topic
filters`.
* **Schema Discovery**: Unconstrained resource lists can quickly exhaust the
context window with redundant data. To prevent this, discover a resource's
schema before executing queries. If unsure of the JSON key path for
projecting fields (`--format`) or filtering (`--filter`), run the targeted
resource's list command (if supported) with a single-item limit:
```bash
gcloud <GROUP> <RESOURCE> list --limit=1 --format=json
```
Examine this single instance's JSON structure to safely identify the correct
schema keys before requesting full or filtered datasets.
### 3. Execution Constraints
* **Single Commands**: Execute a single `gcloud` command at a time. No command
chaining or sequencing.
* **No Shell Operators**: Do not use command substitution (`$(...)`), pipes
(`|`), or redirection (`>`, `>>`, `<`). This is to increase command safety
and ensure commands are more easily understandable and reviewable by users.
* **Non-Interactive Execution (`--quiet` / `-q`)**: Pass the `--quiet` (or
`-q`) global flag on all execution commands (e.g., `gcloud pubsub topics
delete temp-topic --quiet --project=test-project`). AI agents run in
headless, non-interactive environments without a TTY or `stdin` input
handler. Without `--quiet`, commands that prompt for user confirmation (such
as deleting resources, approving defaults, or selecting unspecified regions)
will pause execution indefinitely waiting for input, causing background task
timeouts. Including `--quiet` forces non-interactive mode, causing `gcloud`
to automatically accept safe default choices or fail immediately with an
explicit error if required parameters are missing.
* **No Blind Lists**: NEVER execute a `list` command without `--limit`,
`--filter`, or `--format`.
### 4. Project and Location Scoping (Critical)
To ensure commands are deterministic, non-interactive, and target the correct
environment, they must explicitly provide project and location scoping.
* **Explicit Project Target**: Do not rely on active configuration defaults.
Always append `--project=<PROJECT_ID>` to all resource-manipulating and
querying commands (unless running pure local config commands). This avoids
accidental execution against the wrong project.
* **Prevent Location Prompts**: Many Google Cloud resources are regional or
zonal. If the location flag is omitted (e.g., `--region`, `--zone`, or
`--location`), `gcloud` will trigger an interactive prompt to select a
zone/region. This violates the **No Interactivity** rule. Always provide
explicit location flags if the command requires them.
* **Location Discovery**: If the correct region, zone, or location for a
service is not known, run discovery commands first (remembering to limit
results if there are many):
* **Compute Engine (VMs, Networks)**:
* `gcloud compute regions list --project=<PROJECT_ID>`
* `gcloud compute zones list --project=<PROJECT_ID>`
* **Other Services (Standard API Style)**: Many GCP services utilize a
unified `locations list` command:
* `gcloud <GROUP> locations list --project=<PROJECT_ID>`
* *Examples*: `gcloud artifacts locations list`, `gcloud kms locations
list`, `gcloud secrets locations list`.
## Safety & Guardrails
> [!CAUTION] **Destructive actions (delete, update, remove) MUST be explicitly
> authorized by the user.** Never invoke them autonomously unless explicitly
> instructed to do so in the context of a safe, pre-approved workflow.
### Prohibited Operations (Denylist)
NEVER execute the following commands autonomously. These require explicit
human-in-the-loop authorization:
* **Any IAM policy, role, or binding modification** (Security): Risk of
privilege escalation, administrative lockout, service disruption, or
unauthorized data exposure.
* **No Proactive API Enabling**: Assume necessary APIs are enabled. To prevent
unexpected resource provisioning or billing charges, do not proactively try
to enable APIs. User approval is required to enable any API.
* **`gcloud * delete`** (Destructive): Irreversible resource destruction
(e.g., project deletion) or data wiping.
* **`gcloud billing *`** (Financial): Risk of service disruption or unbounded
costs.
* **`gcloud organizations *`** (Governance): Org-level changes affect security
posture for all users.
* **`gcloud kms *`** (Encryption): Risk of permanently locking data.
* **`gcloud infra-manager deployments apply`** (Destructive): Autonomous IaC
execution can destroy managed resources.
### Execution Guidelines
* **Dry Run (Mandatory)**: If the `--dry-run` or `--validate-only` flag (or
equivalent) is listed in the command help output, ALWAYS include the flag in
the proposed command or initial execution step. ALWAYS preview changes with
`--dry-run` or `--validate-only` prior to actual execution.
* **Long Running Operations**: For commands that support it, the `--async`
flag is highly recommended for long-running operations to avoid blocking the
agentic flow. Note that not every command has an `--async` flag. For
commands that return an operation ID (whether via `--async` or by default),
operation status must be polled for completion, if needed for the next step.
* **Non-Interactive Flag (`--quiet`)**: Include `--quiet` (or `-q`) on all
proposed or executed commands to guarantee non-interactive execution without
waiting for TTY confirmation prompts.
## Structured Workflows
### Discovery Workflow
When asked to perform a task on a service that is unfamiliar:
1. **Invoke Help**: Call `gcloud help <COMMAND>` on the target leaf command
prior to execution.
2. **Traverse Command Tree**: Run help on command groups (e.g., `gcloud help
compute` or `gcloud help`) to discover available subgroups and commands if
the exact command is unknown.
3. **Discover Schema**: Run `gcloud <GROUP> <RESOURCE> list --limit=1
--format=json` to inspect JSON keys before constructing filters or
projections. DO NOT execute unconstrained `list` commands without scoping
flags (e.g., `--limit=1`) to prevent context window exhaustion.
4. **Enforce Data Reduction**: Include data reduction flags (`--limit`,
`--filter`, `--format`) on all command executions.
## Quick Reference / Cheat Sheet
Task | Command Template
------------------ | ----------------------------------------------------------
Discover Schema | `gcloud <GROUP> <RESOURCE> list --limit=1 --format=json`
Filtered List | `gcloud <GROUP> <RESOURCE> list --filter="status:RUNNING"`
Specific Columns | `gcloud <GROUP> <RESOURCE> list --format="json(name, id)"`
Learn Filters | `gcloud topic filters`
Learn Formats | `gcloud topic formats`
Learn Projections | `gcloud topic projections`
Asynchronous Op | `gcloud <COMMAND> --async`
Check Operation | `gcloud operations describe <OPERATION_ID>`
Common commands | `gcloud cheat-sheet`
List Regions (GCE) | `gcloud compute regions list --project=<PROJECT_ID>`
List Zones (GCE) | `gcloud compute zones list --project=<PROJECT_ID>`
List Locations | `gcloud <GROUP> locations list --project=<PROJECT_ID>`
Refer to the
[gcloud CLI Scripting Guide](https://docs.cloud.google.com/sdk/docs/scripting-gcloud.md.txt)
for guidance on using the gcloud CLI in automation.
## Reference Directory
- [CLI Usage](references/cli-usage.md): Platform installation, authentication
methods (interactive, headless, ADC, service account keys, impersonation),
and local configuration management.
- [MCP Usage](references/mcp-usage.md): Using the Cloud CLI remote MCP
server (`run_gcloud_command`), project parameter scoping, input files, and
execution guidelines.