Utilizzo CreateUser con un AWS SDK o una CLI - AWS Esempi di codice SDK

Sono disponibili altri esempi AWS SDK nel repository AWS Doc SDK Examples. GitHub

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Utilizzo CreateUser con un AWS SDK o una CLI

Gli esempi di codice seguenti mostrano come utilizzare CreateUser.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nei seguenti esempi di codice:

.NET
AWS SDK for .NET
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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; }
  • Per i dettagli sull'API, consulta la CreateUsersezione AWS SDK for .NET API Reference.

Bash
AWS CLI con lo script Bash
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 per C++
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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();
  • Per i dettagli sull'API, consulta la CreateUsersezione AWS SDK for C++ API Reference.

CLI
AWS CLI

Esempio 1: Come creare un utente IAM

Il comando create-user seguente crea un utente IAM denominato Bob nell'account corrente.

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

Output:

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

Per ulteriori informazioni, consulta Creare un utente IAM nel tuo AWS account nella Guida per l'utente AWS IAM.

Esempio 2: Come creare un utente IAM in un percorso specificato

Il comando create-user seguente crea un utente IAM denominato Bob nel percorso specificato.

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

Output:

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

Per ulteriori informazioni, consulta Identificatori IAM nella Guida per l'utente di IAM AWS .

Esempio 3: Come creare un utente IAM con tag

Il comando create-user seguente crea un utente IAM denominato Bob con tag. Questo esempio utilizza il flag del parametro --tags con i seguenti tag in formato JSON: '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'. In alternativa, il flag --tags può essere utilizzato con tag in formato abbreviato: 'Key=Department,Value=Accounting Key=Location,Value=Seattle'.

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

Output:

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

Per ulteriori informazioni, consulta Applicazione di tag a utenti IAM nella Guida per l'utente di IAM AWS .

Esempio 3: Come creare un utente IAM con un limite delle autorizzazioni impostato

Il create-user comando seguente crea un utente IAM denominato Bob con il limite delle autorizzazioni di AmazonS3. FullAccess

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

Output:

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

Per ulteriori informazioni, consulta Limiti delle autorizzazioni per le entità IAM nella Guida per l'utente di IAM AWS .

  • Per i dettagli sull'API, consulta Command Reference. CreateUserAWS CLI

Go
SDK per Go V2
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 } // 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 }
  • Per i dettagli sull'API, consulta la CreateUsersezione AWS SDK per Go API Reference.

Java
SDK per Java 2.x
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 ""; } }
  • Per i dettagli sull'API, consulta la CreateUsersezione AWS SDK for Java 2.x API Reference.

JavaScript
SDK per JavaScript (v3)
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

Creare l'utente.

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 per JavaScript (v2)
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 per Kotlin
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 } }
  • Per i dettagli sull'API, CreateUserconsulta AWS SDK for Kotlin API reference.

PHP
SDK per PHP
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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']; }
  • Per i dettagli sull'API, consulta la CreateUsersezione AWS SDK for PHP API Reference.

PowerShell
Strumenti per PowerShell

Esempio 1: questo esempio crea un utente IAM denominato Bob. Se Bob deve accedere alla AWS console, è necessario eseguire separatamente il comando New-IAMLoginProfile per creare un profilo di accesso con una password. Se Bob deve eseguire AWS PowerShell comandi CLI multipiattaforma o AWS effettuare chiamate API, è necessario eseguire separatamente New-IAMAccessKey il comando per creare le chiavi di accesso.

New-IAMUser -UserName Bob

Output:

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
  • Per i dettagli sull'API, vedere CreateUserin AWS Strumenti per PowerShell Cmdlet Reference.

Python
SDK per Python (Boto3)
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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
  • Per i dettagli sull'API, consulta CreateUser AWSSDK for Python (Boto3) API Reference.

Ruby
SDK per Ruby
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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
  • Per i dettagli sull'API, consulta la CreateUsersezione AWS SDK for Ruby API Reference.

Rust
SDK per Rust
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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()) }
  • Per i dettagli sulle API, consulta il riferimento CreateUserall'API AWS SDK for Rust.

Swift
SDK per Swift
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice 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 } }
  • Per i dettagli sull'API, consulta la CreateUserguida di riferimento all'API AWS SDK for Swift.