gcloud

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

gcloud CLI Skill for AI Agents

面向AI Agent的gcloud CLI技能指南

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.
本文档为AI Agent与Google Cloud SDK(
gcloud
CLI)交互提供了必要的指导方针和最佳实践。遵循这些规则对于避免生成幻觉命令、标志、标志值和位置参数语法,防止破坏性操作,以及最小化上下文窗口占用至关重要。

Getting Started

入门指南

1. Installation

1. 安装

If the
gcloud
executable is missing, refer to the official Google Cloud CLI Installation Guide to install it on your platform (Linux, macOS, Windows, etc.).
如果缺少
gcloud
可执行文件,请参考官方的Google Cloud CLI安装指南,在你的平台(Linux、macOS、Windows等)上进行安装。

2. Authorization

2. 授权

Authenticate the CLI with Google Cloud. Choose the flow that matches your running environment:
  • User Account (Interactive): Run
    gcloud auth login
    . Follow the browser prompts to sign in.
  • User Account (Headless Flow): If operating on a terminal without a web browser (e.g. containers, remote SSH), append the
    --no-browser
    flag:
    gcloud auth login --no-browser
    . Copy the URL, sign in on another machine, and return the authentication code.
  • Application Default Credentials (ADC): To authenticate code calls from local applications or SDK libraries, set up ADC via
    gcloud auth application-default login
    (append
    --no-browser
    for headless environments).
  • Service Account (Best for Detached/Headless Automation): Authenticate directly using a JSON key file. Ideal for fully automated, background tasks and pipelines:
    gcloud auth activate-service-account --key-file=path/to/key.json
    . Note that some organizations may restrict access to JSON key files for security reasons.
  • Service Account Impersonation (Preferred for Local Pair-Programming Agents): Leverage the human developer's existing user credentials to assume a service account identity. Best for local development assistants to avoid insecure private keys on human workstations:
    gcloud config set auth/impersonate_service_account SERVICE_ACCT_EMAIL
Separation of Privilege (Critical): Both service account approaches ensure the agent's permissions remain strictly distinct from the human user's wide access limits (enforcing least privilege), and ensure actions are properly audited under the agent's focused identity. (Impersonation requires
roles/iam.serviceAccountTokenCreator
)
.
For more detailed strategies and authentication types (such as Workload Identity Federation), see Authorizing the gcloud CLI.
通过CLI向Google Cloud进行身份验证。选择与你的运行环境匹配的流程:
  • 用户账号(交互式):运行
    gcloud auth login
    。按照浏览器提示完成登录。
  • 用户账号(无浏览器流程):如果在没有网页浏览器的终端(如容器、远程SSH)中操作,添加
    --no-browser
    标志:
    gcloud auth login --no-browser
    。复制URL,在另一台设备上登录,然后返回验证码。
  • 应用默认凭据(ADC):要对本地应用或SDK库的代码调用进行身份验证,通过
    gcloud auth application-default login
    设置ADC(无浏览器环境添加
    --no-browser
    )。
  • 服务账号(适用于无交互/自动化场景的最佳选择):直接使用JSON密钥文件进行身份验证。非常适合完全自动化的后台任务和流水线:
    gcloud auth activate-service-account --key-file=path/to/key.json
    。请注意,部分组织可能出于安全原因限制对JSON密钥文件的访问。
  • 服务账号模拟(本地结对编程Agent的首选方式):利用人类开发者已有的用户凭据来获取服务账号身份。非常适合本地开发助手,避免在人类工作站上存储不安全的私钥:
    gcloud config set auth/impersonate_service_account SERVICE_ACCT_EMAIL
权限分离(至关重要):两种服务账号方式都能确保Agent的权限严格区分于人类用户的广泛访问权限(执行最小权限原则),并确保操作在Agent的专属身份下得到妥善审计。(模拟需要
roles/iam.serviceAccountTokenCreator
权限)
如需更详细的策略和身份验证类型(如工作负载身份联合),请参阅授权gcloud CLI

Core Principles

核心原则

1. Explicit Command Validation (Mandatory)

1. 显式命令验证(强制要求)

Your internal knowledge of
gcloud
may be stale or prone to hallucination (e.g., hallucinating commands, flags, flag values, or positional argument syntax). You are FORBIDDEN from executing commands until you have validated the exact syntax at the leaf level.
  • Action: Always call
    gcloud help <command>
    for the exact command you intend to 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. Validation is not transitive from parent groups.
