选项
首页首页 Skill 安全 iam-recommendations-fetcher

iam-recommendations-fetcher

google/skills google/skills

使用 MCP 工具、gcloud CLI 或直接调用 API,从 Google Cloud 获取针对指定组织、文件夹或项目的 IAM 建议和安全洞察。

...展开全部
14
更新时间 2026-09-04

IAM 建议检索

本技能提供了从 Google Cloud 获取 IAM 建议和洞察的指导 。内容涵盖验证输入目标范围、使用 MCP 工具、gcloud 命令或直接调用 API 来 检索建议,以及 处理常见的 API 错误。

操作步骤

1. 验证输入目标

验证输入目标范围。

  1. 检查格式:确认目标是否符合以下格式之一:

    • organizations/{org_id}
    • 文件夹/{folder_id}
    • projects/{project_id}
  2. 处理模糊/原始目标:如果用户仅提供原始 ID(没有 前缀):

    • 字母数字(以字母开头):假定其为项目 ID。 将其格式化为projects/{project_id}并继续处理。
    • 纯数字:存在歧义(可能是组织、文件夹或 项目编号)。
      • 请用户澄清资源类型:> “目标 ID '{provided_id}' 是组织、文件夹还是项目?”
      • 一旦用户指定,请相应地格式化目标范围(例如, 在前面添加organizations/folders/projects/),然后继续。
      • 如果用户的回答无效或无法澄清,则将其 视为错误,并转至“处理错误” (目标不正确)。
  3. 处理项目编号:如果目标是项目,但使用的是纯 数字 ID(项目编号)而非项目 ID(例如, projects/123456789):

    • gcloudrecommender 命令需要项目 ID。请尝试使用以下命令将 项目编号解析为项目 ID:gcloud projects list --filter="projectNumber={project_number}" --format="value(projectId)"
    • 如果此解析返回空结果或因权限错误而失败,请 不要尝试描述该项目、搜索代码库或搜索 模拟数据。立即返回“处理错误”中指定的标准化错误 JSON, 并停止执行(不要再调用任何 其他工具)。
  4. 记录验证:在进入获取步骤之前,请在您的 思路/推理中明确说明经过验证且格式正确的 目标范围(例如,projects/123456789organizations/123456789012)。

2. 获取建议和洞察(备用流程)

按顺序尝试以下检索方法。一旦成功即停止。

关键:出现错误时快速终止(以避免因相同的授权/权限原因导致失败的 冗余 API 调用):如果任何尝试的方法(选项 A 或选项 B)因 API 级错误(例如PERMISSION_DENIEDUNAUTHENTICATED,或资源NOT_FOUND/ 不存在)或 CLI 验证 错误(例如项目编号不允许),请不要尝试任何后续 选项(包括选项 C 或直接 API/curl 调用)。 请立即停止操作, 不要再调用任何工具,并返回“处理错误”部分中规定的 标准化错误 JSON。

选项 A:MCP 工具(推荐)

如果可用,请使用 MCP 工具。MCP 工具旨在在 Google 内部环境中高效、安全地 运行,与通用 CLI 命令相比,通常提供简化的 身份验证流程和更好的集成能力。

如果您的环境中提供了 IAM Recommender MCP 工具:

  • 请使用target参数调用该工具。

选项 B:gcloud CLI(首选备选方案)

如果无法使用 MCP,请使用run_command执行以下命令(请 根据实际情况替换变量):

Target 标志
projects/{project_id} --project={project_id}
folders/{folder_id} --文件夹={文件夹_id}
组织/{组织_id} --组织={组织_id}

要执行的命令

GCLOUD_COMMON_FLAGS="--format=json --location=global \
--filter=stateInfo.state=ACTIVE"

# 1. 获取推荐结果
gcloud recommender recommendations list \
--recommender=google.iam.policy.Recommender $GCLOUD_COMMON_FLAGS {mapped_flag}

# 2. 获取洞察
gcloud recommender insights list --insight-type=google.iam.policy.Insight
$GCLOUD_COMMON_FLAGS {mapped_flag}

方案 C:Google Cloud API(最终备选方案)

仅当环境中gcloud物理不可用时 才尝试此选项(例如,gcloud:命令未找到)。API 客户端库需要 更多的配置和执行开销,因此仅在缺少 CLI 工具时作为最后手段使用。 如果gcloud可用但因 API 错误而失败, 请勿使用此选项。

通过辅助脚本(或在库不可用时直接 调用 API)使用 Google Cloud Recommender API 客户端库来:

  1. 调用list_recommendations(或recommendations.list)以获取 google.iam.policy.Recommender(过滤条件:stateInfo.state=ACTIVE)。
  2. 调用list_insights(或insights.list)以获取google.iam.policy.Insight (筛选条件:stateInfo.state=ACTIVE)。

