Security engineers and cloud architects use this prompt to perform a structured, human-readable audit of a single IAM policy document against least-privilege principles. The core job-to-be-done is generating a detailed privilege analysis that identifies over-permissioned actions, unused permissions, wildcard resource risks, and missing condition keys, along with specific remediation recommendations. This prompt is designed to be integrated into a pre-deployment security review gate or a periodic access audit cycle, producing an artifact that can be attached to a security finding ticket and tracked to closure.
Prompt
IAM Role Least-Privilege Review Prompt

When to Use This Prompt
Defines the specific security review workflow this prompt supports and the conditions under which it should and should not be applied.
The ideal input is a complete IAM policy JSON document, such as an AWS IAM role policy, an Azure RBAC role definition, or a GCP IAM binding. The prompt expects the raw policy text and an optional [CONTEXT] block specifying the role's intended function, the services it interacts with, and the trust boundary. The output is a structured analysis, not a simple pass/fail verdict. It should enumerate specific actions that exceed the stated requirements, flag any use of "Resource": "*" without a compensating condition, and call out missing condition keys like aws:SourceIp or aws:RequestedRegion that could restrict blast radius. This level of detail makes the prompt useful for engineers who need to justify a remediation to an application team or an auditor.
This prompt is not a replacement for automated IAM analysis tools. Do not use it as a substitute for AWS IAM Access Analyzer, Azure Policy, or GCP Policy Intelligence, which provide continuous, policy-wide analysis across all roles in an account. Instead, use this prompt when you need a targeted, human-readable audit trail for a single high-risk role, or when you need to generate the narrative justification for a remediation that an automated tool has already flagged. It is also inappropriate for analyzing the effective permissions of a principal across multiple attached policies, as the prompt operates on a single policy document and cannot resolve the union of permissions from multiple policy attachments or group memberships. For that, use a policy simulator. Finally, never use the prompt's output as the sole authorization for a production change; all remediation recommendations must be reviewed by a human with context on the application's actual runtime behavior.
Use Case Fit
Where the IAM Role Least-Privilege Review Prompt delivers reliable security analysis and where it introduces unacceptable risk. Use these cards to decide if this prompt fits your workflow before integrating it into a security review pipeline.
Good Fit: Structured Policy Audits
Use when: you have a known IAM policy document (JSON) and need a systematic check for over-permissioned actions, wildcard resources, and missing condition keys. Guardrail: Always provide the full policy JSON as [INPUT] and a specific [SCOPE] (e.g., 'production roles only') to prevent the model from hallucinating permissions that aren't in the document.
Bad Fit: Real-Time Access Decisions
Avoid when: you need to make a live access control decision or evaluate permissions dynamically at request time. This prompt is a design-time review tool, not a policy enforcement point. Guardrail: Route real-time authorization checks to your policy engine (e.g., OPA, Cedar); use this prompt only in CI/CD pipelines or periodic audit workflows.
Required Input: Complete Policy Document
What to watch: The prompt cannot audit what it cannot see. If you provide only a role name or a partial snippet, the analysis will be incomplete or fabricated. Guardrail: Require the full IAM policy JSON as a mandatory [INPUT] field. Add a pre-flight check in your harness that rejects requests with truncated or summarized policies.
Operational Risk: Cross-Account Trust Misinterpretation
What to watch: The model may misclassify cross-account trust policies, either flagging legitimate federation as risky or missing overly permissive Principal: '*' in trust documents. Guardrail: Route any finding related to trust policies or sts:AssumeRole to a human security engineer for review. Never auto-remediate trust policy changes based solely on model output.
Operational Risk: Condition Key Blind Spots
What to watch: The model may miss the absence of critical condition keys (e.g., aws:SourceIp, s3:x-amz-server-side-encryption) or fail to recognize when a condition is present but incorrectly scoped. Guardrail: Maintain a checklist of required condition keys per service in your eval harness. After the prompt runs, programmatically verify that each finding includes a condition key analysis, not just an action audit.
Bad Fit: Unfamiliar Cloud Providers
Avoid when: auditing policies for cloud providers or services outside the model's training distribution (e.g., niche SaaS platforms, custom policy languages). The model may apply AWS IAM logic to a different authorization model, producing misleading results. Guardrail: Restrict use to well-known IAM systems (AWS, Azure, GCP). For anything else, require a human expert to validate the model's reasoning before accepting any finding.
Copy-Ready Prompt Template
Paste this prompt into your AI harness. Replace square-bracket placeholders with real values before execution.
The following prompt template is designed to be copied directly into your AI orchestration layer, model API call, or evaluation harness. It accepts an IAM policy document and a set of business context variables, then produces a structured least-privilege analysis. Every square-bracket placeholder must be replaced with a concrete value before the prompt is sent to the model. Leaving a placeholder unresolved will cause the model to hallucinate or skip critical analysis steps.
textYou are an IAM security reviewer performing a least-privilege audit on a cloud IAM role. ## INPUT Role Name: [ROLE_NAME] Attached Policies (JSON): [POLICY_DOCUMENTS] Inline Policies (JSON): [INLINE_POLICIES] Trust Policy (JSON): [TRUST_POLICY] Last Used Data (JSON, optional): [LAST_USED_REPORT] ## CONTEXT Workload Description: [WORKLOAD_DESCRIPTION] Required Actions: [REQUIRED_ACTIONS] Required Resources: [REQUIRED_RESOURCES] Environment: [ENVIRONMENT] Compliance Framework: [COMPLIANCE_FRAMEWORK] ## CONSTRAINTS - Flag any permission not present in [REQUIRED_ACTIONS] as over-privileged. - Flag any resource pattern containing "*" unless explicitly justified in [REQUIRED_RESOURCES]. - Flag any trust policy principal that is not an explicit account ID or known service. - Flag any missing condition keys that would restrict source IP, VPC endpoint, or MFA. - If [LAST_USED_REPORT] is provided, flag any permission unused for more than [UNUSED_THRESHOLD_DAYS] days. - Do not recommend removing permissions that are required by AWS-managed service roles unless they are clearly unused. ## OUTPUT_SCHEMA Return a JSON object with this exact structure: { "summary": { "total_permissions": <number>, "over_privileged_count": <number>, "unused_count": <number>, "risk_level": "low" | "medium" | "high" | "critical" }, "findings": [ { "id": "F-<number>", "severity": "low" | "medium" | "high" | "critical", "category": "over-privileged" | "unused" | "wildcard-resource" | "missing-condition" | "trust-risk", "policy_name": "<string>", "statement_sid": "<string or null>", "permission": "<string>", "resource": "<string>", "finding": "<explanation>", "recommendation": "<specific fix>" } ], "remediation_plan": { "immediate_actions": ["<string>"], "short_term_actions": ["<string>"], "requires_architectural_change": <boolean> } } ## EXAMPLES <example> Input: Role with s3:* on * resource, workload only needs GetObject on one bucket. Output finding: F-1, critical, over-privileged, s3:*, *, "Role grants full S3 access to all buckets. Workload only requires s3:GetObject on arn:aws:s3:::app-bucket/*. Replace with scoped permission." </example> ## INSTRUCTIONS 1. Parse all policy documents and flatten every Action and Resource. 2. Compare each permission against [REQUIRED_ACTIONS] and [REQUIRED_RESOURCES]. 3. Cross-reference with [LAST_USED_REPORT] if provided. 4. Check every trust policy principal for overly broad trust. 5. Check for missing condition keys: aws:SourceIp, aws:SourceVpc, aws:MultiFactorAuthPresent. 6. Output only the JSON object. No markdown, no commentary.
Adaptation notes: Replace [POLICY_DOCUMENTS] with the full JSON of each attached policy, not just policy names. The model needs the complete Action, Resource, Effect, and Condition blocks to perform accurate analysis. If you don't have a last-used report, remove the [LAST_USED_REPORT] placeholder and the associated constraint bullet, or set [UNUSED_THRESHOLD_DAYS] to a value that makes sense for your environment (typically 90 days). The [COMPLIANCE_FRAMEWORK] field should contain a short identifier like SOC2, HIPAA, PCI-DSS, or NIST-800-53 to help the model prioritize condition key recommendations.
Validation before use: Before sending this prompt to production, run it against a known over-privileged test role and confirm the output JSON parses correctly, the finding count matches your manual count, and the risk_level field aligns with your internal severity rubric. If the model returns findings outside the JSON block, add a stronger output constraint or use a structured output API feature. For high-risk production roles, always route findings through a human reviewer before applying remediation, especially when the recommendation involves removing permissions from a role that serves live traffic.
Prompt Variables
Replace these placeholders with concrete values before sending the prompt. Each variable directly controls the scope and accuracy of the least-privilege analysis.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[IAM_POLICY_DOCUMENT] | The full JSON policy document to be reviewed for over-permissioned statements | {"Version": "2012-10-17", "Statement": [...]} | Must be valid JSON. Parse check required. Reject if empty or contains only deny statements without allow statements. |
[ROLE_NAME] | The human-readable name of the IAM role under review to contextualize findings | prod-payment-processor-role | Must match the pattern ^[a-zA-Z0-9+=,.@_-]+$. Null allowed if reviewing an inline policy detached from a role. |
[ROLE_ATTACHED_BOUNDARIES] | List of permissions boundaries or SCPs that constrain effective permissions | ["arn:aws:iam::aws:policy/PowerUserAccess"] | Array of ARN strings. Null allowed if no boundaries apply. If provided, cross-reference against policy to identify masked permissions. |
[CLOUDTRAIL_EVENT_LOG] | Recent CloudTrail events for the role to cross-reference granted permissions against actual usage | [{"eventSource": "s3.amazonaws.com", "eventName": "GetObject"}] | Array of event objects. Null allowed. If provided, the prompt must flag unused permissions. Validate event timestamps are within the analysis window. |
[ACCESS_ADVISOR_DATA] | IAM Access Advisor last-accessed timestamps for each action in the policy | {"s3:GetObject": "2024-11-15T08:22:00Z"} | Map of action to ISO 8601 timestamp. Null allowed. If provided, actions with no access in 90+ days should be flagged for removal. |
[ORGANIZATIONAL_REQUIREMENTS] | Internal compliance or security standards that override default least-privilege rules | "PCI-DSS 4.0 requires MFA for all console access" | String or null. If provided, the prompt must evaluate policy against these constraints in addition to general least-privilege principles. |
[OUTPUT_SCHEMA] | The expected JSON structure for the analysis output to ensure machine-readability | {"findings": [...], "risk_score": "high"} | Must be a valid JSON Schema or example object. Reject if schema requires fields the prompt cannot produce from available inputs. |
Implementation Harness Notes
How to wire the IAM role least-privilege review prompt into a security review pipeline with validation, retries, and human approval gates.
This prompt is designed to be integrated into a CI/CD pipeline or a periodic security audit workflow, not as a one-off chat interaction. The implementation harness must treat the prompt as a deterministic analysis step that produces structured, machine-readable output suitable for downstream ticketing systems and compliance dashboards. The primary integration points are: a policy retrieval step that gathers the IAM policy document and CloudTrail event history, the prompt execution step that generates the privilege analysis, a validation step that enforces the output schema, and a routing step that sends high-severity findings for human review while auto-approving low-risk observations.
Start by building a policy retrieval adapter that accepts an IAM role ARN and returns a structured context object containing the inline and attached policies, trust relationships, permission boundaries, and a summary of recent API calls from CloudTrail (last 90 days). This adapter must resolve managed policy attachments to their full document bodies and normalize the Action, Resource, and Condition blocks into a consistent format before passing them into the prompt's [IAM_POLICY_DOCUMENT] and [CLOUDTRAIL_ACTIVITY] placeholders. For the [RISK_THRESHOLD] parameter, map your organization's severity levels (e.g., HIGH, MEDIUM, LOW) to the prompt's expected values and set a default of MEDIUM for automated runs. The [COMPLIANCE_FRAMEWORK] placeholder should be populated from a configuration file that maps your accounts to the relevant standards (e.g., SOC2, PCI-DSS, HIPAA) so the prompt can tailor its checks for wildcard resources and missing condition keys specific to each framework.
After the model returns a response, run a schema validator against the expected JSON output structure before any downstream action is taken. The validator must confirm that the findings array contains objects with the required fields (severity, finding_type, description, affected_permissions, recommendation, compliance_flag), that severity values are in the allowed enum, and that the summary object includes total_findings, critical_count, high_count, medium_count, and low_count. If validation fails, implement a retry loop with a maximum of 2 additional attempts, appending the validation error message to the prompt as feedback: The previous output failed schema validation with the following errors: [VALIDATION_ERRORS]. Please correct the JSON output. After 3 total failures, log the raw response and escalate to the security engineering team for manual review rather than silently dropping the analysis.
For findings classified as CRITICAL or HIGH, the harness must open a ticket in your issue tracker (Jira, ServiceNow, etc.) with the finding details, affected role ARN, and a link to the full analysis. For MEDIUM findings, add them to a security backlog for sprint planning. For LOW findings, log them to a compliance evidence store without blocking the pipeline. Implement a human approval gate that prevents automatic remediation of any finding involving iam:PassRole, sts:AssumeRole, or cross-account trust modifications—these must always require explicit security team sign-off. The harness should also maintain an audit log of every prompt execution, including the input policy hash, model version, output hash, validation status, and reviewer identity, so that compliance auditors can trace each least-privilege review from trigger to resolution.
Expected Output Contract
Fields, types, and validation rules for the IAM role least-privilege review output. Use this contract to parse, validate, and integrate the model response into downstream security workflows.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
role_name | string | Must match the [ROLE_NAME] input exactly. Case-sensitive string comparison. | |
overall_risk_level | enum: critical | high | medium | low | informational | Must be one of the five allowed enum values. Reject any other string. | |
findings | array of objects | Must be a non-null array. If no findings exist, return an empty array, not null or a string. | |
findings[].policy_name | string | Must be a non-empty string matching a policy attached to the role. Validate against the [ATTACHED_POLICIES] input list. | |
findings[].severity | enum: critical | high | medium | low | Must be one of the four allowed enum values. Reject any other string. | |
findings[].finding_type | enum: over_permission | unused_permission | missing_condition | wildcard_resource | cross_account_trust | privilege_escalation | Must be one of the six allowed enum values. | |
findings[].affected_action | string | Must be a valid IAM action string matching the pattern ^[a-zA-Z0-9]+:[a-zA-Z0-9*]+$. Reject if empty or malformed. | |
findings[].affected_resource | string | Must be a valid ARN pattern or wildcard string. If the resource is a wildcard, the finding_type must include wildcard_resource. | |
findings[].description | string | Must be a non-empty string between 20 and 500 characters. Reject if shorter than 20 or longer than 500. | |
findings[].remediation | string | Must be a non-empty string between 20 and 1000 characters. Reject if shorter than 20 or longer than 1000. | |
findings[].evidence | object | Must contain policy_name, statement_index, and condition_key fields. policy_name must match the parent finding. statement_index must be a non-negative integer. | |
summary | object | Must contain total_findings, critical_count, high_count, medium_count, and low_count fields. All must be non-negative integers. Sum of severity counts must equal total_findings. |
Common Failure Modes
IAM least-privilege review prompts fail in predictable ways. These cards cover the most common failure modes and the guardrails that prevent them from reaching production.
Wildcard Resource Blindness
What to watch: The model accepts Resource: "*" when the action already implies broad access, or fails to flag wildcards nested inside condition blocks. Guardrail: Add a pre-processing step that extracts all resource ARNs and flags any containing * for mandatory human review before the prompt runs.
Condition Key Omission
What to watch: The model approves a policy that grants s3:GetObject without requiring s3:ResourceTag or aws:PrincipalTag conditions, missing the opportunity to scope access to specific projects. Guardrail: Include a required checklist of standard condition keys per service in the prompt's [CONSTRAINTS] block, and validate the output against it.
Cross-Account Trust Over-Approval
What to watch: The model treats a cross-account trust relationship as benign because the external account ID looks familiar, without verifying the trust policy's ExternalId condition or the principle of least privilege on the trusted role. Guardrail: Require the prompt to output a dedicated cross_account_trusts array with explicit justification for each trust, and flag any trust without an ExternalId condition.
Unused Permission Accumulation
What to watch: The model only analyzes the policy document in isolation, ignoring CloudTrail or IAM Access Advisor data that shows 90% of granted permissions have never been used. Guardrail: Always supply last-accessed data as part of [CONTEXT] and instruct the model to produce a separate unused_permissions list with a removal recommendation for each.
NotAction / NotResource Logic Inversion
What to watch: The model misinterprets NotAction combined with Allow as restrictive when it actually creates a broad allow with specific exclusions, or fails to detect when NotResource inadvertently includes sensitive resources. Guardrail: Require the prompt to expand all NotAction and NotResource statements into explicit lists in the analysis output, and flag any resulting effective permissions that exceed the stated intent.
PassRole Privilege Escalation
What to watch: The model treats iam:PassRole as a low-risk permission and fails to check which roles can be passed to which services, creating a path for privilege escalation via Lambda, EC2, or ECS. Guardrail: Add a mandatory escalation path analysis to the [OUTPUT_SCHEMA] that traces every PassRole permission to the roles it can pass and the services that can assume them.
Evaluation Rubric
Criteria for evaluating the quality of a least-privilege IAM review before shipping the prompt to production. Use these standards in automated eval harnesses or manual spot checks.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Over-Permission Identification | Output lists at least one specific IAM action that is granted but not justified by [USAGE_DATA] or [JUSTIFICATION]. Each finding includes the role name and the exact action. | Output states 'no over-permissions found' when [USAGE_DATA] shows zero invocations for a granted action, or lists actions without role association. | Parse output for action-role pairs. Cross-reference each pair against [USAGE_DATA] timestamps. Flag if unused actions are missing from findings. |
Wildcard Resource Detection | Every role containing 'Resource: "*"' is flagged with a severity rating and a suggested resource constraint based on [RESOURCE_TAGS] or [ACCOUNT_STRUCTURE]. | Wildcard resources are mentioned without a concrete suggested constraint, or roles with 'Resource: "*"' are entirely absent from findings. | Scan output for wildcard findings. For each, verify a non-wildcard ARN pattern is proposed. Check that all roles with known wildcards in [POLICY_DOCUMENT] appear. |
Missing Condition Key Analysis | Output identifies at least one sensitive action (e.g., s3:DeleteBucket, iam:CreateAccessKey) that lacks a condition key, and suggests a specific condition (e.g., aws:SourceIp, aws:PrincipalTag). | Condition key section is empty when [POLICY_DOCUMENT] contains sensitive actions without conditions, or suggestions are generic (e.g., 'add MFA') without mapping to a specific action. | Extract sensitive actions from [POLICY_DOCUMENT]. Verify each has a corresponding entry in the output's condition analysis. Check that suggested condition keys are valid for the target service. |
Cross-Account Trust Risk Flagging | Every cross-account trust in [TRUST_POLICIES] is listed with the external account ID, the trusted principal type, and a risk classification (e.g., 'HIGH' if external account is not in [APPROVED_ACCOUNTS]). | Cross-account trust findings omit the external account ID, or classify a trust as 'LOW' when the external account is not in [APPROVED_ACCOUNTS]. | Parse trust policy ARNs from [TRUST_POLICIES]. Verify each external account ID appears in output. Compare risk classifications against [APPROVED_ACCOUNTS] list. |
Unused Role Identification | Output lists roles with zero access activity in [USAGE_DATA] over the specified [LOOKBACK_DAYS], with a recommended action (delete, detach policies, or escalate for review). | Roles with zero activity are listed without a recommended action, or the output fails to mention roles that have no entries in [USAGE_DATA]. | Join role list from [POLICY_DOCUMENT] with [USAGE_DATA]. Verify every role with no activity appears in output with a non-null recommended action. |
Privilege Escalation Path Detection | Output identifies direct or chained paths where a role can escalate its own privileges (e.g., iam:PutRolePolicy on itself) and marks each as 'CRITICAL'. | Escalation paths are described vaguely without the specific API call chain, or roles with known self-modification permissions are not flagged. | Scan [POLICY_DOCUMENT] for self-referential IAM write actions. Verify each appears in output with a 'CRITICAL' severity and the exact action name. |
Service-Linked Role Awareness | Output explicitly excludes or marks as 'REVIEW SEPARATELY' any AWS service-linked roles, noting they are managed by the service and have constrained modification paths. | Service-linked roles are treated identically to customer-managed roles, with recommendations to delete or modify policies that cannot be changed. | Check output for presence of service-linked role path (aws-service-role). Verify these roles are either absent from actionable findings or tagged with a clear exclusion note. |
Output Schema Compliance | Output is valid JSON matching [OUTPUT_SCHEMA] exactly. All required fields are present, no extra fields, and enum values match allowed sets. | Output is not parseable as JSON, required fields are null or missing, or severity values use strings outside the allowed enum (e.g., 'HIGH', 'MEDIUM', 'LOW', 'INFO'). | Validate output against [OUTPUT_SCHEMA] using a JSON Schema validator. Reject on missing required fields, wrong types, or invalid enum values. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single IAM policy document and a simplified output schema. Drop the multi-account and cross-role comparison logic. Focus on one role, one policy, and a plain-text findings list.
codeAnalyze this IAM policy for over-permissioned actions. Return a list of findings with severity (HIGH/MEDIUM/LOW) and a one-line recommendation. Policy: [POLICY_JSON]
Watch for
- Wildcard resource patterns flagged without context on whether the service supports resource-level permissions
- False positives on
List*andDescribe*read-only actions that are low risk - Missing distinction between unused permissions and genuinely dangerous permissions

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us