你对
gcloud
的内部认知可能过时或容易产生幻觉(例如,生成不存在的命令、标志、标志值或位置参数语法)。在验证确切的叶子级语法之前,禁止执行命令。
  • 操作:始终调用
    gcloud help <command>
    来获取你打算运行的确切命令的帮助信息(例如,
    gcloud help compute instances create
    )。
  • 验证:在尝试执行前,确保命令、标志、标志值和位置参数语法对该特定叶子命令有效。验证不会从父命令组传递。

2. Data Reduction Strategies

2. 数据缩减策略

To save context window space and reduce latency, always minimize the volume of data returned by
gcloud
.
  • Projection: Use
    --format=json(key1, key2, ...)
    to select only the specific fields needed for your 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 your context window with redundant data. To prevent this, discover a resource's schema before executing queries. If you are 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.
为节省上下文窗口空间并降低延迟,始终最小化
gcloud
返回的数据量。
  • 投影:使用
    --format=json(key1, key2, ...)
    仅选择任务所需的特定字段。要了解高级投影和格式语法,请参考
    gcloud topic projections
    gcloud topic formats
  • 限制数量:使用
    --limit=N
    限制返回的资源数量。
  • 过滤:使用
    --filter
    在服务器端缩小结果范围。优先使用
    :
    进行模式匹配,且不要对冒号右侧的内容加引号。将整个过滤标志视为单个字符串,无需引号或转义字符。要学习过滤表达式语法,请参考
    gcloud topic filters
  • Schema发现:不受限制的资源列表会快速用冗余数据耗尽你的上下文窗口。为避免这种情况,在执行查询前先发现资源的Schema。如果你不确定投影字段(
    --format
    )或过滤(
    --filter
    )的JSON键路径,请运行目标资源的列表命令(如果支持)并设置单条结果限制:
    bash
    gcloud <GROUP> <RESOURCE> list --limit=1 --format=json
    检查该单个实例的JSON结构,在请求完整或过滤数据集之前安全地确定正确的Schema键。

3. Execution Constraints

3. 执行约束

  • 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.
  • No Interactivity: Do not run interactive commands or commands requiring a TTY (e.g.,
    gcloud interactive
    ). You must enforce non-interactive mode by appending
    --quiet
    (or
    -q
    ) to your commands. This ensures that defaults are used or errors are raised if input is required.
  • 单命令执行:一次执行一个
    gcloud
    命令。不允许命令链式调用或序列执行。
  • 禁止Shell操作符:不要使用命令替换(
    $(...)
    )、管道(
    |
    )或重定向(
    >
    ,
    >>
    ,
    <
    )。这是为了提高命令安全性,并确保命令更易于用户理解和审核。
  • 禁止交互:不要运行交互式命令或需要TTY的命令(例如,
    gcloud interactive
    )。你必须通过添加
    --quiet
    (或
    -q
    )标志来强制执行非交互模式。这确保在需要输入时使用默认值或抛出错误。

4. Project and Location Scoping (Critical)

4. 项目与地域范围限定(至关重要)

