Use ListRoles with an AWS SDK or command line tool - AWS SDK Code Examples

There are more AWS SDK examples available in the AWS Doc SDK Examples GitHub repo.

Use ListRoles with an AWS SDK or command line tool

The following code examples show how to use ListRoles.

.NET
AWS SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

/// <summary> /// List IAM roles. /// </summary> /// <returns>A list of IAM roles.</returns> public async Task<List<Role>> ListRolesAsync() { var listRolesPaginator = _IAMService.Paginators.ListRoles(new ListRolesRequest()); var roles = new List<Role>(); await foreach (var response in listRolesPaginator.Responses) { roles.AddRange(response.Roles); } return roles; }
  • For API details, see ListRoles in AWS SDK for .NET API Reference.

CLI
AWS CLI

To list IAM roles for the current account

The following list-roles command lists IAM roles for the current account.

aws iam list-roles

Output:

{ "Roles": [ { "Path": "/", "RoleName": "ExampleRole", "RoleId": "AROAJ52OTH4H7LEXAMPLE", "Arn": "arn:aws:iam::123456789012:role/ExampleRole", "CreateDate": "2017-09-12T19:23:36+00:00", "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }, "MaxSessionDuration": 3600 }, { "Path": "/example_path/", "RoleName": "ExampleRoleWithPath", "RoleId": "AROAI4QRP7UFT7EXAMPLE", "Arn": "arn:aws:iam::123456789012:role/example_path/ExampleRoleWithPath", "CreateDate": "2023-09-21T20:29:38+00:00", "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }, "MaxSessionDuration": 3600 } ] }

For more information, see Creating IAM roles in the AWS IAM User Guide.

  • For API details, see ListRoles in AWS CLI Command Reference.

Go
SDK for Go V2
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions // used in the examples. // It contains an IAM service client that is used to perform role actions. type RoleWrapper struct { IamClient *iam.Client } // ListRoles gets up to maxRoles roles. func (wrapper RoleWrapper) ListRoles(maxRoles int32) ([]types.Role, error) { var roles []types.Role result, err := wrapper.IamClient.ListRoles(context.TODO(), &iam.ListRolesInput{MaxItems: aws.Int32(maxRoles)}, ) if err != nil { log.Printf("Couldn't list roles. Here's why: %v\n", err) } else { roles = result.Roles } return roles, err }
  • For API details, see ListRoles in AWS SDK for Go API Reference.

JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

List the roles.

import { ListRolesCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * A generator function that handles paginated results. * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this. * */ export async function* listRoles() { const command = new ListRolesCommand({ MaxItems: 10, }); /** * @type {import("@aws-sdk/client-iam").ListRolesCommandOutput | undefined} */ let response = await client.send(command); while (response?.Roles?.length) { for (const role of response.Roles) { yield role; } if (response.IsTruncated) { response = await client.send( new ListRolesCommand({ Marker: response.Marker, }), ); } else { break; } } }
  • For API details, see ListRoles in AWS SDK for JavaScript API Reference.

PHP
SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

$uuid = uniqid(); $service = new IAMService(); /** * @param string $pathPrefix * @param string $marker * @param int $maxItems * @return Result * $roles = $service->listRoles(); */ public function listRoles($pathPrefix = "", $marker = "", $maxItems = 0) { $listRolesArguments = []; if ($pathPrefix) { $listRolesArguments["PathPrefix"] = $pathPrefix; } if ($marker) { $listRolesArguments["Marker"] = $marker; } if ($maxItems) { $listRolesArguments["MaxItems"] = $maxItems; } return $this->iamClient->listRoles($listRolesArguments); }
  • For API details, see ListRoles in AWS SDK for PHP API Reference.

PowerShell
Tools for PowerShell

Example 1: This example retrieves a list of all of the IAM roles in the AWS account.

Get-IAMRoleList

Example 2: This example code snippet retrieves a list of IAM roles in the AWS account and displays them three at a time, and waits for you to press Enter between each group. It passes the Marker value from the previous call to specify where the next group should begin.

$nextMarker = $null Do { $results = Get-IAMRoleList -MaxItem 3 -Marker $nextMarker $nextMarker = $AWSHistory.LastServiceResponse.Marker $results Read-Host } while ($nextMarker -ne $null)
  • For API details, see ListRoles in AWS Tools for PowerShell Cmdlet Reference.

Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

def list_roles(count): """ Lists the specified number of roles for the account. :param count: The number of roles to list. """ try: roles = list(iam.roles.limit(count=count)) for role in roles: logger.info("Role: %s", role.name) except ClientError: logger.exception("Couldn't list roles for the account.") raise else: return roles
  • For API details, see ListRoles in AWS SDK for Python (Boto3) API Reference.

Ruby
SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

# Lists IAM roles up to a specified count. # @param count [Integer] the maximum number of roles to list. # @return [Array<String>] the names of the roles. def list_roles(count) role_names = [] roles_counted = 0 @iam_client.list_roles.each_page do |page| page.roles.each do |role| break if roles_counted >= count @logger.info("\t#{roles_counted + 1}: #{role.role_name}") role_names << role.role_name roles_counted += 1 end break if roles_counted >= count end role_names rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't list roles for the account. Here's why:") @logger.error("\t#{e.code}: #{e.message}") raise end
  • For API details, see ListRoles in AWS SDK for Ruby API Reference.

Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

pub async fn list_roles( client: &iamClient, path_prefix: Option<String>, marker: Option<String>, max_items: Option<i32>, ) -> Result<ListRolesOutput, SdkError<ListRolesError>> { let response = client .list_roles() .set_path_prefix(path_prefix) .set_marker(marker) .set_max_items(max_items) .send() .await?; Ok(response) }
  • For API details, see ListRoles in AWS SDK for Rust API reference.

Swift
SDK for Swift
Note

This is prerelease documentation for an SDK in preview release. It is subject to change.

Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

public func listRoles() async throws -> [String] { var roleList: [String] = [] var marker: String? = nil var isTruncated: Bool repeat { let input = ListRolesInput(marker: marker) let output = try await client.listRoles(input: input) guard let roles = output.roles else { return roleList } for role in roles { if let name = role.roleName { roleList.append(name) } } marker = output.marker isTruncated = output.isTruncated } while isTruncated == true return roleList }
  • For API details, see ListRoles in AWS SDK for Swift API reference.