Search code examples
amazon-web-servicesamazon-ec2aws-java-sdkaws-java-sdk-2.x

How to create a user and password while launching AWS instance


Azure allows one to create the user and password during the creation of a virtual machine which can later be used for SSH into that VM.

How to create a user and password during run instance in AWS using Java SDK which can be used for SSH.

Currently I laucnh Vm as

  runInstancesRequest
                    .withTagSpecifications(tagSpecification)
                    .withImageId(ec2Configuration.getImageId())
                    .withInstanceType(ec2Configuration.getInstanceType())
                    .withMinCount(ec2Configuration.getMincount())
                    .withMaxCount(ec2Configuration.getMaxcount())
                    .withKeyName(ec2Configuration.getKeyPairName())
                    .withSecurityGroupIds(Arrays.asList(ec2Configuration.getSgId()));
                    .withMonitoring(true);
         
          
                RunInstancesResult result = amazonEC2Client.runInstances(
                        runInstancesRequest);

I want to add something like this

    runInstancesRequest
                    .withTagSpecifications(tagSpecification)
                    .withImageId(ec2Configuration.getImageId())
                    .withInstanceType(ec2Configuration.getInstanceType())
                    .withMinCount(ec2Configuration.getMincount())
                    .withMaxCount(ec2Configuration.getMaxcount())
                    .withKeyName(ec2Configuration.getKeyPairName())
                    .withSecurityGroupIds(Arrays.asList(ec2Configuration.getSgId()));
                    .withMonitoring(true)


                    .withUserName("newUser")
                    .withPassword("d@mnHardPassw0rd");
         
          
                RunInstancesResult result = amazonEC2Client.runInstances(
                        runInstancesRequest);          

I know AWS has default usernames and passwords based on the AMI but I want to make my own custom username and password while launching the VM.

Edit

Also, How to SSH to a Windows a instance? Is the RDP only option? How can I connect via the key pair and SSH? How to get it's administrator password.


Solution

  • You can add it using UserData:

    RunInstancesRequest.withUserData(String userData)
    

    and the user data can be found in the URL below

    https://aws.amazon.com/premiumsupport/knowledge-center/ec2-user-account-cloud-init-user-data/