将 ListRoles 与 Amazon SDK 或命令行工具配合使用 - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

ListRoles 与 Amazon SDK 或命令行工具配合使用

以下代码示例演示如何使用 ListRoles

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,了解如何在 Amazon 代码示例存储库中进行设置和运行。

/// <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; }
  • 有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 ListRoles

CLI
Amazon CLI

要列出当前账户的 IAM 角色

以下 list-roles 命令将列出当前账户中的 IAM 角色。

aws iam list-roles

输出:

{ "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 } ] }

有关更多信息,请参阅《Amazon IAM 用户指南》中的创建 IAM 角色

  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 ListRoles

Go
适用于 Go V2 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// 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 }
  • 有关 API 详细信息,请参阅 Amazon SDK for Go API 参考中的 ListRoles

JavaScript
SDK for JavaScript (v3)
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

列出角色。

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; } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 ListRoles

PHP
适用于 PHP 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

$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); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考中的 ListRoles

PowerShell
适用于 PowerShell 的工具

示例 1:此示例检索 Amazon Web Services 账户 中的所有 IAM 角色列表。

Get-IAMRoleList

示例 2:此示例代码片段检索 Amazon 账户中的 IAM 角色列表,一次显示三个角色,然后等待您在每个组之间按 Enter 键。其传递上一个调用的 Marker 值,以指定下一组应该从哪里开始。

$nextMarker = $null Do { $results = Get-IAMRoleList -MaxItem 3 -Marker $nextMarker $nextMarker = $AWSHistory.LastServiceResponse.Marker $results Read-Host } while ($nextMarker -ne $null)
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 ListRoles

Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 ListRoles

Ruby
适用于 Ruby 的 SDK
注意

查看 GitHub,了解更多信息。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# 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
  • 有关 API 详细信息,请参阅 Amazon SDK for Ruby API 参考中的 ListRoles

Rust
适用于 Rust 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 ListRoles

Swift
SDK for Swift
注意

这是预览版 SDK 的预发布文档。本文档随时可能更改。

注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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 }
  • 有关 API 详细信息,请参阅 Amazon SDK for Swift API 参考中的 ListRoles

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。