How to Add New User with Key Pair in AWS EC2. Learn how to create new user with new key pair and provide separate access to developers. Instead of using the default private key for all operations you can create additional users and share the corresponding private key to access the instance.
In this guide you are going to learn how to create new SSH key pair with public key and private key and add it to your EC2 instance.
Pem key file to access the instance SSH that you downloaded while creating the instance.
Create New Key Pair
Login to your AWS console and navigate to EC2 >> NETWORK & SECURITY >> Key Pairs.
Click Create Key pair.
For Name enter a name to identify your key.
For File Format choose pem which is the default format used by EC2. You can also use ppk format if you wish to use PUTTY to access the instance.
Click Create key pair.
Now the private key will be downloaded to your browser. Save the key safely.
Note: This is the only time you get the key pair. You cannot download the key pair if you lost it.
To use the
.pem key you need to setup correct permissions, otherwise you cannot use it to connect to the instance.
chmod 400 key_pair_name.pem
Retrieve the Public Key from the Private Key
Once you get the private key, you can retrieve the public key easily using the following command.
ssh-keygen -y -f key-pair-name.pem
This command returns the public key similar to the one below.
Copy the public key.
Create New User
SSH to your EC2 instance and perform the below steps to add user.
adduser command to create new user.
For Ubuntu users use the following command.
sudo adduser username --disabled-password
This command will create a user with the specified username without password.
For Amazon Linux or Amazon Linux 2 users use the following command.
sudo adduser username
Add the Public Key to New User
Once the user is created you need to add the retrieved public key to the new user account.
Switch to the new user.
sudo su - username
This command switches from the default
ec2-user to the new user you created in the previous step.
Navigate to the
home directory of the new user.
Create a new
Setup appropriate permissions.
chmod 700 .ssh
Create a file named
authorized_keys in the
.ssh directory and change its file permissions to
600 (only the owner can read or write to the file).
Setup appropriate permissions for the file.
chmod 600 .ssh/authorized_keys
Add the retrieved public key to this file.
Note: The public key should be pasted in a single line. It should not be split over multiple lines.
CTRL + X followed by
ENTER to save and exit the file.
Now you can login to your EC2 instance SSH using the corresponding private key.
If you wish to remove the user, you can easily remove it using the
-r option to remove the home directory. You can also skip this option if you wish to keep the home directory.
sudo userdel -r username
Now you have learned how to create new user with public key and private key on your AWS EC2 instance.