3. 确定输出格式并交付

关键:仅当步骤 2 的检索 成功时,才继续执行此步骤。如果检索失败,请跳过此步骤并直接转至 “处理错误”。

在呈现结果之前,请确定所需的输出格式。

关键:如果用户的初始提示已指定输出格式 (例如,“以 JSON 格式返回原始结果”或“以表格形式显示”),则无需询问 ,直接采用该格式。

否则,请通过下拉菜单向用户询问,选项包括:

  1. JSON 文件
  2. 聊天中的 Markdown 表格

根据选择(无论是预先指定的还是用户选择的),提供 输出:

选项 A:JSON 文件

  1. 将原始结果写入名为 iam_recommendations__.json的文件(其中 表示 经过安全处理的资源标识符,且 格式为 YYYYMMDD_HHMMSS)的文件中。
  2. 文件内容必须与 “执行示例”中所示的结构一致。
  3. 向用户返回该文件路径。

选项 B:聊天表

  1. 排序推荐:对检索到的推荐进行排序,将 服务代理的推荐置于列表末尾。
  2. 表格格式:将排序后的推荐结果格式化为 Markdown 表格。 该表格应包含以下关键字段:
    • 子类型:推荐系统的子类型或洞察的子类型(例如, 用于标明是否针对资源级角色)。
    • 推荐操作:推荐内容的摘要。
    • 理由:理由/依据。
    • 关联洞察:任何关联洞察的 ID(来自 associatedInsights)。
  3. 限制聊天显示:仅在聊天 表格中显示前 10 条推荐。
  4. 提供完整列表:将推荐和 洞察的完整列表保存到 Markdown 文件中(例如: iam_recommendations__.md,其中 是 经过安全处理的资源标识符,且 格式为 YYYYMMDD_HHMMSS),并为用户提供下载链接。
  5. 格式化洞察表:如果存在洞察,请将其格式化为 Markdown 文件中的一个单独表格(并在适当情况下可选地在聊天中 显示摘要,但需保持聊天内容简洁)。该表格应包含以下关键 字段:
    • 洞察 ID:洞察标识符(INSIGHT_ID)。
    • 状态:洞察状态(INSIGHT_STATE)。
    • 子类型:洞察子类型(INSIGHT_SUBTYPE)。
    • 描述:洞察的描述(DESCRIPTION)。
  6. 如果选择了此选项,请 不要提供包含原始结果的 JSON 文件。

4. 执行示例

  • 输入目标: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

  • 预期输出结构

    {
      "raw_results": {
        "recommendations": [
          {
            "name": "projects/my-test-project/locations/global/recommenders/ \
            google.iam.policy.Recommender/recommendations/123",
            "content": { ... }
          }
        ],
        "insights": []
      },
      "error": null
    }
    

5. 处理错误

严重警告:若遇到以下任何错误情况(在 验证或获取数据期间),请立即停止操作。切勿尝试调试、切换 账户、搜索代码库或验证资源是否存在。请立即输出 指定的 JSON 结构作为最终响应,且不再调用任何其他工具。

如果所有方法均失败,请返回:

  • 目标不正确时:{"raw_results": null, "error": "指定的目标资源不正确或不存在。"}
  • 身份验证问题:{"raw_results": null, "error": "用户未通过身份验证。请进行身份验证(例如,运行 'gcloud auth login')。"}
  • 权限问题:{"raw_results": null, "error": "权限不足。请确保您在目标作用域中拥有 'roles/recommender.iamViewer' 角色。"}
  • 其他情况:{"raw_results": null, "error": "无法获取:{error_details}"} (请勿向用户提及 MCP 工具故障)。

注意事项

  • 状态过滤器:请始终确保您过滤的是“ACTIVE” 状态的推荐项。
  • 位置:IAM Recommender 的位置始终为全局。
在 GitHub 上查看
---
name: iam-recommendations-fetcher
description: Fetches IAM recommendations and security insights from Google Cloud for a specified organization, folder, or project, using MCP tools, gcloud CLI, or direct API calls.
---

# IAM Recommendations Retrieval

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.

## Procedures

### 1. Validate Input Target

Verify the input target scope.

1.  **Check Format**: Check if the target matches one of these formats:

    *   `organizations/{org_id}`
    *   `folders/{folder_id}`
    *   `projects/{project_id}`

