iam-recommendations-fetcher
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseIAM Recommendations Retrieval
IAM建议检索
This skill provides instructions for fetching IAM recommendations and insights
from Google Cloud. It covers validating the input target scope, retrieving
recommendations using MCP tools, gcloud commands, or direct API calls, and
handling common API errors.
本工具提供了从Google Cloud获取IAM建议及洞察的操作指南,涵盖输入目标范围验证、使用MCP工具、gcloud命令或直接API调用检索建议,以及处理常见API错误等内容。
Procedures
操作流程
1. Validate Input Target
1. 验证输入目标
Verify the input target scope.
-
Check Format: Check if the target matches one of these formats:
organizations/{org_id}folders/{folder_id}projects/{project_id}
-
Handle Ambiguous/Raw Target: If the user provides only a raw ID (without the prefix):
- Alphanumeric (starts with a letter): Assume it is a Project ID.
Format it as and proceed.
projects/{project_id} - Purely Numeric: It is ambiguous (could be Organization, Folder, or
Project Number).
- Ask the user to clarify the resource type: > "Is the target ID '{provided_id}' an Organization, a Folder, or a Project?"
- Once the user specifies, format the target scope accordingly (e.g.,
prepend ,
organizations/, orfolders/) and proceed.projects/ - If the user's response is invalid or they cannot clarify, treat it as an error and proceed to Handle Errors (incorrect target).
- Alphanumeric (starts with a letter): Assume it is a Project ID.
Format it as
-
Handle Project Numbers: If the target is a project but uses a purely numeric ID (Project Number) instead of a Project ID (e.g.,):
projects/123456789- recommender commands require a Project ID. Attempt to resolve the Project Number to a Project ID using:
gcloudgcloud projects list --filter="projectNumber={project_number}" --format="value(projectId)" - If this resolution returns empty or fails with a permission error, do not attempt to describe the project, search the codebase, or search for mock data. Immediately return the standardized error JSON specified in Handle Errors and stop execution (do not call any more tools).
-
Record Validation: Explicitly state the validated and formatted target scope (e.g.,or
projects/123456789) in your thought/reasoning before proceeding to the fetch step.organizations/123456789012
验证输入的目标范围。
-
检查格式:确认目标是否符合以下格式之一:
organizations/{org_id}folders/{folder_id}projects/{project_id}
-
处理模糊/原始目标:若用户仅提供原始ID(无前缀):
- 字母开头的字母数字ID:默认视为项目ID,格式化为后继续操作。
projects/{project_id} - 纯数字ID:存在歧义(可能是组织、文件夹或项目编号):
- 请用户明确资源类型:> "您提供的ID '{provided_id}' 是组织、文件夹还是项目?"
- 用户指定后,相应地格式化目标范围(例如,添加前缀、
organizations/或folders/)并继续操作。projects/ - 若用户回复无效或无法明确,将其视为错误,跳转至错误处理(目标不正确)。
- 字母开头的字母数字ID:默认视为项目ID,格式化为
-
处理项目编号:若目标是项目但使用纯数字ID(项目编号)而非项目ID(例如):
projects/123456789- 推荐工具命令需要项目ID,尝试通过以下命令将项目编号解析为项目ID:
gcloudgcloud projects list --filter="projectNumber={project_number}" --format="value(projectId)" - 若解析返回空结果或因权限错误失败,请勿尝试描述项目、搜索代码库或查找模拟数据,立即返回错误处理中指定的标准化错误JSON并停止执行(请勿调用更多工具)。
-
记录验证结果:在进入检索步骤前,需明确记录已验证并格式化后的目标范围(例如或
projects/123456789)。organizations/123456789012
2. Fetch Recommendations and Insights (Fallback Flow)
2. 检索建议与洞察(降级流程)
Attempt the following retrieval methods in order. Stop at the first success.
CRITICAL: Fail Fast on Errors (To avoid redundant API calls that will fail
for the same authorization/permission reasons): If any attempted method (Option
A or Option B) fails with an API-level error (such as ,
, or resource / does not exist) or a CLI validation
error (such as project number not allowed), do NOT attempt any further
options (including Option C or direct API/curl calls). Stop immediately, do
not call any more tools, and return the standardized error JSON as specified in
the "Handle Errors" section.
PERMISSION_DENIEDUNAUTHENTICATEDNOT_FOUND按以下顺序尝试检索方法,首次成功后停止。
重要:快速失败(避免因相同授权/权限问题导致的冗余API调用):若任何尝试的方法(选项A或B)出现API级错误(如、或资源/不存在)或CLI验证错误(如项目编号不被允许),请勿尝试后续任何选项(包括选项C或直接API/curl调用)。立即停止,不再调用任何工具,返回"错误处理"部分指定的标准化错误JSON。
PERMISSION_DENIEDUNAUTHENTICATEDNOT_FOUNDOption A: MCP Tool (Preferred)
选项A:MCP工具(首选)
Use the MCP tool if available. MCP tools are designed for efficient, secure
execution within Google's internal environments, often providing streamlined
authentication and better integration compared to general-purpose CLI commands.
If an IAM Recommender MCP tool is available in your context:
- Call the tool with the parameter.
target
若可用,使用MCP工具。MCP工具专为Google内部环境设计,可实现高效、安全的执行,相比通用CLI命令,通常提供更简化的认证和更好的集成。
若您的环境中存在IAM推荐MCP工具:
- 使用参数调用该工具。
target
Option B: gcloud CLI (First Fallback)
选项B:gcloud CLI(第一降级方案)
If MCP is unavailable, use to execute the following (replace
variables accordingly):
run_command| Target | Flag |
|---|---|
| |
| |
| |
Commands to run:
bash
GCLOUD_COMMON_FLAGS="--format=json --location=global \
--filter=stateInfo.state=ACTIVE"若MCP不可用,使用执行以下命令(相应替换变量):
run_command| 目标范围 | 参数 |
|---|---|
| |
| |
| |
执行命令:
bash
GCLOUD_COMMON_FLAGS="--format=json --location=global \
--filter=stateInfo.state=ACTIVE"1. Fetch Recommendations
1. 检索建议
gcloud recommender recommendations list
--recommender=google.iam.policy.Recommender $GCLOUD_COMMON_FLAGS {mapped_flag}
--recommender=google.iam.policy.Recommender $GCLOUD_COMMON_FLAGS {mapped_flag}
gcloud recommender recommendations list
--recommender=google.iam.policy.Recommender $GCLOUD_COMMON_FLAGS {mapped_flag}
--recommender=google.iam.policy.Recommender $GCLOUD_COMMON_FLAGS {mapped_flag}
2. Fetch Insights
2. 检索洞察
gcloud recommender insights list --insight-type=google.iam.policy.Insight
$GCLOUD_COMMON_FLAGS {mapped_flag}
undefinedgcloud recommender insights list --insight-type=google.iam.policy.Insight
$GCLOUD_COMMON_FLAGS {mapped_flag}
undefinedOption C: Google Cloud API (Final Fallback)
选项C:Google Cloud API(最终降级方案)
Only attempt this option if is physically unavailable in the
environment (e.g., ). API client libraries require
more setup and execution overhead, so they are only used as a last resort if CLI
tools are missing. Do NOT use this option if is available but failed
with an API error.
gcloudgcloud: command not foundgcloudUse Google Cloud Recommender API client libraries via a helper script (or direct
API calls if libraries are unavailable) to:
- Call (or
list_recommendations) forrecommendations.list(filter:google.iam.policy.Recommender).stateInfo.state=ACTIVE - Call (or
list_insights) forinsights.list(filter:google.iam.policy.Insight).stateInfo.state=ACTIVE
仅当环境中确实无法使用时(例如提示),才尝试此选项。API客户端库需要更多设置和执行开销,因此仅在CLI工具缺失时作为最后手段使用。若可用但因API错误失败,请勿使用此选项。
gcloudgcloud: command not foundgcloud通过辅助脚本(若库不可用则直接调用API)使用Google Cloud Recommender API客户端库:
- 调用(或
list_recommendations)获取recommendations.list的结果(过滤条件:google.iam.policy.Recommender)。stateInfo.state=ACTIVE - 调用(或
list_insights)获取insights.list的结果(过滤条件:google.iam.policy.Insight)。stateInfo.state=ACTIVE
3. Determine Output Format and Deliver
3. 确定输出格式并交付
CRITICAL: Only proceed to this step if the retrieval in Step 2 was
successful. If the retrieval failed, skip this step and go directly to
Handle Errors.
Before presenting the results, determine the desired output format.
CRITICAL: If the user's initial prompt already specifies the output format
(e.g., "return the raw results in JSON" or "show it in a table"), bypass asking
and proceed directly to that format.
Otherwise, ask the user in a dropdown menu, with the options being:
- JSON file
- Markdown table in chat
Based on the choice (either pre-specified or chosen by the user), deliver the
output:
重要:仅当步骤2的检索成功时,才进入此步骤。若检索失败,跳过此步骤直接跳转至错误处理。
在展示结果前,确定所需的输出格式。
重要:若用户初始请求已指定输出格式(例如"以JSON格式返回原始结果"或"以表格形式展示"),无需询问,直接按指定格式执行。
否则,通过下拉菜单询问用户,选项如下:
- JSON文件
- 聊天中的Markdown表格
根据选择(预先指定或用户选择)交付输出:
Option A: JSON File
选项A:JSON文件
- Write the raw results to a file named
(where
iam_recommendations_<target_id>_<timestamp>.jsonis the sanitized resource identifier and<target_id>is formatted as<timestamp>) in the current working directory.YYYYMMDD_HHMMSS - The file content must match the structure shown in Example Execution.
- Respond to the user with the file path.
- 将原始结果写入当前工作目录下名为的文件(其中
iam_recommendations_<target_id>_<timestamp>.json为清理后的资源标识符,<target_id>格式为<timestamp>)。YYYYMMDD_HHMMSS - 文件内容必须符合示例执行中展示的结构。
- 向用户返回文件路径。
Option B: Chat Table
选项B:聊天表格
- Sort Recommendations: Sort the retrieved recommendations, placing service agent recommendations last in the list.
- Format Table: Format the sorted recommendations into a markdown table.
The table should contain key fields:
- Subtype: The recommender subtype or insight subtype (e.g., indicating if it's for resource-level roles).
- Recommended Action: Summary of the recommendation.
- Rationale: Rationale/justification.
- Associated Insights: The IDs of any linked insights (from
).
associatedInsights
- Limit Chat Display: Display only the top 10 recommendations in the chat table.
- Provide Full List: Save the complete list of recommendations and
insights to a markdown file (e.g.,
, where
iam_recommendations_<target_id>_<timestamp>.mdis the sanitized resource identifier and<target_id>is formatted as<timestamp>) and provide a link for the user to download it.YYYYMMDD_HHMMSS - Format Insights Table: If insights are present, format them in a
separate table in the markdown file (and optionally show a summary in chat
if appropriate, but keep the chat clean). The table should contain key
fields:
- Insight ID: The insight identifier ().
INSIGHT_ID - State: The insight state ().
INSIGHT_STATE - Subtype: The insight subtype ().
INSIGHT_SUBTYPE - Description: Description of the insight ().
DESCRIPTION
- Insight ID: The insight identifier (
- DO NOT provide a JSON file with the raw results if this option is chosen.
- 排序建议:对检索到的建议进行排序,将服务代理建议放在列表最后。
- 格式化表格:将排序后的建议格式化为Markdown表格,需包含以下关键字段:
- 子类型:推荐子类型或洞察子类型(例如,指示是否针对资源级角色)。
- 建议操作:建议摘要。
- 理由:建议的理由/依据。
- 关联洞察:所有关联洞察的ID(来自)。
associatedInsights
- 限制聊天展示数量:仅在聊天表格中显示前10条建议。
- 提供完整列表:将完整的建议和洞察列表保存至Markdown文件(例如,其中
iam_recommendations_<target_id>_<timestamp>.md为清理后的资源标识符,<target_id>格式为<timestamp>),并提供下载链接给用户。YYYYMMDD_HHMMSS - 格式化洞察表格:若存在洞察,在Markdown文件中单独格式化表格(若合适,可在聊天中展示摘要,但需保持聊天界面简洁)。表格需包含以下关键字段:
- 洞察ID:洞察标识符()。
INSIGHT_ID - 状态:洞察状态()。
INSIGHT_STATE - 子类型:洞察子类型()。
INSIGHT_SUBTYPE - 描述:洞察描述()。
DESCRIPTION
- 洞察ID:洞察标识符(
- 请勿在此选项下提供包含原始结果的JSON文件。
4. Example Execution
4. 示例执行
-
Input Target: projects/my-test-project
-
Mapped Flag: --project=my-test-project
-
Action (Option B): Run
gcloud recommender recommendations list --recommender=google.iam.policy.Recommender --format=json --location=global --filter=stateInfo.state=ACTIVE --project=my-test-project -
Expected Output Structure:json
{ "raw_results": { "recommendations": [ { "name": "projects/my-test-project/locations/global/recommenders/ \ google.iam.policy.Recommender/recommendations/123", "content": { ... } } ], "insights": [] }, "error": null }
-
输入目标:projects/my-test-project
-
映射参数:--project=my-test-project
-
操作(选项B):执行
gcloud recommender recommendations list --recommender=google.iam.policy.Recommender --format=json --location=global --filter=stateInfo.state=ACTIVE --project=my-test-project -
预期输出结构:json
{ "raw_results": { "recommendations": [ { "name": "projects/my-test-project/locations/global/recommenders/ \ google.iam.policy.Recommender/recommendations/123", "content": { ... } } ], "insights": [] }, "error": null }
5. Handle Errors
5. 错误处理
CRITICAL: If you encounter any of the error conditions below (during
validation or fetch), stop immediately. Do not attempt to debug, switch
accounts, search the codebase, or verify resource existence. Immediately output
the specified JSON structure as your final response and call no further tools.
If all methods fail, return:
- For incorrect target:
{"raw_results": null, "error": "The specified target resource is incorrect or does not exist."} - For authentication issues:
{"raw_results": null, "error": "User is unauthenticated. Please authenticate (e.g., run 'gcloud auth login')."} - For permissions:
{"raw_results": null, "error": "Insufficient permissions. Please ensure you have 'roles/recommender.iamViewer' on the target scope."} - Other: (Do not mention MCP tool failures to the user).
{"raw_results": null, "error": "Failed to fetch: {error_details}"}
重要:若在验证或检索过程中遇到以下任何错误情况,立即停止。请勿尝试调试、切换账号、搜索代码库或验证资源是否存在。立即输出指定的JSON结构作为最终响应,不再调用任何工具。
若所有方法均失败,返回:
- 目标不正确:
{"raw_results": null, "error": "指定的目标资源不正确或不存在。"} - 认证问题:
{"raw_results": null, "error": "用户未认证。请进行认证(例如执行'gcloud auth login')。"} - 权限不足:
{"raw_results": null, "error": "权限不足。请确保您在目标范围内拥有'roles/recommender.iamViewer'角色。"} - 其他错误:(请勿向用户提及MCP工具失败)
{"raw_results": null, "error": "检索失败: {error_details}"}
Gotchas
注意事项
- State Filter: Always ensure you are filtering for recommendations.
ACTIVE - Location: The location for IAM Recommender is always global.
- 状态过滤:始终确保过滤状态的建议。
ACTIVE - 地域:IAM推荐工具的地域始终为global。