Skip to content

Instantly share code, notes, and snippets.

@bathivinod
Last active June 24, 2025 09:34
Show Gist options
  • Select an option

  • Save bathivinod/6fa89dc64a69fe9c5e8c8bcc9da9bcb7 to your computer and use it in GitHub Desktop.

Select an option

Save bathivinod/6fa89dc64a69fe9c5e8c8bcc9da9bcb7 to your computer and use it in GitHub Desktop.
This guide explains how to securely create a new user with sudo permissions on a Linux EC2 instance

πŸ‘€ Adding a New EC2 User with SSH Key Access and Passwordless Sudo

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.


πŸ”§ Prerequisites

  • Access to an existing EC2 instance
  • A .pem private key file (e.g., <user_name>.pem)
  • SSH access to the instance using an admin user (e.g., ec2-user)

πŸͺͺ Step 1: Generate the Public Key from PEM

Generate a public key from your existing private key (.pem):

ssh-keygen -y -f <user_name>.pem

It will output a long line starting with ssh-rsa AAAA.... Copy this public key for later use.

πŸ‘€ Step 2: Create a New User Without a Password

sudo adduser <user_name> --disabled-password

This creates a new user named <user_name> and disables password-based login.

πŸ”’ Step 3: Add the User to the Sudo Group

sudo usermod -aG sudo <user_name>

This allows <user_name> to run commands as sudo.

πŸ“‚ Step 4: Set Up SSH Directory and Key

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_keys

Edit the authorized_keys file:

nano ~/.ssh/authorized_keys

Paste the public key ssh-rsa generate from Step 1 into this file and save it. Exit the <user_name> session:

exit

βœ… Step 5: Configure Passwordless Sudo

Edit the sudoers file using a safe method:

sudo visudo

Add the following line:

<user_name> ALL=(ALL) NOPASSWD: ALL

Save and exit (Ctrl+X, then Y, then Enter).

πŸ” Step 6: Test SSH and Sudo Access

From your local machine:

ssh -i <user_name>.pem <user_name>@<your-ec2-public-ip>

Then run a sudo command:

sudo whoami

Expected output:

root

Then try a sudo command:

sudo ls /root

Expected output:

You should not be prompted for a password anymore.

πŸ›  Optional (Security Consideration):

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:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment