View a markdown version of this page

Usare CreateUser con un AWS SDK o CLI - AWS Identity and Access Management

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à.

Usare CreateUser con un AWS SDK o CLI

I seguenti esempi di codice mostrano come usare 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
SDK per .NET
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.

/// <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 CreateUser nel AWS SDK per .NET Riferimento API.

Bash
AWS CLI con script Bash
Nota

C'è dell'altro 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 AWS 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 }
  • Per i dettagli sull'API, consulta CreateUser nel AWS CLI Riferimento al comando.

C++
SDK per C++
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.

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 CreateUser nel AWS SDK per C++ Riferimento API.

CLI
AWS CLI

Esempio 1: Come creare un utente IAM

Quanto segue create-user l'esempio 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, vedere Creazione di un utente IAM nel tuo AWS conto nel AWS Guida per l'utente IAM.

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

Quanto segue create-user l'esempio 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: creare un utente IAM con tag

Quanto segue create-user l'esempio crea un utente IAM denominato Bob con tag. Questo esempio utilizza --tags flag di parametro con il seguente JSON-formatted tag: '{"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 4: creare un utente IAM con un limite di autorizzazioni impostato

Quanto segue create-user l'esempio crea un utente IAM denominato Bob con il limite delle autorizzazioni di AmazonS3FullAccess.

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 CreateUser nel AWS CLI Riferimento al comando.

Go
SDK per Go V2
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.

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 CreateUser nel AWS SDK per Go Riferimento API.

Java
SDK per Java 2.x
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.

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 CreateUser nel AWS SDK for Java 2.x Riferimento API.

JavaScript
SDK per JavaScript (v3)
Nota

C'è dell'altro 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'è dell'altro 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'è di più 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.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createUser(request) return response.user?.userName } }
  • Per i dettagli sull'API, consulta CreateUser nel AWS Riferimento all'API SDK per Kotlin.

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 CreateUser nel AWS SDK per PHP Riferimento API.

PowerShell
Strumenti per PowerShell V4

Esempio 1: questo esempio crea un utente IAM denominato Bob. Se Bob deve accedere al AWS console, quindi è necessario eseguire separatamente il comando New-IAMLoginProfile per creare un profilo di accesso con una password. Se Bob ha bisogno di correre AWS PowerShell o comandi CLI multipiattaforma o make AWS chiamate API, quindi è necessario eseguire separatamente New-IAMAccessKey comando per creare 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, vedi CreateUser nel AWS Strumenti per PowerShell Riferimento al cmdlet (V4).

Strumenti per PowerShell V5

Esempio 1: questo esempio crea un utente IAM denominato Bob. Se Bob deve accedere al AWS console, quindi è necessario eseguire separatamente il comando New-IAMLoginProfile per creare un profilo di accesso con una password. Se Bob ha bisogno di correre AWS PowerShell o comandi CLI multipiattaforma o make AWS chiamate API, quindi è necessario eseguire separatamente New-IAMAccessKey comando per creare 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, vedi CreateUser nel AWS Strumenti per PowerShell Riferimento al cmdlet (V5).

Python
SDK per Python (Boto3)
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.

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 nel AWS Riferimento alle API SDK per Python (Boto3).

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 CreateUser nel AWS SDK per Ruby Riferimento API.

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 sull'API, consulta CreateUser nel AWS SDK per Rust API di riferimento.

SAP ABAP
SDK per SAP ABAP
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.

TRY. oo_result = lo_iam->createuser( iv_username = iv_user_name ). MESSAGE 'User created successfully.' TYPE 'I'. CATCH /aws1/cx_iamentityalrdyexex. MESSAGE 'User already exists.' TYPE 'E'. CATCH /aws1/cx_iamlimitexceededex. MESSAGE 'Limit exceeded for IAM users.' TYPE 'E'. CATCH /aws1/cx_iamnosuchentityex. MESSAGE 'Entity does not exist.' TYPE 'E'. ENDTRY.
  • Per i dettagli sull'API, consulta CreateUser nel AWS Riferimento all'API SDK per SAP ABAP.

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 CreateUser nel AWS Riferimento SDK per Swift API.

Per un elenco completo di AWS Guide per sviluppatori SDK ed esempi di codice, consulta L'utilizzo di questo servizio con un AWS SDK. Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell’SDK.