I’m going to help you troubleshoot a particular issue that many AWS users face – locked out of SSH into your EC2 instance. This might happen if you have made some changes in firewall (in Ubuntu its ufw) for example you enabled it and allowed some port only and if that ssh connection broke or something, you can’t get reconnect. Don’t worry; I’ve got your back! In just couple of minutes, I’ll show you some quick steps to get you back on track.

Before we dive in….. there are couple of points to remember

1.) This procedure requires a stop and start of the EC2 instance. If the instance has any data stored on instance store volumes, that data is deleted after stopping the instance.

2.) If the instance is part of an Amazon EC2 Auto Scaling group, then terminating the instance might also stop instances within the Auto Scaling group.

3.) If the instance is launched by services that use AWS Auto Scaling, then terminating the instance might also stop instances within the Auto Scaling group.

4.) Instance termination depends on the instance scale-in protection settings for the Auto Scaling group. If the instance is part of an Auto Scaling group, temporarily remove the instance from the Auto Scaling group before starting the resolution steps.

5.) Stopping and starting the instance changes the public IP address of the instance. It’s a best practice to use an Elastic IP address instead of a public IP address when routing external traffic to the instance.

==============================================
Follow these steps to configure user-data for the instance:
==============================================

1.) Open the Amazon EC2 console.

2. Choose Instances from the navigation pane, and then select the instance that you plan to connect to.

3. Stop the instance.

4. Choose Actions, Instance Settings, Edit User Data.

5. Copy the following user data script into the Edit User Data dialog box, and then choose Save.

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
iptables -P INPUT ACCEPT
iptables -F
systemctl restart sshd.service || service sshd restart
if [[ $( cat /etc/hosts.[ad]* | grep -vE '^#' | awk 'NF' | wc -l) -ne 0 ]];\
then sudo sed -i '1i sshd2 sshd : ALL: allow' /etc/hosts.allow; fi
--//

6. Connect to the instance using SSH.

7. The preceding user data script is set to run on every reboot of the instance. After regaining access to the instance, remove the user data script.

Write A Comment