Skip to content

Instantly share code, notes, and snippets.

@r3dact3d
Last active May 19, 2019 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r3dact3d/29abd38c587fdcbbd0e0c76386f2b776 to your computer and use it in GitHub Desktop.
Save r3dact3d/29abd38c587fdcbbd0e0c76386f2b776 to your computer and use it in GitHub Desktop.
Shell script to set friendly hostnames for AWS ec2instances
#!/bin/bash
# brady [r3dact3d]
echo '### Setting Hostname ###'
OLD_HOSTNAME=`hostname`
if [[ $OLD_HOSTNAME != "master" || "node" || "etcd" || "ansible" ]]; then
# Change first field here depending on section of UserData for 'master|ectd|node|ansible'
NEW_HOSTNAME=ansible-`hostname | cut -d- -f4,5`
# Set hostname on ec2 instance
hostnamectl set-hostname "$NEW_HOSTNAME"
# Set hostname in /etc/sysconfig/network config
sed -i "s/HOSTNAME=.*/HOSTNAME=$NEW_HOSTNAME/g" /etc/sysconfig/network
# Set hostname in /etc/hosts config
if [ -n "$( grep "$OLD_HOSTNAME" /etc/hosts )" ]; then
sed -i "s/$OLD_HOSTNAME/$NEW_HOSTNAME/g" /etc/hosts
else
echo -e "$( hostname -I | awk '{ print $1 }' )\t$NEW_HOSTNAME" >> /etc/hosts
fi
echo "### Set Hostname to: $NEW_HOSTNAME ###"
else
echo "### Hostname already includes role ###"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment