How to create a user on Linux EC2 instance on AWS and add a public key to it using a shell script

Creating a user and adding a public key to it can be very tedious. In this article, we will see how this process can be automated using a shell script which can help us avoid human errors that can arise if we do the task manually.

Pre-requisites

  1. Basic understanding of Shell Scripts.
  2. AWS Account (Create if you don’t have one).
  3. EC2 Instance with the user having sudo access (Click here to learn to create an EC2 instance if you don’t have one or if you want to learn )

What will we do

  1. Create a script and a private-public key pair.
  2. Create a user using the script.

Create a script and a private-public key pair

Create a script with the following code in it. You can find the same code on my Github repo on the following link.

Github Link: https://github.com/shivalkarrahul/DevOps/blob/master/aws/shell-scripts/aws-ec2-create-user-add-public-key/provide-access.sh
File: provide-access.sh
helpFunction()
{ 
      echo ""
      printf "\033[1;32mUsage: $0 -K <internal.pem> -U <internal-user> -I <internal-ip> -u <user-to-be-created> -k <\"public-key-string-shared-by-the-user\">"
      echo ""
      echo -e "\t-K \".pem key of the server on which a new user has be created\""
      echo -e "\t-U UserName of the server on which a new user has be created"
      echo -e "\t-I IP of the server on which a new user has be created "
      echo -e "\t-u user to be created on the internal server"
      echo -e "\t-k \"public key string to be added shared by the user\""
      echo -e "Put Public Key in double quotes"

      echo -e  "e.g."
      echo "./provide-access.sh -U ubuntu -K /Users/cloudcover/Documents/Rahul/access/rahuls.pem -I 192.168.134.100  -u rahul -k  \"ssh-rsa Z1rbx6/F/ZntfkvKzX6e82oYOOLb9QtTu4IO+W560+afjp1xLOYqWKeEsZycq0iyHX5herNWxorLU3gGnwGSABCb+62yP3eaESMMHMR91OeDsxeLL41ABANofMROQ8yDjNcYVUxjKWyzNzuJxgnN5KngwkUOWHGbCFmHUsz1WVuWA+rhhk1CPZFywUdsDeGR/Dxd+oNKGvaKGIQuDqK1vY5GiLg0N+OvanTPbLper3/Z5A5d62fRF6+mensZGsKW543 key-name\""

      echo -e "\033[0m" #reset color
      exit 1 # Exit script after printing help
}

while getopts "I:K:U:u:k:" opt
do
   case "$opt" in
      K ) internalServerPemKey="$OPTARG" ;;
      U ) internalServerUser="$OPTARG" ;;	
      I ) internalServerIP="$OPTARG" ;;
      u ) userName="$OPTARG" ;;
      k ) keyString="$OPTARG" ;;
      ? ) helpFunction ;; # Print helpFunction in case parameter is non-existent
   esac
done

# Print helpFunction in case parameters are empty
if [ -z "$internalServerIP" ] || [ -z "$internalServerPemKey" ] || [ -z "$internalServerUser" ] || [ -z "$userName" ] || [ -z "$keyString" ]
then
      printf "\033[1;31m"
      echo "Some or all of the parameters are empty";
      helpFunction
fi

# Begin script in case all parameters are correct
printf "\033[1;33m------------------------------------------------------------------Before ssh"
echo -e "\033[0m" #reset color
echo ".pem key of the server on which a new user has be created		:  	$internalServerPemKey"
echo "UserName of the server on which a new user has be created		: 	$internalServerUser"
echo "IP of the server on which a new user has be created			:	$internalServerIP"
echo "user to be created on the internal server				:	$userName"
echo "public key string to be added shared by the user			:	$keyString"


printf "\033[1;31mLogging into: "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"

ssh -i "$internalServerPemKey" "$internalServerUser"@"$internalServerIP" << HERE
      printf "\033[1;33m------------------------------------------------------------------After ssh"
      echo -e "\033[0m" #reset color
      echo "Creating user \"$userName\" <--- on="" ---=""> \"$internalServerIP\" <---"
      sudo useradd -m $userName
      sleep 2
      echo "Changing user to \"$userName\""
      sudo -i -u $userName bash << EOF
      echo "User Switched To;"
      whoami
      echo "creating dir: .ssh"
      mkdir -p .ssh
      echo "changing permission of dir .ssh to 700"
      chmod 700 .ssh
      echo "creating a file: .ssh/authorized_keys"
      touch .ssh/authorized_keys
      echo "changing permission of .ssh/authorized_keys to 600"
      chmod 600 .ssh/authorized_keys
      echo "appending $keyString "
      echo "to .ssh/authorized_keys"
      echo '$keyString' >> .ssh/authorized_keys
      echo "Content of .ssh/authorized_keys"
      cat .ssh/authorized_keys
      printf "\033[1;31mExiting from         ---> "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"\033[0m\n"
      #echo "Existing user	---> $userName"
EOF
HERE

Create a key-pair for the user to be created. Here, I ll store these keys in /tmp/

ssh-keygen

Create a key-pair

ls /tmp/id_rsa*

List the keys we created

Create a user using the script

Now, let's create a user with the following command. You need to change values on the script with the one valid for you. Execute the following command from your local linux system.

Before you execute the script, changes its permissions

chmod 744 provide-access.sh
./provide-access.sh -U ubuntu -K ~/Downloads/howtoforge-test.pem -I ec2-15-236-64-128.eu-west-3.compute.amazonaws.com -u rahul -k "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzS60i+fPFEYMbA1w8dLOFK2EAV+vFtlckSU
5+DGxtLHp3smpAxTDkKYJ33bM9Cs6toMDD0HITAH6VRyrgJ4V+Z4EpO6w8kHp3g2Fro5b4X2VX4GWsVdmkLkj0KbUhbd2sKTx/O2x+wNlxT7cUvr0ugii9FIXlXLLjwLsw47bEUNSIhwJB+x7u8tfOc00IBzhghCU9DjfGzMNxWdwpWg2GsAoRWQAT1YGO3laqPpxSVN6RKAzsTJ
gSar7bwJsjEtiCb7+of95SIR/lkP/e1hpsbuDUpc94mTAkde88pFPE/799w+YnbUwaj+1Y8e9R1QRjbs9Xh+b2wAgaAlMTPEFh [email protected]"

Here,

  • -U = ubuntu = User with sudo access to login in to the EC2 instance.
  • -K =~/Downloads/howtoforge-test.pem = Ureate to login in to the EC2 instance.
  • -I =ec2-15-236-64-128.eu-west-3.compute.amazonaws.com = IP of the EC2 instance.
  • -u = rahul = User to be created
  • -k = Public key of the user to be created.

These values will vary for you. Add values valid for you.

Create a user

You can see that the user has been created.

Now, you can log in to the EC2 instance to check if the user has been created or not.

ssh -i ~/Downloads/howtoforge-test.pem [email protected]
cat /etc/passwd | grep rahul

Check if the user is created

You can now try to login into the server using the user, i.e. rahul, that we just created. 

Before that, change permissions of the private key to be used to authenticate to the server.

chmod 400 /tmp/id_rsa.pub
ssh -i /tmp/id_rsa.pub [email protected]

Try to login

In the above screenshot, you can see that we were able to login into the server using the user we created.

Also, check the key we added to the user. You will find the public key we passed to the script was added to the server.

Check the key we added

Conclusion

In this article, we saw the script to automate the process of creating a user on the Ubuntu EC2 instance and adding a public key to it. 

This automation can help to minimize the effort required to create users manually and add public keys to them.

Share this page:

0 Comment(s)