This guide explains how to securely create a new user on a Linux EC2 instance, configure SSH access using a .pem key file, and enable passwordless sudo access.
- Access to an existing EC2 instance
- A
.pemprivate key file (e.g.,<user_name>.pem) - SSH access to the instance using an admin user (e.g.,
ec2-user)
Generate a public key from your existing private key (.pem):
ssh-keygen -y -f <user_name>.pemIt will output a long line starting with ssh-rsa AAAA.... Copy this public key for later use.
sudo adduser <user_name> --disabled-passwordThis creates a new user named <user_name> and disables password-based login.
sudo usermod -aG sudo <user_name>This allows <user_name> to run commands as sudo.
Switch to the new user:
sudo su - <user_name>Create the .ssh directory and set correct permissions:
mkdir ~/.ssh
chmod 700 ~/.ssh
touch ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keysEdit the authorized_keys file:
nano ~/.ssh/authorized_keysPaste the public key ssh-rsa generate from Step 1 into this file and save it. Exit the <user_name> session:
exitEdit the sudoers file using a safe method:
sudo visudoAdd the following line:
<user_name> ALL=(ALL) NOPASSWD: ALLSave and exit (Ctrl+X, then Y, then Enter).
From your local machine:
ssh -i <user_name>.pem <user_name>@<your-ec2-public-ip>Then run a sudo command:
sudo whoamiExpected output:
rootThen try a sudo command:
sudo ls /rootExpected output:
You should not be prompted for a password anymore.If you want to restrict <user_name> to specific commands (not full sudo), you can replace the line with something like:
<user_name> ALL=(ALL) NOPASSWD:/bin/systemctl restart apache2π References: