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 "33[1;32mUsage: $0 -K  -U  -I  -u  -k "
      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 "33[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 "33[1;31m"
      echo "Some or all of the parameters are empty";
      helpFunction
fi

# Begin script in case all parameters are correct
printf "33[1;33m------------------------------------------------------------------Before ssh"
echo -e "33[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 "33[1;31mLogging into: "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"33[0mn"

ssh -i "$internalServerPemKey" "$internalServerUser"@"$internalServerIP" << HERE
      printf "33[1;33m------------------------------------------------------------------After ssh"
      echo -e "33[0m" #reset color
      echo "Creating user "$userName"  "$internalServerIP" <---"
      sudo useradd -m $userName
      sleep 2
      echo "Changing user to "$userName""
      sudo -i -u $userName bash <> .ssh/authorized_keys
      echo "Content of .ssh/authorized_keys"
      cat .ssh/authorized_keys
      printf "33[1;31mExiting from         ---> "$internalServerPemKey" "$internalServerUser"@"$internalServerIP"33[0mn"
      #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

<img alt="Create a key-pair" data-ezsrc="https://kirelos.com/wp-content/uploads/2021/04/echo/screenshot_2021-03-21_at_75830_pm.png60709417b6005.jpg" ezimgfmt="rs rscb3 src ng ngcb3" height="231" loading="lazy" src="data:image/svg xml,” width=”750″>

ls /tmp/id_rsa*

<img alt="List the keys we created" data-ezsrc="https://kirelos.com/wp-content/uploads/2021/04/echo/screenshot_2021-03-21_at_75904_pm.png60709417dd9d7.jpg" ezimgfmt="rs rscb3 src ng ngcb3" height="60" loading="lazy" src="data:image/svg xml,” width=”750″>

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.

<img alt="Create a user" data-ezsrc="https://kirelos.com/wp-content/uploads/2021/04/echo/screenshot_2021-03-21_at_74900_pm.png607094183d82a.jpg" ezimgfmt="rs rscb3 src ng ngcb3" height="347" loading="lazy" src="data:image/svg xml,” width=”750″>

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

<img alt="Check if the user is created" data-ezsrc="https://kirelos.com/wp-content/uploads/2021/04/echo/screenshot_2021-03-21_at_75004_pm.png60709418772a5.jpg" ezimgfmt="rs rscb3 src ng ngcb3" height="300" loading="lazy" src="data:image/svg xml,” width=”750″>

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]

<img alt="Try to login" data-ezsrc="https://kirelos.com/wp-content/uploads/2021/04/echo/screenshot_2021-03-21_at_75454_pm.png60709418b2582.jpg" ezimgfmt="rs rscb3 src ng ngcb3" height="432" loading="lazy" src="data:image/svg xml,” width=”750″>

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.

<img alt="Check the key we added" data-ezsrc="https://kirelos.com/wp-content/uploads/2021/04/echo/screenshot_2021-03-21_at_75615_pm.png60709418ed019.jpg" ezimgfmt="rs rscb3 src ng ngcb3" height="122" loading="lazy" src="data:image/svg xml,” width=”750″>

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.