Locked out of EC2 instance
There are a couple of ways you can lock yourself out of your EC2 instance.
- You lose your SSH private key
- The
ec2-user
gets corrupted somehow
Fortunately, there are ways to get back into your EC2 instance. The least invasive approach is to modify the UserData
.
There's a really good AWS article that describes how to do this. Below, I'll go over the steps you
need to do this.
Create a back-door user via User Data
First, you need to stop your EC2 instance. Go to EC2 > Actions > Instance State > Stop
Second, edit the UserData
. Go to EC2 > Actions > Instance Settings > View/Change User Data.
Third, paste in the following code snippet (replacing everything that's already there)
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [scripts-user, always]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
USER=robtest #1
adduser $USER #2
echo "$USER ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/cloud-init #3
mkdir /home/$USER/.ssh #4
echo "ssh-rsa AAAAB3NzaC1yc2EAAA....A38MHe0KAzY9Ob private.key" >> /home/$USER/.ssh/authorized_keys #5
--//
UserData
gets called once on first launch. The first 20 lines of code forces the EC2 instance to run the bash
script at the bottom for every launch.
This is what the bash script is doing:
- You're creating a user named
robtest
. Be sure to replace this with a username of your choice. - You create a regular Linux user (this is not an SFTP user)
- You grant this user sudo access, just like how
ec2-user
has sudo access - Create a
.ssh
directory. This needs to exist before you can create theauthorized_keys
file - You append a public key to
/home/robtest/.ssh/authorized_keys
. Make sure you replace the contents of the public key.
To generate a public key, run the following command on your local Mac:
ssh-keygen -t rsa -C private.key -f private.key -q -N ""
This generates two files:
private.key
: You'll use this tossh -i
into the instance momentarily. (Be sure tochmod 600
it)private.key.pub
: This is the public key, whose contents you paste into the bash script above.
Finally, hit Save.
Start your EC2 instance again: Go to EC2 > Actions > Instance State > Start
If all goes well, you should be able to SSH using your new username
.
Cleanup
If everything is working, make sure you delete your UserData
so that it doesn't keep running on subsequent launches.
Like before, you'll have to stop your instance in order to make the change.