script to change hostname for AWS instance

If you want to set the public DNS as a hostname to the AWS linux  server then you can set it by using following scripts.
The default public DNs for the AWs instance in the format “ec2-51-163-230-103.compute-1.amazonaws.com” and when we create the instance from AWs then it set internal hostname for the server. We can set the correct hostname for AWS instance.
1) Create file vi /home/hostname.sh and add the following code.
————————————
#!/usr/bin/env bash
OLD_HOSTNAME="$( hostname )"
# Auto Detect the Hostname of the server
NEW_HOSTNAME="$( curl http://169.254.169.254/latest/meta-data/public-hostname )"

if [ -z "$NEW_HOSTNAME" ]; then
#echo -n "Please enter new hostname: "
read NEW_HOSTNAME < /dev/tty
fi
if [ -z "$NEW_HOSTNAME" ]; then
echo "Error: no hostname entered. Exiting."
exit 1
fi
echo "Changing hostname from $OLD_HOSTNAME to $NEW_HOSTNAME..."
hostname "$NEW_HOSTNAME"
sed -i "s/HOSTNAME=.*/HOSTNAME=$NEW_HOSTNAME/g" /etc/sysconfig/network
if [ -n "$( grep "$OLD_HOSTNAME" /etc/hosts )" ]; then
sed -i "s/$OLD_HOSTNAME/$NEW_HOSTNAME/g" /etc/hosts
else
echo -e "$( curl wgetip.com )\t$NEW_HOSTNAME" >> /etc/hosts
fi
echo "Done."

————————————
2) chmod 755 /home/hostname.sh
3) sh /home/hostname.sh
4) check hostname is changed or not by using the command
[root@] hostname
[root@] hostname -i
4) Done

Leave a Comment