選項
首頁首頁 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}
    • folders/{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}
組織/{organization_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. 針對google.iam.policy.Insight呼叫list_insights(或insights.list) (篩選條件: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