2.  **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 `projects/{project_id}` and proceed.
    *   **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/`, `folders/`, or `projects/`) and proceed.
        *   If the user's response is invalid or they cannot clarify, treat it
            as an error and proceed to [Handle Errors](#5-handle-errors)
            (incorrect target).

3.  **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`):

    *   `gcloud` recommender commands require a Project ID. Attempt to resolve
        the Project Number to a Project ID using: `gcloud 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](#5-handle-errors) and stop execution (do not call any
        more tools).

4.  **Record Validation**: Explicitly state the validated and formatted target
    scope (e.g., `projects/123456789` or `organizations/123456789012`) in your
    thought/reasoning before proceeding to the fetch step.

### 2. Fetch Recommendations and Insights (Fallback Flow)

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 `PERMISSION_DENIED`,
`UNAUTHENTICATED`, or resource `NOT_FOUND` / 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.

#### Option A: MCP Tool (Preferred)

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 `target` parameter.

#### Option B: gcloud CLI (First Fallback)

If MCP is unavailable, use `run_command` to execute the following (replace
variables accordingly):

Target                            | Flag
:-------------------------------- | :---------------------------------
`projects/{project_id}`           | `--project={project_id}`
`folders/{folder_id}`             | `--folder={folder_id}`
`organizations/{organization_id}` | `--organization={organization_id}`

**Commands to run**:

```bash
GCLOUD_COMMON_FLAGS="--format=json --location=global \
--filter=stateInfo.state=ACTIVE"

# 1. Fetch Recommendations
gcloud recommender recommendations list \
--recommender=google.iam.policy.Recommender $GCLOUD_COMMON_FLAGS {mapped_flag}

# 2. Fetch Insights
gcloud recommender insights list --insight-type=google.iam.policy.Insight
$GCLOUD_COMMON_FLAGS {mapped_flag}
```

#### Option C: Google Cloud API (Final Fallback)

Only attempt this option if `gcloud` is physically unavailable in the
environment (e.g., `gcloud: command not found`). 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 `gcloud` is available but failed
with an API error.

Use Google Cloud Recommender API client libraries via a helper script (or direct
API calls if libraries are unavailable) to:

1.  Call `list_recommendations` (or `recommendations.list`) for
    `google.iam.policy.Recommender` (filter: `stateInfo.state=ACTIVE`).
2.  Call `list_insights` (or `insights.list`) for `google.iam.policy.Insight`
    (filter: `stateInfo.state=ACTIVE`).

### 3. Determine Output Format and Deliver

**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](#5-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:

1.  JSON file
2.  Markdown table in chat

Based on the choice (either pre-specified or chosen by the user), deliver the
output:

#### Option A: JSON File

1.  Write the raw results to a file named
    `iam_recommendations_<target_id>_<timestamp>.json` (where `<target_id>` is
    the sanitized resource identifier and `<timestamp>` is formatted as
    `YYYYMMDD_HHMMSS`) in the current working directory.
2.  The file content must match the structure shown in
    [Example Execution](#4-example-execution).
3.  Respond to the user with the file path.

#### Option B: Chat Table

1.  **Sort Recommendations**: Sort the retrieved recommendations, placing
    service agent recommendations last in the list.
2.  **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`).
3.  **Limit Chat Display**: Display only the top 10 recommendations in the chat
    table.
4.  **Provide Full List**: Save the complete list of recommendations and
    insights to a markdown file (e.g.,
    `iam_recommendations_<target_id>_<timestamp>.md`, where `<target_id>` is the
    sanitized resource identifier and `<timestamp>` is formatted as
    `YYYYMMDD_HHMMSS`) and provide a link for the user to download it.
5.  **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`).
6.  **DO NOT** provide a JSON file with the raw results if this option is
    chosen.

### 4. Example Execution

*   **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
    }
    ```

### 5. Handle Errors

**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: `{"raw_results": null, "error": "Failed to fetch: {error_details}"}`
    (Do not mention MCP tool failures to the user).

## Gotchas

*   **State Filter**: Always ensure you are filtering for `ACTIVE`
    recommendations.
*   **Location**: The location for IAM Recommender is always global.

所有文件

0 个文件

安装 iam-recommendations-fetcher

下载技能文件并将其解压到 .claude/skills/ 目录中。

下载ZIP

克隆仓库并复制技能文件到您的项目中。

git clone https://github.com/google/skills/tree/main/skills/cloud/iam-recommendations-fetcher # Copy SKILL.md to your .claude/skills/ directory

复制 复制
快速设置: 将技能文件夹复制到 .claude/skills/ Claude 将自动检测并使用该技能
仓库 google/skills

相关技能

gmgn-portfolio
更新时间 2026-07-01
zeroize-audit
更新时间 2026-07-01
device-integrity
更新时间 2026-06-29
flutter-use-http-package
更新时间 2026-06-30
OR