One of the most common issues people experience is loosing ssh connection to their instances which could be due to various reasons such as permissions, ownership or even firewalls.

You can easily resolve any of these issues using userdata. This will have to be done via the AWS Management console using the steps below:

1- Stop your instance.
2- In the console, select your instance, go to Actions -> Instance Settings -> View/Change User Data
3- Inside User Data

4- Start your instance.

The userdata script you will use depends on the flavor of linux you are running:

For Ubuntu instances:

#cloud-config
bootcmd:
– [ chmod, 700, /home/ubuntu ]
– [ chmod, 700, /home/ubuntu/.ssh ]
– [ chmod, 600, /home/ubuntu/.ssh/* ]
– [ chmod, 600, /etc/ssh/ssh_host_*_key ]
– [ chmod, 600, /home/ubuntu/.ssh/authorized_keys ]
– [ sh, -c, “chown -R ubuntu:ubuntu /home/ubuntu” ]
– [ chmod, 711, /var/empty/sshd ]

For Amazon linux and RHEL instances:

#cloud-config
bootcmd:
– [ chmod, 700, /home/ec2-user ]
– [ chmod, 700, /home/ec2-user/.ssh ]
– [ chmod, 600, /home/ec2-user/.ssh/* ]
– [ chmod, 600, /etc/ssh/ssh_host_*_key ]
– [ chmod, 711, /var/empty/sshd ]
– [ chmod, 600, /home/ec2-user/.ssh/authorized_keys ]
– [ sh, -c, “chown -R ec2-user:ec2-user /home/ec2-user” ]

For Centos instances:

#cloud-config
bootcmd:
– [ chmod, 700, /home/centos ]
– [ chmod, 700, /home/centos/.ssh ]
– [ chmod, 600, /home/centos/.ssh/* ]
– [ chmod, 600, /etc/ssh/ssh_host_*_key ]
– [ chmod, 600, /home/centos/.ssh/authorized_keys ]
– [ sh, -c, “chown -R centos:centos /home/centos” ]
– [ chmod, 711, /var/empty/sshd ]

 

If the issue is firewall related, the following userdata can be used:

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
ufw disable
iptables -L
iptables -F
–//

You can read more on AWS userdata by visiting the link below:

https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html

 

Leave a Reply

Your email address will not be published. Required fields are marked *