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

CreateUser 与 Amazon SDK 或 CLI 配合使用

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

操作示例是大型程序的代码摘录,必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

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

/// <summary> /// Create an IAM user. /// </summary> /// <param name="userName">The username for the new IAM user.</param> /// <returns>The IAM user that was created.</returns> public async Task<User> CreateUserAsync(string userName) { var response = await _IAMService.CreateUserAsync(new CreateUserRequest { UserName = userName }); return response.User; }
  • 有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 CreateUser

Bash
Amazon CLI 及 Bash 脚本
注意

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

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function iam_create_user # # This function creates the specified IAM user, unless # it already exists. # # Parameters: # -u user_name -- The name of the user to create. # # Returns: # The ARN of the user. # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function iam_create_user() { local user_name response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function iam_create_user" echo "Creates an WS Identity and Access Management (IAM) user. You must supply a username:" echo " -u user_name The name of the user. It must be unique within the account." echo "" } # Retrieve the calling parameters. while getopts "u:h" option; do case "${option}" in u) user_name="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$user_name" ]]; then errecho "ERROR: You must provide a username with the -u parameter." usage return 1 fi iecho "Parameters:\n" iecho " User name: $user_name" iecho "" # If the user already exists, we don't want to try to create it. if (iam_user_exists "$user_name"); then errecho "ERROR: A user with that name already exists in the account." return 1 fi response=$(aws iam create-user --user-name "$user_name" \ --output text \ --query 'User.Arn') local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports create-user operation failed.$response" return 1 fi echo "$response" return 0 }
  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 CreateUser

