Create IAM User with Java

How to create IAM user with AWS SDK in Java ?

Step 1 – add dependencies

After you create your project, add these dependencies to the pom.xml file.

    <dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.25.12</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>iam</artifactId>
</dependency>
</dependencies>

Step 2 – Using the SDK in your Java class

Create IAM Client

First you need to create an IAM client.

IamClient iam = IamClient.builder().build();

Create User request and response

Then create request and response.

try {
IamClient iam = IamClient.builder().build();
CreateUserRequest request = CreateUserRequest.builder().userName("testuser").build();
CreateUserResponse response = iam.createUser(request);
System.out.println(response);
} catch(IamException ex) {
System.err.println(ex.awsErrorDetails().errorMessage());
}

Now run the application.

Output :

Creating IAM User using AWS SDK through Java
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
CreateUserResponse(User=User(Path=/, UserName=testuser, UserId=AIDA47CRVZHM4Q2U333NM, Arn=arn:aws:iam::891377011161:user/testuser, CreateDate=2024-03-19T13:38:28Z))

SLF4J is automatically added to your project when AWS SDK is used.

To avoid those SLF4J warnings, remove existing in your project and add slf4j-simple dependency to your project.

Check in AWS console :

You can see the testuser being created.

Complete program

package org.example;

import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.CreateUserRequest;
import software.amazon.awssdk.services.iam.model.CreateUserResponse;
import software.amazon.awssdk.services.iam.model.IamException;

public class CreateIAMUser {
public static void main(String[] args) {
System.out.println("Creating IAM User using AWS SDK through Java");
try {
IamClient iam = IamClient.builder().build();
CreateUserRequest request = CreateUserRequest.builder().userName("testuser").build();
CreateUserResponse response = iam.createUser(request);
System.out.println(response);
} catch(IamException ex) {
System.err.println(ex.awsErrorDetails().errorMessage());
}
}
}