옵션
집 Skill 보안 iam-recommendations-fetcher

iam-recommendations-fetcher

google/skills google/skills

MCP 도구, gcloud CLI 또는 직접 API 호출을 사용하여 지정된 조직, 폴더 또는 프로젝트에 대한 IAM 권장 사항 및 보안 인사이트를 Google Cloud에서 가져옵니다.

...모든 것을 확장하십시오
14
업데이트 된 시간 2026년 9월 4일

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):

    • gcloud recommender 명령어는 프로젝트 ID를 필요로 합니다. 다음 명령어를 사용하여 프로젝트 번호를 프로젝트 ID로 변환해 보십시오: gcloud projects list --filter="projectNumber={project_number}" --format="value(projectId)"
    • 이 변환 결과가 비어 있거나 권한 오류로 실패하는 경우, 프로젝트 설명, 코드베이스 검색 또는 모의 데이터 검색을 시도하지 마십시오. 즉시 ‘오류 처리’에 명시된 표준화된 오류 JSON을 반환하고 실행을 중지하십시오(더 이상 도구를 호출하지 마십시오).
  4. 기록 유효성 검사: 가져오기 단계로 진행하기 전에, 생각/추론 과정에 유효성이 검증되고 형식이 지정된 대상 범위(예: projects/123456789 또는 organizations/123456789012)를 명시적으로 기재하십시오.

2. 권장 사항 및 인사이트 가져오기(대체 흐름)

다음 검색 방법을 순서대로 시도하십시오. 첫 번째 성공 시 중단하십시오.

중요: 오류 발생 시 즉시 중단하십시오 (동일한 인증/권한 문제로 실패할 중복된 API 호출을 방지하기 위해): 시도한 방법(옵션 A 또는 옵션 B) 중 어느 하나라도 API 수준 오류(예: PERMISSION_DENIED, UNAUTHENTICATED, 또는 리소스 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. google.iam.policy.Recommender에 대해 list_recommendations (또는 recommendations.list) 호출합니다 (필터: stateInfo.state=ACTIVE).
  2. google.iam.policy.Insight에 대해 list_insights (또는 insights.list) 호출합니다(필터: stateInfo.state=ACTIVE).

3. 출력 형식 결정 및 전달

중요: 2단계의 검색이 성공한 경우에만 이 단계로 진행하십시오. 검색이 실패한 경우, 이 단계를 건너뛰고 '오류 처리'로 바로 이동하십시오.

결과를 표시하기 전에 원하는 출력 형식을 결정하십시오.

중요: 사용자의 초기 요청에 이미 출력 형식이 명시되어 있는 경우 (예: “JSON 형식으로 원본 결과를 반환해 주세요” 또는 “표로 표시해 주세요”), 사용자에게 다시 묻지 말고 해당 형식으로 바로 진행하십시오.

그렇지 않은 경우, 드롭다운 메뉴를 통해 사용자에게 다음 옵션 중 하나를 선택하도록 요청하십시오:

  1. JSON 파일
  2. 채팅 내 마크다운 테이블

선택 사항(사전 지정된 것 또는 사용자가 선택한 것)에 따라 출력 결과를 제공합니다:

옵션 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 레코멘더의 위치는 항상 전역입니다.
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