C++
SDK for C++
注意

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

Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::CreateUserRequest create_request; create_request.SetUserName(userName); auto create_outcome = iam.CreateUser(create_request); if (!create_outcome.IsSuccess()) { std::cerr << "Error creating IAM user " << userName << ":" << create_outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully created IAM user " << userName << std::endl; } return create_outcome.IsSuccess();
  • 有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考中的 CreateUser

CLI
Amazon CLI

示例 1:创建 IAM 用户

以下 create-user 命令可在当前账户中创建一个名为 Bob 的 IAM 用户。

aws iam create-user \ --user-name Bob

输出:

{ "User": { "UserName": "Bob", "Path": "/", "CreateDate": "2023-06-08T03:20:41.270Z", "UserId": "AIDAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::123456789012:user/Bob" } }

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

示例 2:在指定路径创建 IAM 用户

以下 create-user 命令可在指定路径创建一个名为 Bob 的 IAM 用户。

aws iam create-user \ --user-name Bob \ --path /division_abc/subdivision_xyz/

输出:

{ "User": { "Path": "/division_abc/subdivision_xyz/", "UserName": "Bob", "UserId": "AIDAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::12345678012:user/division_abc/subdivision_xyz/Bob", "CreateDate": "2023-05-24T18:20:17+00:00" } }

有关更多信息,请参阅《Amazon IAM 用户指南》中的 IAM 标识符

示例 3:创建带有标签的 IAM 用户

以下 create-user 命令将创建一个名为 Bob 且带有标签的 IAM 用户。此示例使用带有以下 JSON 格式标签的 --tags 参数标志:'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'。或者,--tags 标志可与简写格式的标签一起使用:'Key=Department,Value=Accounting Key=Location,Value=Seattle'

aws iam create-user \ --user-name Bob \ --tags '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'

输出:

{ "User": { "Path": "/", "UserName": "Bob", "UserId": "AIDAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::12345678012:user/Bob", "CreateDate": "2023-05-25T17:14:21+00:00", "Tags": [ { "Key": "Department", "Value": "Accounting" }, { "Key": "Location", "Value": "Seattle" } ] } }

有关更多信息,请参阅《Amazon IAM 用户指南》中的标记 IAM 用户

示例 3:创建具有设定权限边界的 IAM 用户

以下 create-user 命令将创建一个名为 Bob 且权限边界为 AmazonS3FullAccess 的 IAM 用户。

aws iam create-user \ --user-name Bob \ --permissions-boundary arn:aws:iam::aws:policy/AmazonS3FullAccess

输出:

{ "User": { "Path": "/", "UserName": "Bob", "UserId": "AIDAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::12345678012:user/Bob", "CreateDate": "2023-05-24T17:50:53+00:00", "PermissionsBoundary": { "PermissionsBoundaryType": "Policy", "PermissionsBoundaryArn": "arn:aws:iam::aws:policy/AmazonS3FullAccess" } } }

有关更多信息,请参阅《Amazon IAM 用户指南》中的 IAM 实体的权限边界

  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 CreateUser

Go
适用于 Go V2 的 SDK
注意

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

// 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 } // CreateUser creates a new user with the specified name. func (wrapper UserWrapper) CreateUser(ctx context.Context, userName string) (*types.User, error) { var user *types.User result, err := wrapper.IamClient.CreateUser(ctx, &iam.CreateUserInput{ UserName: aws.String(userName), }) if err != nil { log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err) } else { user = result.User } return user, err }
  • 有关 API 详细信息,请参阅 Amazon SDK for Go API 参考中的 CreateUser

Java
SDK for Java 2.x
注意

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

import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.services.iam.model.CreateUserRequest; import software.amazon.awssdk.services.iam.model.CreateUserResponse; import software.amazon.awssdk.services.iam.model.IamException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; import software.amazon.awssdk.services.iam.waiters.IamWaiter; import software.amazon.awssdk.services.iam.model.GetUserRequest; import software.amazon.awssdk.services.iam.model.GetUserResponse; /** * 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 CreateUser { public static void main(String[] args) { final String usage = """ Usage: <username>\s Where: username - The name of the user to create.\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String username = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); String result = createIAMUser(iam, username); System.out.println("Successfully created user: " + result); iam.close(); } public static String createIAMUser(IamClient iam, String username) { try { // Create an IamWaiter object. IamWaiter iamWaiter = iam.waiter(); CreateUserRequest request = CreateUserRequest.builder() .userName(username) .build(); CreateUserResponse response = iam.createUser(request); // Wait until the user is created. GetUserRequest userRequest = GetUserRequest.builder() .userName(response.user().userName()) .build(); WaiterResponse<GetUserResponse> waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest); waitUntilUserExists.matched().response().ifPresent(System.out::println); return response.user().userName(); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • 有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 CreateUser

JavaScript
SDK for JavaScript (v3)
注意

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

创建 用户。

import { CreateUserCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} name */ export const createUser = (name) => { const command = new CreateUserCommand({ UserName: name }); return client.send(command); };
SDK for JavaScript (v2)
注意

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

// 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 = { UserName: process.argv[2], }; iam.getUser(params, function (err, data) { if (err && err.code === "NoSuchEntity") { iam.createUser(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } }); } else { console.log( "User " + process.argv[2] + " already exists", data.User.UserId ); } });
Kotlin
适用于 Kotlin 的 SDK
注意

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

suspend fun createIAMUser(usernameVal: String?): String? { val request = CreateUserRequest { userName = usernameVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createUser(request) return response.user?.userName } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 CreateUser

PHP
适用于 PHP 的 SDK
注意

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

$uuid = uniqid(); $service = new IAMService(); $user = $service->createUser("iam_demo_user_$uuid"); echo "Created user with the arn: {$user['Arn']}\n"; /** * @param string $name * @return array * @throws AwsException */ public function createUser(string $name): array { $result = $this->iamClient->createUser([ 'UserName' => $name, ]); return $result['User']; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考中的 CreateUser

PowerShell
适用于 PowerShell 的工具

示例 1:此示例创建一个名为 Bob 的 IAM 用户。如果 Bob 需要登录 Amazon 控制台,则必须单独运行命令 New-IAMLoginProfile 来创建带有密码的登录配置文件。如果 Bob 需要运行 Amazon PowerShell 或跨平台 CLI 命令或者 Amazon 进行 API 调用,则必须单独运行 New-IAMAccessKey 命令来创建访问密钥。

New-IAMUser -UserName Bob

输出:

Arn : arn:aws:iam::123456789012:user/Bob CreateDate : 4/22/2015 12:02:11 PM PasswordLastUsed : 1/1/0001 12:00:00 AM Path : / UserId : AIDAJWGEFDMEMEXAMPLE1 UserName : Bob
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 CreateUser

Python
SDK for Python (Boto3)
注意

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

def create_user(user_name): """ Creates a user. By default, a user has no permissions or access keys. :param user_name: The name of the user. :return: The newly created user. """ try: user = iam.create_user(UserName=user_name) logger.info("Created user %s.", user.name) except ClientError: logger.exception("Couldn't create user %s.", user_name) raise else: return user
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 CreateUser

Ruby
适用于 Ruby 的 SDK
注意

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

# Creates a user and their login profile # # @param user_name [String] The name of the user # @param initial_password [String] The initial password for the user # @return [String, nil] The ID of the user if created, or nil if an error occurred def create_user(user_name, initial_password) response = @iam_client.create_user(user_name: user_name) @iam_client.wait_until(:user_exists, user_name: user_name) @iam_client.create_login_profile( user_name: user_name, password: initial_password, password_reset_required: true ) @logger.info("User '#{user_name}' created successfully.") response.user.user_id rescue Aws::IAM::Errors::EntityAlreadyExists @logger.error("Error creating user '#{user_name}': user already exists.") nil rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating user '#{user_name}': #{e.message}") nil end
  • 有关 API 详细信息,请参阅 Amazon SDK for Ruby API 参考中的 CreateUser

Rust
适用于 Rust 的 SDK
注意

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

pub async fn create_user(client: &iamClient, user_name: &str) -> Result<User, iamError> { let response = client.create_user().user_name(user_name).send().await?; Ok(response.user.unwrap()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 CreateUser

Swift
适用于 Swift 的 SDK
注意

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

import AWSIAM import AWSS3 public func createUser(name: String) async throws -> String { let input = CreateUserInput( userName: name ) do { let output = try await client.createUser(input: input) guard let user = output.user else { throw ServiceHandlerError.noSuchUser } guard let id = user.userId else { throw ServiceHandlerError.noSuchUser } return id } catch { print("ERROR: createUser:", dump(error)) throw error } }
  • 有关 API 详细信息,请参阅 Amazon SDK for Swift API 参考中的 CreateUser

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