iam-recommendations-fetcher
google/skills
Obtém recomendações do IAM e informações de segurança do Google Cloud para uma organização, pasta ou projeto especificado, utilizando ferramentas do MCP, a CLI do gcloud ou chamadas diretas à API.
...Expandir tudoRecuperação de recomendações do IAM
Esta habilidade fornece instruções para obter recomendações e insights do IAM do Google Cloud. Ela abrange a validação do escopo de destino de entrada, a recuperação de recomendações usando ferramentas do MCP, comandos do gcloud ou chamadas diretas à API, e o tratamento de erros comuns da API.
Procedimentos
1. Validar o escopo de destino de entrada
Verifique o escopo do alvo de entrada.
Verifique o formato: verifique se o escopo de destino corresponde a um destes formatos:
organizations/{org_id}pastas/{id_da_pasta}projetos/{project_id}
Tratamento de destino ambíguo/bruto: Se o usuário fornecer apenas um ID bruto (sem o prefixo):
- Alfanumérico (começa com uma letra): Presuma que seja um ID de projeto.
Formate-o como
projects/{project_id}e prossiga. - Puramente numérico: é ambíguo (pode ser um número de organização, pasta ou
projeto).
- Peça ao usuário para esclarecer o tipo de recurso: > “O ID de destino '{provided_id}' é uma organização, uma pasta ou um projeto?”
- Assim que o usuário especificar, formate o escopo de destino de acordo (por exemplo,
adicione
organizations/,folders/ouprojects/no início) e prossiga. - Se a resposta do usuário for inválida ou ele não puder esclarecer, trate isso como um erro e prossiga para “Tratar erros” (alvo incorreto).
- Alfanumérico (começa com uma letra): Presuma que seja um ID de projeto.
Formate-o como
Tratamento de números de projeto: Se o destino for um projeto, mas utilizar um ID puramente numérico (número de projeto) em vez de um ID de projeto (por exemplo,
projects/123456789):- os comandos
do gcloudrecommender exigem um ID do projeto. Tente resolver o número do projeto para um ID do projeto usando:gcloud projects list --filter="projectNumber={project_number}" --format="value(projectId)" - Se essa resolução retornar um resultado vazio ou falhar com um erro de permissão, não tente descrever o projeto, pesquisar na base de código ou procurar dados simulados. Retorne imediatamente o JSON de erro padronizado especificado em “Tratamento de erros” e interrompa a execução (não chame mais nenhuma ferramenta).
- os comandos
Validação de registro: Indique explicitamente o escopo de destino validado e formatado (por exemplo,
projects/123456789ouorganizations/123456789012) em sua justificativa antes de prosseguir para a etapa de busca.
2. Obter recomendações e insights (fluxo alternativo)
Tente os seguintes métodos de recuperação em ordem. Pare assim que houver sucesso.
CRÍTICO: Detecte erros rapidamente (para evitar chamadas de API redundantes que falharão
pelos mesmos motivos de autorização/permissão): Se qualquer método tentado (Opção
A ou Opção B) falhar com um erro no nível da API (como PERMISSION_DENIED,
UNAUTHENTICATED ou recurso NOT_FOUND / não existe) ou um erro de validação da CLI
(como número de projeto não permitido), NÃO tente nenhuma outra
opção (incluindo a Opção C ou chamadas diretas à API/curl). Interrompa imediatamente,
não chame mais nenhuma ferramenta e retorne o JSON de erro padronizado, conforme especificado na
seção “Tratamento de erros”.
Opção A: Ferramenta MCP (preferencial)
Use a ferramenta MCP, se disponível. As ferramentas MCP são projetadas para uma execução eficiente e segura nos ambientes internos do Google, geralmente oferecendo uma autenticação simplificada e melhor integração em comparação com comandos de CLI de uso geral.
Se uma ferramenta MCP do IAM Recommender estiver disponível no seu contexto:
- Chame a ferramenta com o parâmetro
“target”.
Opção B: CLI do gcloud (primeira alternativa)
Se o MCP não estiver disponível, use `run_command` para executar o seguinte (substitua
as variáveis conforme necessário):
| Destino | Sinalizador |
|---|---|
projects/{project_id} |
--project={project_id} |
pastas/{id_pasta} |
--pasta={id_da_pasta} |
organizações/{id_da_organização} |
--organização={id_da_organização} |
Comandos a serem executados:
GCLOUD_COMMON_FLAGS="--format=json --location=global \
--filter=stateInfo.state=ACTIVE"
# 1. Obter recomendações
gcloud recommender recommendations list \
--recommender=google.iam.policy.Recommender $GCLOUD_COMMON_FLAGS {mapped_flag}
# 2. Obter insights
gcloud recommender insights list --insight-type=google.iam.policy.Insight
$GCLOUD_COMMON_FLAGS {mapped_flag}
Opção C: API do Google Cloud (opção de recurso final)
Tente essa opção somente se o gcloud estiver fisicamente indisponível no
ambiente (por exemplo, gcloud: comando não encontrado). As bibliotecas de cliente da API exigem
mais configuração e sobrecarga de execução, portanto, são usadas apenas como último recurso caso as ferramentas da CLI
estejam ausentes. NÃO use esta opção se o gcloud estiver disponível, mas tiver falhado
com um erro de API.
Use as bibliotecas cliente da API do Google Cloud Recommender por meio de um script auxiliar (ou chamadas diretas à API, caso as bibliotecas não estejam disponíveis) para:
- Chamar
list_recommendations(ourecommendations.list) paragoogle.iam.policy.Recommender(filtro:stateInfo.state=ACTIVE). - Chamar
list_insights(ouinsights.list) paragoogle.iam.policy.Insight(filtro:stateInfo.state=ACTIVE).
3. Determinar o formato de saída e entregar
CRÍTICO: Só prossiga para esta etapa se a recuperação na Etapa 2 tiver sido bem-sucedida. Se a recuperação falhar, pule esta etapa e vá diretamente para Tratar erros.
Antes de apresentar os resultados, determine o formato de saída desejado.
CRÍTICO: Se a solicitação inicial do usuário já especificar o formato de saída (por exemplo, “retorne os resultados brutos em JSON” ou “mostre em uma tabela”), não pergunte e prossiga diretamente para esse formato.
Caso contrário, pergunte ao usuário em um menu suspenso, com as seguintes opções:
- Arquivo JSON
- Tabela em Markdown no chat
Com base na escolha (seja ela pré-especificada ou selecionada pelo usuário), forneça a saída:
Opção A: Arquivo JSON
- Grave os resultados brutos em um arquivo chamado
iam_recommendations_(onde_ .json é o identificador de recurso sanitizado eestá formatado comoAAAAAMMDD_HHMMSS) no diretório de trabalho atual. - O conteúdo do arquivo deve corresponder à estrutura mostrada no Exemplo de Execução.
- Responda ao usuário com o caminho do arquivo.
Opção B: Tabela de bate-papo
- Classificar recomendações: Classifique as recomendações recuperadas, colocando as recomendações do agente de atendimento por último na lista.
- Formatar tabela: Formate as recomendações classificadas em uma tabela Markdown.
A tabela deve conter os seguintes campos-chave:
- Subtipo: O subtipo do recomendador ou do insight (por exemplo, indicando se é para funções no nível de recurso).
- Ação recomendada: Resumo da recomendação.
- Fundamentação: Fundamentação/justificativa.
- Insights associados: Os IDs de quaisquer insights vinculados (de
associatedInsights).
- Limitar exibição no chat: Exibir apenas as 10 principais recomendações na tabela do chat .
- Fornecer lista completa: Salve a lista completa de recomendações e
insights em um arquivo Markdown (por exemplo,
iam_recommendations_, onde_ .md é o identificador de recurso sanitizado eestá formatado comoAAAAAMMDD_HHMMSS) e forneça um link para o usuário baixá-la. - Formatar a tabela de insights: Se houver insights, formate-os em uma
tabela separada no arquivo Markdown (e, opcionalmente, mostre um resumo no chat
se for apropriado, mas mantenha o chat organizado). A tabela deve conter os seguintes
campos principais:
- ID do insight: O identificador do insight (
INSIGHT_ID). - Estado: O estado do insight (
INSIGHT_STATE). - Subtipo: O subtipo do insight (
INSIGHT_SUBTYPE). - Descrição: Descrição da informação (
DESCRIPTION).
- ID do insight: O identificador do insight (
- NÃO forneça um arquivo JSON com os resultados brutos se esta opção for escolhida.
4. Exemplo de execução
Destino de entrada: projects/my-test-project
Sinalizador mapeado: --project=my-test-project
Ação (Opção B): Execute
gcloud recommender recommendations list --recommender=google.iam.policy.Recommender --format=json --location=global --filter=stateInfo.state=ACTIVE --project=my-test-projectEstrutura de saída esperada:
{ "raw_results": { "recommendations": [ { "name": "projects/my-test-project/locations/global/recommenders/ \ google.iam.policy.Recommender/recommendations/123", "content": { ... } } ], "insights": [] }, "error": null }
5. Tratamento de erros
CRÍTICO: Se você encontrar qualquer uma das condições de erro abaixo (durante a validação ou a recuperação de dados), pare imediatamente. Não tente depurar, trocar de conta, pesquisar no código-fonte ou verificar a existência do recurso. Envie imediatamente a estrutura JSON especificada como sua resposta final e não chame mais nenhuma ferramenta.
Se todos os métodos falharem, retorne:
- Para destino incorreto:
{"raw_results": null, "error": "O recurso de destino especificado está incorreto ou não existe."} - Para problemas de autenticação:
{"raw_results": null, "error": "O usuário não está autenticado. Por favor, autentique-se (por exemplo, execute 'gcloud auth login')."} - Para problemas de permissão:
{"raw_results": null, "error": "Permissões insuficientes. Certifique-se de ter a função 'roles/recommender.iamViewer' no escopo de destino."} - Outros:
{"raw_results": null, "error": "Falha ao buscar: {error_details}"}(Não mencione falhas da ferramenta MCP ao usuário).
Pontos a serem observados
- Filtro de estado: Certifique-se sempre de filtrar por recomendações
ATIVAS. - Localização: A localização do IAM Recommender é sempre 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 os arquivos
0 arquivosInstalar iam-recommendations-fetcher
Baixe e extraia os arquivos de habilidades para o diretório .claude/skills/.
Baixar ZIPClone o repositório e copie os arquivos da habilidade para o seu projeto.
git clone https://github.com/google/skills/tree/main/skills/cloud/iam-recommendations-fetcher # Copy SKILL.md to your .claude/skills/ directory
Copiar





Lar
