aws iam list-roles lists IAM roles in your AWS account, returning metadata such as ARN, path, and trust policy, with optional filtering by path prefix and pagination controls.
aws iam list-roles
This command retrieves all IAM roles with their AssumeRolePolicyDocument. Without flags, output is JSON with automatic pagination (up to 100 items per page). Use --path-prefix to filter roles by path, --max-items to limit results, and --starting-token for manual pagination. All flags documented here are verified against AWS CLI v2.34.61.
Syntax
aws iam list-roles [--path-prefix ] [--max-items ] [--cli-input-json | --cli-input-yaml] [--starting-token ] [--page-size ] [--generate-cli-skeleton ] [--debug] [--endpoint-url ] [--no-verify-ssl]
Options and Flags
| Flag | Type | Default | Description |
|---|---|---|---|
--path-prefix |
String | N/A (all roles) | Filters roles to those with a matching path prefix, e.g., /service-role/ |
--max-items |
Integer | 100 (service default, not CLI) | Maximum number of items returned per page |
--starting-token |
String | N/A | Pagination token from a previous list-roles response to fetch the next page |
--page-size |
Integer | 100 | Controls the number of results fetched per API call; larger values reduce pagination overhead |
--no-paginate |
Flag | False | Disables automatic pagination; returns only the first page of results |
--output |
String | json | Output format: json, text, table, yaml, or yaml-stream |
--query |
String | N/A | JMESPath expression to filter or shape the output |
--generate-cli-skeleton |
String | N/A | Generates a valid input skeleton; accepted values: input or yaml-input |
Usage Examples
List all roles in the account
aws iam list-roles
Returns an unfiltered list of all IAM roles. Useful for account-wide audits. Output includes the trust policy document (AssumeRolePolicyDocument). Without pagination flags, the CLI automatically handles pagination up to the default 100 items per page.
Filter roles by path prefix and output only names and ARNs
aws iam list-roles --path-prefix /service-role/ --query 'Roles[].[RoleName, Arn]' --output table
Filters roles under the /service-role/ path (commonly used for AWS service-linked roles) and outputs a clean table with only the role name and ARN. The --query flag projects specific fields from the JSON structure, reducing output noise.
Paginate through large role sets with controlled page size
aws iam list-roles --page-size 50 --max-items 200
Fetches roles with a custom page size of 50, limiting total results to 200 (two pages). Useful for reducing API call impact in large accounts. Combine with --starting-token from the previous response to continue pagination across multiple CLI invocations.
List roles and the services that can assume them
aws iam list-roles --query 'Roles[].[RoleName, AssumeRolePolicyDocument.Statement[].Principal.Service]' --output json
Extracts the role name and the list of AWS services allowed to assume each role via the trust policy. Useful for auditing cross-service access (e.g., finding all roles usable by EC2, Lambda, etc.). The Principal.Service field appears only when a service is the principal.
Troubleshooting and Common Errors
| Error Message | Root Cause | Resolution Command |
|---|---|---|
| An error occurred (AccessDenied) when calling the ListRoles operation: … | Missing iam:ListRoles permission in the caller’s policy |
Attach a policy with "Action": "iam:ListRoles"; verify with aws iam get-user or aws sts get-caller-identity |
| InvalidParameterValue: The value … for parameter pathPrefix is invalid | Path prefix does not start with / or contains invalid characters |
Correct the prefix: --path-prefix /service-role/ (must begin and end with /) |
| RequestError: send request failed: dial tcp: lookup iam.amazonaws.com: no such host | DNS resolution failure or network proxy misconfiguration | curl -v https://iam.amazonaws.com; check --endpoint-url for VPC endpoint usage |
| Incomplete output / truncated role list | Exceeded default pagination limit; output is only a page | Use aws iam list-roles --no-paginate | jq '.Roles | length' to check count, then add --max-items or handle --starting-token manually |
Exit Codes
| Code | Meaning | Operational Impact |
|---|---|---|
| 0 | Success | Command completed successfully; roles listed or empty result |
| 255 | Parsing/validation error | Invalid flag, malformed --query, or incorrect argument type |
| 254 | Service error | AWS IAM returned an error (e.g., throttling, access denied, internal failure) |
Performance Considerations and Tuning
Performance of aws iam list-roles depends on CLI pagination parameters and network stack. Control result set size with --max-items and --page-size. A smaller --page-size reduces per-call memory but increases total round-trips; a larger one reduces overhead but raises latency per call. Set timeouts via --cli-read-timeout and --cli-connect-timeout to avoid stalls. Use --no-paginate to process a single page.
- Batch size:
--max-items 100 --page-size 20 - Timeouts:
--cli-read-timeout 10 --cli-connect-timeout 5 - Parallelism: Combine with GNU Parallel:
aws iam list-roles --query "Roles[].RoleName" --output text | parallel -j4 '...' - MTU and buffer sizes: Tuned at kernel level; refer to Linux Network Performance Tuning Guide (e.g.,
sysctl net.core.rmem_maxfor read buffers,ip linkfor MTU).
The following command applies performance knobs in one call (AWS CLI v2.34.61):
aws iam list-roles
--page-size 50
--max-items 200
--cli-read-timeout 15
--cli-connect-timeout 10
--no-paginate
--output json
Security and Operational Best Practices
Apply least-privilege IAM for aws iam list-roles. Grant only iam:ListRoles permission to callers, not iam:PassRole or iam:CreateRole. Use IAM Access Analyzer to review trust policies and reduce attack surface.
- Least-privilege: Attach a policy with
Effect: AllowandAction: iam:ListRolesonResource: "*". Restrict further withConditionblocks (e.g.,aws:SourceIp) if sensitive roles exist. - Authentication knobs: Use
--profilefor separate accounts,--regionfor regional isolation, and--no-sign-requestonly in non-production environments. For signed requests, enforce MFA via policy withaws:MultiFactorAuthPresent. - Audit and logging: Enable AWS CloudTrail to capture all
ListRolesevents. Monitor withaws cloudtrail lookup-eventsor integrate with Amazon Security Lake. Use--queryto extract only needed fields, reducing downstream processing.
# Paginate, filter, and audit IAM ListRoles calls
aws iam list-roles --max-items 50 --query "Roles[?RoleName!='AWSServiceRole*'].[RoleName,Arn]" --output json --profile prod --region us-east-1
# Check CloudTrail for who called ListRoles in the last hour
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=ListRoles --query "Events[*].{Time:EventTime,User:Username,SourceIP:SourceIPAddress}" --output table --region us-east-1
Frequently Asked Questions
What is the difference between --no-paginate and using the default pagination in aws iam list-roles?
--no-paginate disables automatic pagination, returning all results in a single API call. Default pagination (enabled) automatically fetches subsequent pages via the Python SDK boto3 when MaxItems is set (default 100). --no-paginate forces the CLI to issue one ListRoles request and returns the raw response, useful for scripting with --query on a known small number of roles. Example: aws iam list-roles --no-paginate --query 'Roles[*].RoleName' --output json.
When should I use the --path-prefix flag with aws iam list-roles?
Use --path-prefix to filter roles by their path, typically for organizing roles per environment (e.g., /production/, /staging/). This flag narrows results to roles whose path begins with the given string (case-sensitive). Essential for multi-account multi-environment setups. Example: aws iam list-roles --path-prefix /application/production/ --output table. The path must start and end with /; the default path is /.
How do I fix the error “An error occurred (AccessDenied) when calling the ListRoles operation”?
Attach the IAM policy granting iam:ListRoles (e.g., IAMReadOnlyAccess). For a user: aws iam attach-user-policy --user-name <username> --policy-arn arn:aws:iam::aws:policy/IAMReadOnlyAccess. For a role: aws iam attach-role-policy --role-name <rolename> --policy-arn arn:aws:iam::aws:policy/IAMReadOnlyAccess. Verify with aws sts get-caller-identity.
Does aws iam list-roles work in AWS GovCloud (US-Gov) regions?
Yes, it works in GovCloud endpoints. The IAM service is globally available. Configure aws configure with GovCloud partition ARNs and specify the region, e.g., aws iam list-roles --region us-gov-west-1. Note that some IAM features (e.g., AWS Organizations) may differ; check the GovCloud documentation.
What is the fastest way to list all IAM roles with their ARN and creation date?
Use --no-paginate combined with --query and --output json for a single, filtered API call. For large accounts (thousands of roles), pipe with jq for sorting: aws iam list-roles --no-paginate --query 'Roles[*].{Name:RoleName, ARN:Arn, Created:CreateDate}' --output json | jq 'sort_by(.Created)'. This minimizes data transfer by extracting only necessary fields.

Command Line Expert & Software Engineer
Welcome! I’m Thomas Heinrich, a software engineer and system administrator with a deep passion for the Command Line Interface (CLI). With years of experience navigating the terminal, building backend architectures, and automating server deployments, I created this space to share practical, real-world terminal knowledge.
Whether you are a beginner taking your first steps in a Linux environment or a seasoned DevOps engineer looking to optimize your deployment scripts, you will find actionable solutions here. My goal is to help you ditch the mouse, speed up your workflow, and harness the full power of the command line.