本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
下列程式碼範例示範如何使用 ListRoles
。
- .NET
-
- AWS SDK for .NET
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /// <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 詳細資訊,請參閱 AWS SDK for .NET API Reference 中的 ListRoles。
-
- CLI
-
- AWS 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 } ] }
如需詳細資訊,請參閱《AWS IAM 使用者指南》中的建立 IAM 角色。
-
如需 API 詳細資訊,請參閱《AWS CLI 命令參考》中的 ListRoles
。
-
- Go
-
- SDK for Go V2
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 import ( "context" "encoding/json" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/iam" "github.com/aws/aws-sdk-go-v2/service/iam/types" ) // 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(ctx context.Context, maxRoles int32) ([]types.Role, error) { var roles []types.Role result, err := wrapper.IamClient.ListRoles(ctx, &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 詳細資訊,請參閱 適用於 Go 的 AWS SDK API Reference 中的 ListRoles
。
-
- JavaScript
-
- SDK for JavaScript (v3)
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 列出角色。
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 詳細資訊,請參閱《AWS SDK for JavaScript API 參考》中的 ListRoles。
-
- PHP
-
- SDK for PHP
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 $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 詳細資訊,請參閱 AWS SDK for PHP API Reference 中的 ListRoles。
-
- PowerShell
-
- Tools for PowerShell
-
範例 1:此範例會擷取 AWS 帳戶中所有 IAM 角色的清單。
Get-IAMRoleList
-
如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet Reference 中的 ListRoles。
-
- Python
-
- SDK for Python (Boto3)
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 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 詳細資訊,請參閱 AWS SDK for Python (Boto3) API Reference 中的 ListRoles。
-
- Ruby
-
- SDK for Ruby
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 # 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 詳細資訊,請參閱 AWS SDK for Ruby API Reference 中的 ListRoles。
-
- Rust
-
- SDK for Rust
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 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 詳細資訊,請參閱 AWS SDK for Rust API reference 中的 ListRoles
。
-
- Swift
-
- SDK for Swift
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 import AWSIAM import AWSS3 public func listRoles() async throws -> [String] { var roleList: [String] = [] // Use "Paginated" to get all the roles. // This lets the SDK handle the 'isTruncated' in "ListRolesOutput". let input = ListRolesInput() let pages = client.listRolesPaginated(input: input) do { for try await page in pages { guard let roles = page.roles else { print("Error: no roles returned.") continue } for role in roles { if let name = role.roleName { roleList.append(name) } } } } catch { print("ERROR: listRoles:", dump(error)) throw error } return roleList }
-
如需 API 詳細資訊,請參閱 AWS SDK for Swift API reference 中的 ListRoles
。
-
- AWS SDK for .NET
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /// <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 詳細資訊,請參閱 AWS SDK for .NET API Reference 中的 ListRoles。
-
如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱 將此服務與 AWS SDK 搭配使用。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。