ListUsers 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

ListUsers 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 ListUsers

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/// <summary> /// List IAM users. /// </summary> /// <returns>A list of IAM users.</returns> public async Task<List<User>> ListUsersAsync() { var listUsersPaginator = _IAMService.Paginators.ListUsers(new ListUsersRequest()); var users = new List<User>(); await foreach (var response in listUsersPaginator.Responses) { users.AddRange(response.Users); } return users; }
  • 如需 API 詳細資訊,請參閱 ListUsers AWS SDK for .NET 參考中的 API

Bash
AWS CLI 使用 Bash 指令碼
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function iam_list_users # # List the IAM users in the account. # # Returns: # The list of users names # And: # 0 - If the user already exists. # 1 - If the user doesn't exist. ############################################################################### function iam_list_users() { local option OPTARG # Required to use getopts command in a function. local error_code # bashsupport disable=BP5008 function usage() { echo "function iam_list_users" echo "Lists the AWS Identity and Access Management (IAM) user in the account." echo "" } # Retrieve the calling parameters. while getopts "h" option; do case "${option}" in h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 local response response=$(aws iam list-users \ --output text \ --query "Users[].UserName") error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports list-users operation failed.$response" return 1 fi echo "$response" return 0 }
  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 ListUsers

C++
C++ 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

