Picture of Brian Love wearing black against a dark wall in Portland, OR.

Brian Love

Add new sudo user to EC2 Ubuntu

This post is more for me as a reference guide for adding a new user to Ubuntu. I just spun up a new instance on AWS and want to create a new user that has sudo privileges so I can use this user rather than the default ubuntu root user. I also want to have SSH use my computer’s private key rather than having to authenticate using the private key generated by AWS.

SSH to EC2 Instance

Connect to the EC2 instance using your private key (provided by AWS when you created the key pair).

$ ssh -i mykey.pem ubuntu@public-dns.compute-1.amazonaws.com

Create a new User

First, add the user. I am going to specify the home directory to be created, the default shell to use (bash), as well as add the new user to the admin group:

$ sudo adduser --home /home/blove --shell /bin/bash --ingroup admin *username*

After creating the new user, let’s give the user the ability to use the sudo command. I am going to make it so that the user doesn’t need to enter their password after using the sudo command. Let’s do this by using our favorite editor, vi.

$ sudo vi /etc/sudoers

Add the following line of code to the file. I added this after the root user in the User privilege specification section:

# User privilege specification
username ALL=(ALL) NOPASSWD:ALL

Setup SSH

I am running on a Mac and want to add my public key to the authorized_keys file for the new user I just created. This will allow me to connect via SSH without specifying the user’s password.

If you don’t have an SSH key on your Mac (located at ~/.ssh/id_rsa.pub), then you will need to generate one:

$ ssh-keygen -b 1024 -f user -t dsa

Now, copy the file to the server’s tmp directory:

$ scp -i mykey.pem ~/.ssh/id_rsa.pub ubuntu@public-dns.compute-1.amazonaws.com:/tmp/

Back on the server, copy this file to the home directory of the user we just created:

$ su username
$ cd ~
$ mkdir .ssh
$ cat /tmp/id_rsa.pub > .ssh/authorized_keys
$ chmod 600 .ssh/*
$ chmod 700 .ssh/

You should now be able to connect to the server using your newly created username without having to specify a password:

$ ssh username@public-dns.compute-1.amazonaws.com

You can further protect your ubuntu instance by disabling password logins to your machine. You can read more on how to do this in the Tips for Securing Your EC2 Instance article provided by Amazon.