For those who manage multi-instance environments, providing a descriptive identifier, i.e. a hostname, to each node on a network may be of some utility. Once you've developed a naming convention that makes sense for you, here's a Bash script that will automate the renaming process on Debian-based systems:
#!/usr/bin/env bash
# Change hostname in Debian-based operating systems (OSs).
# Assign existing hostname to $hostn
currenthost=$(cat /etc/hostname)
# Exit if not ROOT.
root_user_check () {
if [ "$EUID" != "0" ]; then
printf "%s\n" "ROOT privileges are required to continue. Exiting.">&2
exit 1
fi
}
# Display existing hostname
show_current_hostname () {
printf "%s\n" "Existing hostname is $currenthost"
}
# Ask for new hostname $newhost
get_new_hostname () {
printf "%s\n" "Enter new hostname: "
read -r newhost
}
# Change hostname in /etc/hosts & /etc/hostname
change_hostname () {
sed --in-place "s/$currenthost/$newhost/g" /etc/hosts
sed --in-place "s/$currenthost/$newhost/g" /etc/hostname
}
# Display new hostname
show_new_hostname () {
printf "%s\n" "Your new hostname is $newhost"
}
# Press a key to reboot
rebooty () {
read -s -n 1 -rp "Press any key to reboot"
reboot
}
# Main
root_user_check
main () {
show_current_hostname
get_new_hostname
change_hostname
show_new_hostname
rebooty
}
main "$@"
.
This script works well for already-provisioned instances, but what if you want to implement your naming convention when spinning up a new node (or several)? Well, you could use a service like CloudInit, which handles the "early initialization of a cloud instance." The same process then, using cloud-init:
#cloud-config
runcmd:
- newhost="<%newhostname%>"
- oldhost=$(cat /etc/hostname)
- echo "Exisitng hostname is $oldhost"
- echo "New hostname will be $newhost"
- sed -i "s/$oldhost/$newhost/g" /etc/hosts
- sed -i "s/$oldhost/$newhost/g" /etc/hostname
power_state:
mode: reboot
.
Please note: the first script should end with .sh
, like: change_host.sh
. Make it executable with: chmod u+x change_host.sh
, and run it with: ./change_host.sh
. The second script needs to end in .yml
, e.g.: change_host.yml
.
If you'd like a TUI
version of this script here you go.
Cheers.