gcloud
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesegcloud 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 ( 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.
gcloud本文档为AI Agent与Google Cloud SDK( CLI)交互提供了必要的指导方针和最佳实践。遵循这些规则对于避免生成幻觉命令、标志、标志值和位置参数语法,防止破坏性操作,以及最小化上下文窗口占用至关重要。
gcloudGetting Started
入门指南
1. Installation
1. 安装
If the 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等)上进行安装。
gcloud2. Authorization
2. 授权
Authenticate the CLI with Google Cloud. Choose the flow that matches your
running environment:
- User Account (Interactive): Run . Follow the browser prompts to sign in.
gcloud auth login - User Account (Headless Flow): If operating on a terminal without a web
browser (e.g. containers, remote SSH), append the flag:
--no-browser. Copy the URL, sign in on another machine, and return the authentication code.gcloud auth login --no-browser - Application Default Credentials (ADC): To authenticate code calls from
local applications or SDK libraries, set up ADC via (append
gcloud auth application-default loginfor headless environments).--no-browser - Service Account (Best for Detached/Headless Automation): Authenticate
directly using a JSON key file. Ideal for fully automated, background tasks
and pipelines: . Note that some organizations may restrict access to JSON key files for security reasons.
gcloud auth activate-service-account --key-file=path/to/key.json - 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.serviceAccountTokenCreatorFor 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。复制URL,在另一台设备上登录,然后返回验证码。gcloud auth login --no-browser - 应用默认凭据(ADC):要对本地应用或SDK库的代码调用进行身份验证,通过设置ADC(无浏览器环境添加
gcloud auth application-default login)。--no-browser - 服务账号(适用于无交互/自动化场景的最佳选择):直接使用JSON密钥文件进行身份验证。非常适合完全自动化的后台任务和流水线:。请注意,部分组织可能出于安全原因限制对JSON密钥文件的访问。
gcloud auth activate-service-account --key-file=path/to/key.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 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.
gcloud- Action: Always call for the exact command you intend to run (e.g.,
gcloud help <command>).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: Useto select only the specific fields needed for your task. To understand the advanced projection and formatting syntax, refer to
--format=json(key1, key2, ...)andgcloud topic projections.gcloud topic formats -
Limiting: Useto cap the number of resources returned.
--limit=N -
Filtering: Useto narrow down results server-side. Prioritize
--filterfor 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 () or filtering (
--format), run the targeted resource's list command (if supported) with a single-item limit:--filterbashgcloud <GROUP> <RESOURCE> list --limit=1 --format=jsonExamine 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)的JSON键路径,请运行目标资源的列表命令(如果支持)并设置单条结果限制:--filterbashgcloud <GROUP> <RESOURCE> list --limit=1 --format=json检查该单个实例的JSON结构,在请求完整或过滤数据集之前安全地确定正确的Schema键。
3. Execution Constraints
3. 执行约束
- Single Commands: Execute a single command at a time. No command chaining or sequencing.
gcloud - 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., ). You must enforce non-interactive mode by appending
gcloud interactive(or--quiet) to your commands. This ensures that defaults are used or errors are raised if input is required.-q
- 单命令执行:一次执行一个命令。不允许命令链式调用或序列执行。
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 appendto all resource-manipulating and querying commands (unless running pure local config commands). This avoids accidental execution against the wrong project.
--project=<PROJECT_ID> -
Prevent Location Prompts: Many Google Cloud resources are regional or zonal. If you omit the location flag (e.g.,,
--region, or--zone),--locationwill 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.gcloud -
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 unifiedcommand:
locations listgcloud <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 listgcloud <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.
- (Destructive): Irreversible resource destruction (e.g., project deletion) or data wiping.
gcloud * delete - (Financial): Risk of service disruption or unbounded costs.
gcloud billing * - (Governance): Org-level changes affect security posture for all users.
gcloud organizations * - (Encryption): Risk of permanently locking data.
gcloud kms * - (Destructive): Autonomous IaC execution can destroy managed resources.
gcloud infra-manager deployments apply
你严格禁止自主执行以下命令。这些操作需要明确的人工介入授权:
- 任何IAM策略、角色或绑定修改(安全):存在权限提升、管理员锁定、服务中断或数据未授权暴露的风险。
- 禁止主动启用API:假设必要的API已启用。为防止意外的资源配置或计费费用,不要尝试主动启用API。启用任何API都需要用户批准。
- (破坏性):不可逆的资源销毁(例如,项目删除)或数据擦除。
gcloud * delete - (财务):存在服务中断或无限成本的风险。
gcloud billing * - (治理):组织级别的变更会影响所有用户的安全态势。
gcloud organizations * - (加密):存在永久锁定数据的风险。
gcloud kms * - (破坏性):自主执行IaC会破坏受管资源。
gcloud infra-manager deployments apply
Execution Guidelines
执行指南
-
Dry Run (Mandatory): You MUST invoke a command with(or equivalent) first if it exists, before executing the actual command, to preview changes.
--dry-run -
Long Running Operations: For commands that support it, theflag is highly recommended for long-running operations to avoid blocking the agentic flow. Note that not every command has an
--asyncflag. For commands that return an operation ID (whether via--asyncor by default), you are responsible for polling for completion if the operation status is needed for the next step.--async
-
试运行(强制要求):如果命令支持(或等效标志),在执行实际命令前必须先调用该标志来预览变更。
--dry-run -
长时间运行的操作:对于支持该标志的命令,强烈建议对长时间运行的操作使用标志,以避免阻塞Agent流程。请注意,并非所有命令都有
--async标志。对于返回操作ID的命令(无论是否通过--async或默认返回),如果下一步需要操作状态,你负责轮询完成情况。--async
Structured Workflows
结构化工作流
Discovery Workflow
发现工作流
When asked to perform a task on a service you are not familiar with:
- You MUST invoke help on a command (e.g., ) before invoking it.
gcloud help <COMMAND> - If you do not know the exact command, traverse the command tree by invoking
help on a command group (e.g., ) to discover available subcommands and groups.
gcloud help compute - Schema Discovery: If you need to filter or project fields from a list
command, but do not know the exact JSON keys, first run to safely discover the schema. Never run a raw
gcloud <GROUP> <RESOURCE> list --limit=1 --format=jsoncommand without scoping constraints (likelist), as unconstrained results will pollute and exhaust your context window.--limit=1 - Execute with data reduction flags.
当被要求对不熟悉的服务执行任务时:
- 在调用命令前,必须先调用该命令的帮助信息(例如,)。
gcloud help <COMMAND> - 如果你不知道确切的命令,通过调用命令组的帮助信息(例如,)来遍历命令树,发现可用的子命令和组。
gcloud help compute - Schema发现:如果你需要从列表命令中过滤或投影字段,但不知道确切的JSON键,请先运行来安全地发现Schema。绝对不要在没有范围约束(如
gcloud <GROUP> <RESOURCE> list --limit=1 --format=json)的情况下运行原始--limit=1命令,因为不受限制的结果会污染并耗尽你的上下文窗口。list - 使用数据缩减标志执行命令。
Quick Reference / Cheat Sheet
快速参考/ Cheat Sheet
| Task | Command Template |
|---|---|
| Discover Schema | |
| Filtered List | |
| Specific Columns | |
| Learn Filters | |
| Learn Formats | |
| Learn Projections | |
| Asynchronous Op | |
| Check Operation | |
| Common commands | |
| List Regions (GCE) | |
| List Zones (GCE) | |
| List Locations | |
Refer to the
gcloud CLI Scripting Guide
for guidance on using the gcloud CLI in automation.
| 任务 | 命令模板 |
|---|---|
| 发现Schema | |
| 过滤列表 | |
| 指定列 | |
| 学习过滤语法 | |
| 学习格式语法 | |
| 学习投影语法 | |
| 异步操作 | |
| 检查操作状态 | |
| 常用命令 | |
| 列出GCE区域 | |
| 列出GCE分区 | |
| 列出地域 | |
请参阅gcloud CLI脚本指南,了解在自动化中使用gcloud CLI的指导。