iam-recommendations-fetcher
google/skills
Ruft IAM-Empfehlungen und Sicherheitsinformationen aus Google Cloud für eine bestimmte Organisation, einen bestimmten Ordner oder ein bestimmtes Projekt ab – entweder mithilfe von MCP-Tools, der gcloud-Befehlszeilenschnittstelle oder durch direkte API-Aufrufe.
...Alle erweiternAbruf von IAM-Empfehlungen
Diese Anleitung enthält Anweisungen zum Abrufen von IAM-Empfehlungen und -Erkenntnissen aus Google Cloud. Sie behandelt die Validierung des Zielbereichs der Eingabe, das Abrufen von Empfehlungen mithilfe von MCP-Tools, gcloud-Befehlen oder direkten API-Aufrufen sowie die Behandlung häufiger API-Fehler.
Vorgehensweisen
1. Eingabeziel überprüfen
Überprüfen Sie den Zielbereich der Eingabe.
Format prüfen: Überprüfen Sie, ob das Ziel einem der folgenden Formate entspricht:
organizations/{org_id}Ordner/{ordner_id}projects/{project_id}
Umgang mit mehrdeutigen/unformatierten Zielen: Wenn der Benutzer nur eine unformatierte ID (ohne das Präfix) angibt:
- Alphanumerisch (beginnt mit einem Buchstaben): Gehen Sie davon aus, dass es sich um eine Projekt-ID handelt.
Formatieren Sie sie als
projects/{project_id}und fahren Sie fort. - Rein numerisch: Die Angabe ist mehrdeutig (könnte eine Organisations-, Ordner- oder
Projektnummer sein).
- Bitten Sie den Benutzer, den Ressourcentyp zu präzisieren: > „Ist die Ziel-ID ‚{provided_id}‘ eine Organisation, ein Ordner oder ein Projekt?“
- Sobald der Benutzer eine Angabe gemacht hat, formatieren Sie den Zielbereich entsprechend (z. B.
mit dem Präfix
organizations/,folders/oderprojects/) und fahren Sie fort. - Wenn die Antwort des Benutzers ungültig ist oder er keine Klarstellung vornehmen kann, behandeln Sie dies als Fehler und fahren Sie mit „Fehlerbehandlung“ fort (falsches Ziel).
- Alphanumerisch (beginnt mit einem Buchstaben): Gehen Sie davon aus, dass es sich um eine Projekt-ID handelt.
Formatieren Sie sie als
Umgang mit Projektnummern: Wenn das Ziel ein Projekt ist, aber eine rein numerische ID (Projektnummer) anstelle einer Projekt-ID verwendet (z. B.
projects/123456789):- erfordern
„gcloudrecommender“-Befehle eine Projekt-ID. Versuchen Sie, die Projektnummer in eine Projekt-ID aufzulösen, indem Sie Folgendes verwenden:gcloud projects list --filter="projectNumber={project_number}" --format="value(projectId)" - Wenn diese Auflösung leer zurückgibt oder mit einem Berechtigungsfehler fehlschlägt, versuche nicht, das Projekt zu beschreiben, die Codebasis zu durchsuchen oder nach Mock-Daten zu suchen. Gib sofort das in „Behandlung von Fehlern“ angegebene standardisierte Fehler-JSON zurück und beende die Ausführung (rufe keine weiteren Tools auf).
- erfordern
Validierung der Aufzeichnung: Geben Sie den validierten und formatierten Zielbereich (z. B.
projects/123456789oderorganizations/123456789012) ausdrücklich in Ihrer Begründung an, bevor Sie mit dem Abrufschritt fortfahren.
2. Abruf von Empfehlungen und Erkenntnissen (Fallback-Ablauf)
Versuchen Sie die folgenden Abrufmethoden der Reihe nach. Brechen Sie beim ersten Erfolg ab.
KRITISCH: Bei Fehlern schnell abbrechen (um redundante API-Aufrufe zu vermeiden, die
aus denselben Autorisierungs-/Berechtigungsgründen fehlschlagen): Wenn eine versuchte Methode (Option
A oder Option B) mit einem Fehler auf API-Ebene (z. B. PERMISSION_DENIED,
UNAUTHENTICATED oder wenn die Ressource NOT_FOUND ist bzw. nicht existiert) oder einem CLI-Validierungsfehler
(z. B. unzulässige Projektnummer) fehlschlägt, versuchen Sie KEINE weiteren
Optionen (einschließlich Option C oder direkter API-/curl-Aufrufe). Beenden Sie den Vorgang sofort,
rufen Sie keine weiteren Tools auf und geben Sie das standardisierte Fehler-JSON zurück, wie im
Abschnitt „Fehlerbehandlung“ angegeben.
Option A: MCP-Tool (bevorzugt)
Verwenden Sie das MCP-Tool, sofern verfügbar. MCP-Tools sind für die effiziente und sichere Ausführung in den internen Umgebungen von Google konzipiert und bieten oft eine optimierte Authentifizierung sowie eine bessere Integration im Vergleich zu allgemeinen CLI-Befehlen.
Falls in Ihrem Kontext ein IAM Recommender-MCP-Tool verfügbar ist:
- Rufen Sie das Tool mit dem Parameter
„target“auf.
Option B: gcloud-CLI (erste Ausweichmöglichkeit)
Wenn MCP nicht verfügbar ist, führen Sie mit „run_command“ Folgendes aus (ersetzen Sie
die Variablen entsprechend):
| Ziel | Flag |
|---|---|
projects/{project_id} |
--project={project_id} |
folders/{folder_id} |
--Ordner={Ordner-ID} |
Organisationen/{organization_id} |
--organisation={organisation_id} |
Auszuführende Befehle:
GCLOUD_COMMON_FLAGS="--format=json --location=global \
--filter=stateInfo.state=ACTIVE"
# 1. Empfehlungen abrufen
gcloud recommender recommendations list \
--recommender=google.iam.policy.Recommender $GCLOUD_COMMON_FLAGS {mapped_flag}
# 2. Insights abrufen
gcloud recommender insights list --insight-type=google.iam.policy.Insight
$GCLOUD_COMMON_FLAGS {mapped_flag}
Option C: Google Cloud-API (letzter Ausweg)
Versuchen Sie diese Option nur, wenn „gcloud“ in der
Umgebung physisch nicht verfügbar ist (z. B. „gcloud: Befehl nicht gefunden“). API-Client-Bibliotheken erfordern
einen höheren Einrichtungs- und Ausführungsaufwand und werden daher nur als letzter Ausweg verwendet, wenn CLI-Tools
fehlen. Verwenden Sie diese Option NICHT, wenn „gcloud“ verfügbar ist, aber
mit einem API-Fehler fehlgeschlagen ist.
Verwenden Sie die Google Cloud Recommender-API-Client-Bibliotheken über ein Hilfsskript (oder direkte API-Aufrufe, falls keine Bibliotheken verfügbar sind), um:
- Rufen Sie
`list_recommendations` (oder`recommendations.list`) für`google.iam.policy.Recommender` auf (Filter: `stateInfo.state=ACTIVE`). - Rufen Sie
`list_insights` (oder`insights.list`) für`google.iam.policy.Insight` auf (Filter: `stateInfo.state=ACTIVE`).
3. Ausgabeformat festlegen und bereitstellen
WICHTIG: Fahren Sie nur dann mit diesem Schritt fort, wenn der Abruf in Schritt 2 erfolgreich war. Wenn der Abruf fehlgeschlagen ist, überspringen Sie diesen Schritt und fahren Sie direkt mit „Fehlerbehandlung“ fort.
Legen Sie vor der Darstellung der Ergebnisse das gewünschte Ausgabeformat fest.
WICHTIG: Wenn in der ursprünglichen Eingabeaufforderung des Benutzers bereits das Ausgabeformat angegeben ist (z. B. „die Rohdaten in JSON zurückgeben“ oder „in einer Tabelle anzeigen“), überspringe die Abfrage und fahre direkt mit diesem Format fort.
Andernfalls fragen Sie den Benutzer über ein Dropdown-Menü ab, wobei folgende Optionen zur Auswahl stehen:
- JSON-Datei
- Markdown-Tabelle im Chat
Je nach Auswahl (entweder vorab festgelegt oder vom Benutzer gewählt) liefern Sie die Ausgabe:
Option A: JSON-Datei
- Schreiben Sie die Rohdaten in eine Datei mit dem Namen
iam_recommendations_(wobei_ .json der bereinigte Ressourcenbezeichner ist undim FormatYYYYMMDD_HHMMSS) im aktuellen Arbeitsverzeichnis. - Der Inhalt der Datei muss der in „Beispielausführung“ dargestellten Struktur entsprechen.
- Geben Sie dem Benutzer den Dateipfad als Antwort zurück.
Option B: Chat-Tabelle
- Empfehlungen sortieren: Sortieren Sie die abgerufenen Empfehlungen so, dass die Empfehlungen der Service-Agenten am Ende der Liste stehen.
- Tabelle formatieren: Formatieren Sie die sortierten Empfehlungen als Markdown-Tabelle.
Die Tabelle sollte folgende Schlüsselfelder enthalten:
- Untertyp: Der Untertyp des Empfehlungssystems oder der Erkenntnis (z. B. als Angabe, ob es sich um Rollen auf Ressourcenebene handelt).
- Empfohlene Maßnahme: Zusammenfassung der Empfehlung.
- Begründung: Begründung/Rechtfertigung.
- Zugehörige Erkenntnisse: Die IDs aller verknüpften Erkenntnisse (aus
„associatedInsights“).
- Anzeige im Chat einschränken: Nur die 10 besten Empfehlungen in der Chat-Tabelle anzeigen .
- Vollständige Liste bereitstellen: Speichern Sie die vollständige Liste der Empfehlungen und
Erkenntnisse in einer Markdown-Datei (z. B.
iam_recommendations_, wobei_ .md die bereinigte Ressourcen-ID ist undim FormatJJJJMMTT_HHMMSSformatiert ist) und stellen Sie dem Benutzer einen Link zum Herunterladen bereit. - Tabelle mit Erkenntnissen formatieren: Falls Erkenntnisse vorliegen, formatieren Sie diese in einer
separaten Tabelle in der Markdown-Datei (und zeigen Sie optional eine Zusammenfassung im Chat an,
sofern dies angemessen ist, halten Sie den Chat jedoch übersichtlich). Die Tabelle sollte folgende
Schlüsselfelder enthalten:
- Einblicks-ID: Die Kennung des Einblicks (
INSIGHT_ID). - Status: Der Status der Erkenntnis (
INSIGHT_STATE). - Untertyp: Der Insight-Untertyp (
INSIGHT_SUBTYPE). - Beschreibung: Beschreibung der Erkenntnis (
DESCRIPTION).
- Einblicks-ID: Die Kennung des Einblicks (
- Stellen Sie KEINE JSON-Datei mit den Rohdaten bereit, wenn diese Option ausgewählt ist.
4. Ausführungsbeispiel
Eingabeziel: projects/my-test-project
Zugeordnetes Flag: --project=my-test-project
Aktion (Option B): Führen Sie
„gcloud recommender recommendations list --recommender=google.iam.policy.Recommender --format=json --location=global --filter=stateInfo.state=ACTIVE --project=my-test-project“ausErwartete Ausgabestruktur:
{ "raw_results": { "recommendations": [ { "name": "projects/my-test-project/locations/global/recommenders/ \ google.iam.policy.Recommender/recommendations/123", "content": { ... } } ], "insights": [] }, "error": null }
5. Fehlerbehandlung
KRITISCH: Wenn eine der folgenden Fehlerbedingungen auftritt (während der Validierung oder beim Abruf), brechen Sie den Vorgang sofort ab. Versuchen Sie nicht, den Fehler zu beheben, das Konto zu wechseln, den Code zu durchsuchen oder die Existenz der Ressource zu überprüfen. Geben Sie sofort die angegebene JSON-Struktur als endgültige Antwort aus und rufen Sie keine weiteren Tools auf.
Wenn alle Methoden fehlschlagen, gib Folgendes zurück:
- Bei falschem Ziel:
{"raw_results": null, "error": "Die angegebene Zielressource ist falsch oder existiert nicht."} - Bei Authentifizierungsproblemen:
{"raw_results": null, "error": "Der Nutzer ist nicht authentifiziert. Bitte authentifizieren Sie sich (z. B. mit dem Befehl 'gcloud auth login')."} - Bei Berechtigungsproblemen:
{"raw_results": null, "error": "Unzureichende Berechtigungen. Bitte stellen Sie sicher, dass Sie über die Rolle 'roles/recommender.iamViewer' im Zielbereich verfügen."} - Sonstiges:
{"raw_results": null, "error": "Abruf fehlgeschlagen: {error_details}"}(Weisen Sie den Nutzer nicht auf Fehler des MCP-Tools hin).
Zu beachtende Punkte
- Statusfilter: Stellen Sie stets sicher, dass Sie nach
AKTIVENEmpfehlungen filtern. - Standort: Der Standort für den IAM Recommender ist immer global.
---
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.
Alle Dateien
0 Dateieniam-recommendations-fetcher installieren
Laden Sie die Skill-Dateien herunter und entpacken Sie sie in Ihr Verzeichnis „.claude/skills/“.
ZIP herunterladenKlonen Sie das Repository und kopieren Sie die Skill-Dateien in Ihr Projekt.
git clone https://github.com/google/skills/tree/main/skills/cloud/iam-recommendations-fetcher # Copy SKILL.md to your .claude/skills/ directory
Kopieren





Heim