To ensure commands are deterministic, non-interactive, and target the correct environment, you must explicitly manage 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 you omit the location flag (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 you do not know the correct region, zone, or location for a service, 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
        .
为确保命令具有确定性、非交互性,并指向正确的环境,你必须显式管理项目和地域范围。
  • 显式指定目标项目:不要依赖活动配置的默认值。始终在所有资源操作和查询命令后添加
    --project=<PROJECT_ID>
    (除非运行纯本地配置命令)。这避免了在错误的项目上意外执行命令。
  • 避免地域提示:许多Google Cloud资源是区域性或分区性的。如果你省略地域标志(例如,
    --region
    ,
    --zone
    , 或
    --location
    ),
    gcloud
    会触发交互式提示来选择区域/分区。这违反了禁止交互规则。如果命令需要,始终提供显式的地域标志。
  • 地域发现:如果你不知道服务的正确区域、分区或地域,请先运行发现命令(如果结果较多,请记得限制数量):
    • Compute Engine(虚拟机、网络)
      • gcloud compute regions list --project=<PROJECT_ID>
      • gcloud compute zones list --project=<PROJECT_ID>
    • 其他服务(标准API风格):许多GCP服务使用统一的
      locations list
      命令:
      • gcloud <GROUP> locations list --project=<PROJECT_ID>
      • 示例
        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.
[!CAUTION] 破坏性操作(删除、更新、移除)必须获得用户的明确授权。 除非在安全、预先批准的工作流中明确指示,否则绝不能自主调用这些操作。

Prohibited Operations (Denylist)

禁止操作(黑名单)

You are strictly prohibited from executing 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.
严格禁止自主执行以下命令。这些操作需要明确的人工介入授权:
  • 任何IAM策略、角色或绑定修改(安全):存在权限提升、管理员锁定、服务中断或数据未授权暴露的风险。
  • 禁止主动启用API:假设必要的API已启用。为防止意外的资源配置或计费费用,不要尝试主动启用API。启用任何API都需要用户批准。
  • gcloud * delete
    (破坏性):不可逆的资源销毁(例如,项目删除)或数据擦除。
  • gcloud billing *
    (财务):存在服务中断或无限成本的风险。
  • gcloud organizations *
    (治理):组织级别的变更会影响所有用户的安全态势。
  • gcloud kms *
    (加密):存在永久锁定数据的风险。
  • gcloud infra-manager deployments apply
    (破坏性):自主执行IaC会破坏受管资源。

Execution Guidelines

执行指南

  • Dry Run (Mandatory): You MUST invoke a command with
    --dry-run
    (or equivalent) first if it exists, before executing the actual command, to preview changes.
  • 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), you are responsible for polling for completion if the operation status is needed for the next step.
  • 试运行(强制要求):如果命令支持
    --dry-run
    (或等效标志),在执行实际命令前必须先调用该标志来预览变更。
  • 长时间运行的操作:对于支持该标志的命令,强烈建议对长时间运行的操作使用
    --async
    标志,以避免阻塞Agent流程。请注意,并非所有命令都有
    --async
    标志。对于返回操作ID的命令(无论是否通过
    --async
    或默认返回),如果下一步需要操作状态,你负责轮询完成情况。

Structured Workflows

结构化工作流

Discovery Workflow

发现工作流

When asked to perform a task on a service you are not familiar with:
  1. You MUST invoke help on a command (e.g.,
    gcloud help <COMMAND>
    ) before invoking it.
  2. If you do not know the exact command, traverse the command tree by invoking help on a command group (e.g.,
    gcloud help compute
    ) to discover available subcommands and groups.
  3. Schema Discovery: If you need to filter or project fields from a list command, but do not know the exact JSON keys, first run
    gcloud <GROUP> <RESOURCE> list --limit=1 --format=json
    to safely discover the schema. Never run a raw
    list
    command without scoping constraints (like
    --limit=1
    ), as unconstrained results will pollute and exhaust your context window.
  4. Execute with data reduction flags.
当被要求对不熟悉的服务执行任务时:
  1. 在调用命令前,必须先调用该命令的帮助信息(例如,
    gcloud help <COMMAND>
    )。
  2. 如果你不知道确切的命令,通过调用命令组的帮助信息(例如,
    gcloud help compute
    )来遍历命令树,发现可用的子命令和组。
  3. Schema发现:如果你需要从列表命令中过滤或投影字段,但不知道确切的JSON键,请先运行
    gcloud <GROUP> <RESOURCE> list --limit=1 --format=json
    来安全地发现Schema。绝对不要在没有范围约束(如
    --limit=1
    )的情况下运行原始
    list
    命令,因为不受限制的结果会污染并耗尽你的上下文窗口。
  4. 使用数据缩减标志执行命令。

Quick Reference / Cheat Sheet

快速参考/ Cheat Sheet

TaskCommand 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 for guidance on using the gcloud CLI in automation.
任务命令模板
发现Schema
gcloud <GROUP> <RESOURCE> list --limit=1 --format=json
过滤列表
gcloud <GROUP> <RESOURCE> list --filter="status:RUNNING"
指定列
gcloud <GROUP> <RESOURCE> list --format="json(name, id)"
学习过滤语法
gcloud topic filters
学习格式语法
gcloud topic formats
学习投影语法
gcloud topic projections
异步操作
gcloud <COMMAND> --async
检查操作状态
gcloud operations describe <OPERATION_ID>
常用命令
gcloud cheat-sheet
列出GCE区域
gcloud compute regions list --project=<PROJECT_ID>
列出GCE分区
gcloud compute zones list --project=<PROJECT_ID>
列出地域
gcloud <GROUP> locations list --project=<PROJECT_ID>
请参阅gcloud CLI脚本指南,了解在自动化中使用gcloud CLI的指导。