iam-recommendations-fetcher
google/skills
Obtiene recomendaciones de IAM e información de seguridad de Google Cloud para una organización, carpeta o proyecto específicos, utilizando las herramientas de MCP, la CLI de gcloud o llamadas directas a la API.
...Expandir todoRecuperación de recomendaciones de IAM
Esta habilidad ofrece instrucciones para obtener recomendaciones e información de IAM de Google Cloud. Abarca la validación del ámbito de destino de entrada, la recuperación de recomendaciones mediante herramientas de MCP, comandos de gcloud o llamadas directas a la API, y la gestión de errores comunes de la API.
Procedimientos
1. Validar el ámbito de destino introducido
Comprueba el ámbito del objetivo de entrada.
Comprueba el formato: comprueba si el objetivo se ajusta a uno de estos formatos:
organizations/{org_id}carpetas/{id_carpeta}proyectos/{project_id}
Tratamiento de destinos ambiguos o sin formato: Si el usuario proporciona únicamente un ID sin formato (sin el prefijo):
- Alfanumérico (comienza con una letra): Se considera que es un ID de proyecto.
Se le aplica el formato
projects/{project_id}y se continúa. - Puramente numérico: es ambiguo (podría ser el número de una organización, una carpeta o
un proyecto).
- Pide al usuario que aclare el tipo de recurso: > «¿El ID de destino '{provided_id}' es una organización, una carpeta o un proyecto?»
- Una vez que el usuario lo haya especificado, formatea el ámbito de destino en consecuencia (p. ej.,
añade
organizations/,folders/oprojects/al principio) y continúa. - Si la respuesta del usuario no es válida o no puede aclararlo, trátalo como un error y pasa a «Gestionar errores» (destino incorrecto).
- Alfanumérico (comienza con una letra): Se considera que es un ID de proyecto.
Se le aplica el formato
Gestión de números de proyecto: Si el destino es un proyecto pero utiliza un ID puramente numérico (número de proyecto) en lugar de un ID de proyecto (p. ej.,
projects/123456789):- los comandos
de gcloudrecommender requieren un ID de proyecto. Intenta resolver el número de proyecto en un ID de proyecto utilizando:gcloud projects list --filter="projectNumber={project_number}" --format="value(projectId)" - Si esta resolución devuelve un resultado vacío o falla con un error de permisos, no intentes describir el proyecto, buscar en el código fuente ni buscar datos simulados. Devuelve inmediatamente el JSON de error estandarizado especificado en «Gestión de errores» y detén la ejecución (no llames a ninguna herramienta más).
- los comandos
Validación del registro: Indica explícitamente el ámbito de destino validado y formateado (por ejemplo,
projects/123456789uorganizations/123456789012) en tu razonamiento antes de pasar al paso de obtención.
2. Obtención de recomendaciones e información (flujo alternativo)
Intenta los siguientes métodos de recuperación en orden. Detente ante el primer éxito.
CRÍTICO: Detén rápidamente el proceso ante errores (para evitar llamadas a la API redundantes que fallarán
por los mismos motivos de autorización o permisos): si cualquier método intentado (Opción
A u Opción B) falla con un error a nivel de la API (como PERMISSION_DENIED,
UNAUTHENTICATED o un recurso NOT_FOUND / que no existe) o un error de validación de la CLI
(como un número de proyecto no válido), NO intentes ninguna otra
opción (incluidas la Opción C o las llamadas directas a la API/curl). Deténgase inmediatamente,
no llame a más herramientas y devuelva el JSON de error estandarizado tal y como se especifica en
la sección «Gestión de errores».
Opción A: Herramienta MCP (recomendada)
Utilice la herramienta MCP si está disponible. Las herramientas MCP están diseñadas para una ejecución eficiente y segura dentro de los entornos internos de Google, y suelen ofrecer una autenticación simplificada y una mejor integración en comparación con los comandos de la CLI de uso general.
Si en tu contexto hay disponible una herramienta MCP de IAM Recommender:
- Invoca la herramienta con el parámetro
«target».
Opción B: CLI de gcloud (primera alternativa)
Si MCP no está disponible, utiliza run_command para ejecutar lo siguiente (sustituye
las variables según corresponda):
| Destino | Indicador |
|---|---|
projects/{project_id} |
--project={project_id} |
carpetas/{id_carpeta} |
--carpeta={id_carpeta} |
organizaciones/{id_organización} |
--organización={id_organización} |
Comandos a ejecutar:
GCLOUD_COMMON_FLAGS="--format=json --location=global \
--filter=stateInfo.state=ACTIVE"
# 1. Obtener recomendaciones
gcloud recommender recommendations list \
--recommender=google.iam.policy.Recommender $GCLOUD_COMMON_FLAGS {mapped_flag}
# 2. Obtener información detallada
gcloud recommender insights list --insight-type=google.iam.policy.Insight
$GCLOUD_COMMON_FLAGS {mapped_flag}
Opción C: API de Google Cloud (solución de último recurso)
Prueba esta opción solo si gcloud no está físicamente disponible en el
entorno (por ejemplo, «gcloud: comando no encontrado»). Las bibliotecas de cliente de la API requieren
más configuración y una mayor sobrecarga de ejecución, por lo que solo se utilizan como último recurso si faltan las herramientas de la CLI
. NO utilices esta opción si gcloud está disponible pero ha fallado
con un error de API.
Utiliza las bibliotecas cliente de la API de Google Cloud Recommender mediante un script auxiliar (o llamadas directas a la API si las bibliotecas no están disponibles) para:
- Llamar a
list_recommendations(orecommendations.list) paragoogle.iam.policy.Recommender(filtro:stateInfo.state=ACTIVE). - Llamar a
list_insights(oinsights.list) paragoogle.iam.policy.Insight(filtro:stateInfo.state=ACTIVE).
3. Determinar el formato de salida y entregar
IMPORTANTE: Solo continúe con este paso si la recuperación del paso 2 se ha realizado correctamente. Si la recuperación ha fallado, omita este paso y vaya directamente a Gestionar errores.
Antes de presentar los resultados, determina el formato de salida deseado.
CRÍTICO: Si la solicitud inicial del usuario ya especifica el formato de salida (por ejemplo, «devolver los resultados sin procesar en JSON» o «mostrarlos en una tabla»), omite la pregunta y pasa directamente a ese formato.
De lo contrario, pregúntale al usuario mediante un menú desplegable, con las siguientes opciones:
- Archivo JSON
- Tabla Markdown en el chat
En función de la elección (ya sea preestablecida o seleccionada por el usuario), entrega la salida:
Opción A: Archivo JSON
- Escribe los resultados sin procesar en un archivo denominado
iam_recommendations_(donde_ .json es el identificador del recurso depurado ytiene el formatoAAAAMMDD_HHMMSS) en el directorio de trabajo actual. - El contenido del archivo debe coincidir con la estructura que se muestra en «Ejemplo de ejecución».
- Responde al usuario con la ruta del archivo.
Opción B: Tabla de chat
- Ordenar recomendaciones: Ordena las recomendaciones recuperadas, colocando las recomendaciones de los agentes de servicio al final de la lista.
- Formato de la tabla: Da formato a las recomendaciones ordenadas en una tabla Markdown.
La tabla debe contener los campos clave:
- Subtipo: el subtipo del sistema de recomendación o el subtipo de información (por ejemplo, indicando si es para roles a nivel de recursos).
- Acción recomendada: Resumen de la recomendación.
- Justificación:Razones o fundamentación.
- Informes asociados: Los ID de cualquier informe vinculado (de
associatedInsights).
- Limitar la visualización en el chat: Mostrar solo las 10 recomendaciones principales en la tabla del chat.
- Proporcionar la lista completa: Guardar la lista completa de recomendaciones e
informaciones en un archivo Markdown (p. ej.,
iam_recommendations_, donde_ .md es el identificador de recurso depurado ytiene el formatoAAAAAMMDD_HHMMSS) y proporcionar un enlace para que el usuario pueda descargarla. - Dar formato a la tabla de información: Si hay información disponible, preséntala en una
tabla independiente dentro del archivo Markdown (y, opcionalmente, muestra un resumen en el chat
si procede, pero mantén el chat ordenado). La tabla debe contener los siguientes
campos clave:
- ID de información: El identificador de la información (
INSIGHT_ID). - Estado: el estado de la información (
INSIGHT_STATE). - Subtipo: el subtipo del dato (
INSIGHT_SUBTYPE). - Descripción: Descripción del dato (
DESCRIPTION).
- ID de información: El identificador de la información (
- NO proporcione un archivo JSON con los resultados sin procesar si se elige esta opción.
4. Ejemplo de ejecución
Destino de entrada: projects/my-test-project
Indicador asignado: --project=my-test-project
Acción (Opción B): Ejecutar
gcloud recommender recommendations list --recommender=google.iam.policy.Recommender --format=json --location=global --filter=stateInfo.state=ACTIVE --project=my-test-projectEstructura de salida esperada:
{ "raw_results": { "recommendations": [ { "name": "projects/my-test-project/locations/global/recommenders/ \ google.iam.policy.Recommender/recommendations/123", "content": { ... } } ], "insights": [] }, "error": null }
5. Gestión de errores
CRÍTICO: Si te encuentras con alguna de las condiciones de error que se indican a continuación (durante la validación o la recuperación de datos), detente inmediatamente. No intentes depurar, cambiar de cuenta, buscar en el código fuente ni verificar la existencia de los recursos. Envía inmediatamente la estructura JSON especificada como respuesta final y no llames a ninguna otra herramienta.
Si fallan todos los métodos, devuelve:
- Para un destino incorrecto:
{"raw_results": null, "error": "El recurso de destino especificado es incorrecto o no existe."} - En caso de problemas de autenticación:
{"raw_results": null, "error": "El usuario no está autenticado. Auténtate (por ejemplo, ejecuta 'gcloud auth login')"} - Por permisos:
{"raw_results": null, "error": "Permisos insuficientes. Asegúrate de que tienes 'roles/recommender.iamViewer' en el ámbito de destino."} - Otros:
{"raw_results": null, "error": "Error al recuperar: {error_details}"}(No menciones al usuario los fallos de la herramienta MCP).
Aspectos a tener en cuenta
- Filtro de estado: Asegúrate siempre de filtrar por recomendaciones
ACTIVAS. - Ubicación: La ubicación de IAM Recommender es siempre 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.
Todos los archivos
0 archivosInstalar iam-recommendations-fetcher
Descarga y descomprime los archivos de habilidades en tu directorio .claude/skills/.
Descargar ZIPClona el repositorio y copia los archivos de la habilidad a tu proyecto.
git clone https://github.com/google/skills/tree/main/skills/cloud/iam-recommendations-fetcher # Copy SKILL.md to your .claude/skills/ directory
Copiar





Hogar
