オプション
家 Skill 安全 iam-recommendations-fetcher

iam-recommendations-fetcher

google/skills google/skills

MCPツール、gcloud CLI、またはAPIへの直接呼び出しを使用して、指定された組織、フォルダ、またはプロジェクトについて、Google CloudからIAMの推奨事項とセキュリティに関するインサイトを取得します。

...すべて拡張します
14
更新された時間 2026年9月4日

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/123456789またはorganizations/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} --organization={organization_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. 表のフォーマット:ソートされたレコメンデーションをマークダウン形式の表にフォーマットします。 表には以下の主要フィールドを含める必要があります:
    • サブタイプ:レコメンダーのサブタイプまたはインサイトのサブタイプ(例: リソースレベルのロール向けであるかどうかを示す)。
    • 推奨アクション:推奨事項の概要。
    • 根拠:根拠/正当性。
    • 関連インサイト:リンクされているインサイトの ID( associatedInsights から取得)。
  3. チャット表示の制限:チャット テーブルに上位 10 件の推奨事項のみを表示します。
  4. 完全なリストの提供:推奨事項と インサイトの完全なリストをマークダウンファイルに保存します(例: iam_recommendations__.md。ここで は サニタイズされたリソース識別子であり、 YYYYMMDD_HHMMSS の形式で)として、ユーザーがダウンロードできるリンクを提供します。
  5. インサイト表のフォーマット: インサイトが存在する場合は、それらを マークダウンファイル内の別の表にフォーマットします(必要に応じてチャットに要約を表示しても 構いませんが、チャットは簡潔に保ってください)。表には以下の主要な フィールドを含める必要があります:
    • インサイト 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年7月1日
zeroize-audit
更新された時間 2026年7月1日
device-integrity
更新された時間 2026年6月29日
flutter-use-http-package
更新された時間 2026年6月30日
OR