bool AwsDoc::IAM::listUsers(const Aws::Client::ClientConfiguration &clientConfig) { const Aws::String DATE_FORMAT = "%Y-%m-%d"; Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::ListUsersRequest request; bool done = false; bool header = false; while (!done) { auto outcome = iam.ListUsers(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to list iam users:" << outcome.GetError().GetMessage() << std::endl; return false; } if (!header) { std::cout << std::left << std::setw(32) << "Name" << std::setw(30) << "ID" << std::setw(64) << "Arn" << std::setw(20) << "CreateDate" << std::endl; header = true; } const auto &users = outcome.GetResult().GetUsers(); for (const auto &user: users) { std::cout << std::left << std::setw(32) << user.GetUserName() << std::setw(30) << user.GetUserId() << std::setw(64) << user.GetArn() << std::setw(20) << user.GetCreateDate().ToGmtString(DATE_FORMAT.c_str()) << std::endl; } if (outcome.GetResult().GetIsTruncated()) { request.SetMarker(outcome.GetResult().GetMarker()); } else { done = true; } } return true; }
  • 如需 API 詳細資訊,請參閱 ListUsers AWS SDK for C++ 參考中的 API

CLI
AWS CLI

列出 IAM 使用者

下列list-users命令列出目前帳戶中的 IAM 使用者。

aws iam list-users

輸出:

{ "Users": [ { "UserName": "Adele", "Path": "/", "CreateDate": "2013-03-07T05:14:48Z", "UserId": "AKIAI44QH8DHBEXAMPLE", "Arn": "arn:aws:iam::123456789012:user/Adele" }, { "UserName": "Bob", "Path": "/", "CreateDate": "2012-09-21T23:03:13Z", "UserId": "AKIAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::123456789012:user/Bob" } ] }

如需詳細資訊,請參閱 IAM 使用者指南中的列出 Word 使用者AWS IAM

  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 ListUsers

Go
SDK for Go V2
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import ( "context" "encoding/json" "errors" "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" "github.com/aws/smithy-go" ) // UserWrapper encapsulates user actions used in the examples. // It contains an IAM service client that is used to perform user actions. type UserWrapper struct { IamClient *iam.Client } // ListUsers gets up to maxUsers number of users. func (wrapper UserWrapper) ListUsers(ctx context.Context, maxUsers int32) ([]types.User, error) { var users []types.User result, err := wrapper.IamClient.ListUsers(ctx, &iam.ListUsersInput{ MaxItems: aws.Int32(maxUsers), }) if err != nil { log.Printf("Couldn't list users. Here's why: %v\n", err) } else { users = result.Users } return users, err }
  • 如需 API 詳細資訊,請參閱 ListUsers AWS SDK for Go 參考中的 API

Java
Java 2.x 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import software.amazon.awssdk.services.iam.model.AttachedPermissionsBoundary; import software.amazon.awssdk.services.iam.model.IamException; import software.amazon.awssdk.services.iam.model.ListUsersRequest; import software.amazon.awssdk.services.iam.model.ListUsersResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; import software.amazon.awssdk.services.iam.model.User; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListUsers { public static void main(String[] args) { Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); listAllUsers(iam); System.out.println("Done"); iam.close(); } public static void listAllUsers(IamClient iam) { try { boolean done = false; String newMarker = null; while (!done) { ListUsersResponse response; if (newMarker == null) { ListUsersRequest request = ListUsersRequest.builder().build(); response = iam.listUsers(request); } else { ListUsersRequest request = ListUsersRequest.builder() .marker(newMarker) .build(); response = iam.listUsers(request); } for (User user : response.users()) { System.out.format("\n Retrieved user %s", user.userName()); AttachedPermissionsBoundary permissionsBoundary = user.permissionsBoundary(); if (permissionsBoundary != null) System.out.format("\n Permissions boundary details %s", permissionsBoundary.permissionsBoundaryTypeAsString()); } if (!response.isTruncated()) { done = true; } else { newMarker = response.marker(); } } } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 如需 API 詳細資訊,請參閱 ListUsers AWS SDK for Java 2.x 參考中的 API

JavaScript
SDK for JavaScript (v3)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

列出使用者。

import { ListUsersCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); export const listUsers = async () => { const command = new ListUsersCommand({ MaxItems: 10 }); const response = await client.send(command); for (const { UserName, CreateDate } of response.Users) { console.log(`${UserName} created on: ${CreateDate}`); } return response; };
SDK for JavaScript (v2)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the IAM service object var iam = new AWS.IAM({ apiVersion: "2010-05-08" }); var params = { MaxItems: 10, }; iam.listUsers(params, function (err, data) { if (err) { console.log("Error", err); } else { var users = data.Users || []; users.forEach(function (user) { console.log("User " + user.UserName + " created", user.CreateDate); }); } });
Kotlin
SDK for Kotlin
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun listAllUsers() { IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.listUsers(ListUsersRequest { }) response.users?.forEach { user -> println("Retrieved user ${user.userName}") val permissionsBoundary = user.permissionsBoundary if (permissionsBoundary != null) { println("Permissions boundary details ${permissionsBoundary.permissionsBoundaryType}") } } } }
  • 如需 API 詳細資訊,請參閱 ListUsers AWS for Kotlin SDK 參考中的 API

PHP
適用於 PHP 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

$uuid = uniqid(); $service = new IAMService(); public function listUsers($pathPrefix = "", $marker = "", $maxItems = 0) { $listUsersArguments = []; if ($pathPrefix) { $listUsersArguments["PathPrefix"] = $pathPrefix; } if ($marker) { $listUsersArguments["Marker"] = $marker; } if ($maxItems) { $listUsersArguments["MaxItems"] = $maxItems; } return $this->iamClient->listUsers($listUsersArguments); }
  • 如需 API 詳細資訊,請參閱 ListUsers AWS SDK for PHP 參考中的 API

PowerShell
for PowerShell 工具

範例 1:此範例會擷取目前 中的使用者集合 AWS 帳戶。

Get-IAMUserList

輸出:

Arn : arn:aws:iam::123456789012:user/Administrator CreateDate : 10/16/2014 9:03:09 AM PasswordLastUsed : 3/4/2015 12:12:33 PM Path : / UserId : 7K3GJEANSKZF2EXAMPLE1 UserName : Administrator Arn : arn:aws:iam::123456789012:user/Bob CreateDate : 4/6/2015 12:54:42 PM PasswordLastUsed : 1/1/0001 12:00:00 AM Path : / UserId : L3EWNONDOM3YUEXAMPLE2 UserName : bab Arn : arn:aws:iam::123456789012:user/David CreateDate : 12/10/2014 3:39:27 PM PasswordLastUsed : 3/19/2015 8:44:04 AM Path : / UserId : Y4FKWQCXTA52QEXAMPLE3 UserName : David
  • 如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考中的 ListUsers

Python
SDK for Python (Boto3)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

def list_users(): """ Lists the users in the current account. :return: The list of users. """ try: users = list(iam.users.all()) logger.info("Got %s users.", len(users)) except ClientError: logger.exception("Couldn't get users.") raise else: return users
  • 如需 API 詳細資訊,請參閱 ListUsers AWS SDK for Python (Boto3) Word 參考中的 API

Ruby
Ruby 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

# Lists all users in the AWS account # # @return [Array<Aws::IAM::Types::User>] An array of user objects def list_users users = [] @iam_client.list_users.each_page do |page| page.users.each do |user| users << user end end users rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing users: #{e.message}") [] end
  • 如需 API 詳細資訊,請參閱 ListUsers AWS SDK for Ruby 參考中的 API

Rust
Rust 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

pub async fn list_users( client: &iamClient, path_prefix: Option<String>, marker: Option<String>, max_items: Option<i32>, ) -> Result<ListUsersOutput, SdkError<ListUsersError>> { let response = client .list_users() .set_path_prefix(path_prefix) .set_marker(marker) .set_max_items(max_items) .send() .await?; Ok(response) }
  • 如需 API 詳細資訊,請參閱 ListUsers AWS for Rust SDK 參考中的 API

Swift
Swift 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

import AWSIAM import AWSS3 public func listUsers() async throws -> [MyUserRecord] { var userList: [MyUserRecord] = [] // Use "Paginated" to get all the users. // This lets the SDK handle the 'isTruncated' in "ListUsersOutput". let input = ListUsersInput() let output = client.listUsersPaginated(input: input) do { for try await page in output { guard let users = page.users else { continue } for user in users { if let id = user.userId, let name = user.userName { userList.append(MyUserRecord(id: id, name: name)) } } } } catch { print("ERROR: listUsers:", dump(error)) throw error } return userList }
  • 如需 API 詳細資訊,請參閱 ListUsers AWS for Swift SDK 參考中的 API