与 AWS SDK或CreateUser一起使用 CLI - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与 AWS SDK或CreateUser一起使用 CLI

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

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

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/// <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详细信息,请参阅 “AWS SDK for .NET API参考 CreateUser” 中的。

Bash
AWS CLI 使用 Bash 脚本
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

############################################################################### # 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 }
C++
SDK对于 C++
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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详细信息,请参阅 “AWS SDK for C++ API参考 CreateUser” 中的。

CLI
AWS 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" } }

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

示例 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" } }

有关更多信息,请参阅《AWS 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" } ] } }

有关更多信息,请参阅《用户指南》中的为IAM AWS IAM用户添加标签

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

以下create-user命令创建一个名为、权限边界为 Bob AmazonS3 FullAccess 的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" } } }

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

Go
SDK适用于 Go V2
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

// 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详细信息,请参阅 “AWS SDK for Go API参考 CreateUser” 中的。

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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详细信息,请参阅 “AWS SDK for Java 2.x API参考 CreateUser” 中的。

JavaScript
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

创建 用户。

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对于 JavaScript (v2)
注意

还有更多相关信息 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 = { 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
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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详细信息,请参阅CreateUser中的 Kotlin AWS SDK API 参考

PHP
SDK for PHP
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

$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详细信息,请参阅 “AWS SDK for PHP API参考 CreateUser” 中的。

PowerShell
用于 PowerShell

示例 1:此示例创建了一个名为的IAM用户Bob。如果 Bob 需要登录 AWS 控制台,则必须单独运行命令New-IAMLoginProfile来创建带有密码的登录配置文件。如果 Bob 需要运行 AWS PowerShell 或跨平台CLI命令或拨 AWS 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详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考CreateUser中的。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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详细信息,请参阅CreateUser中的 AWS SDKPython (Boto3) API 参考。

Ruby
SDK对于 Ruby
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

# 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详细信息,请参阅 “AWS SDK for Ruby API参考 CreateUser” 中的。

Rust
SDK对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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详细信息,请参见CreateUser中的 Rust AWS SDK API 参考

Swift
SDK为斯威夫特
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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详细信息,请参阅CreateUser中的 Swi AWS SDK ft API 参考