Skip to content

Instantly share code, notes, and snippets.

@brianoflan
Last active December 16, 2016 17:44
Show Gist options
  • Save brianoflan/3b499c709f063378fa9cd0ab1c7addae to your computer and use it in GitHub Desktop.
Save brianoflan/3b499c709f063378fa9cd0ab1c7addae to your computer and use it in GitHub Desktop.
Set hostname on CentOS on AWS EC2 instance (hostnamectl set-hostname, /etc/hosts, /etc/sysconfig/network, /etc/cloud/cloud.cfg)
#!/bin/bash
# # # USAGE: hostname -f ; /bin/bash setHostname.sh new.hostname.to.be.set.in.some.domain ; hostname -f
# # # Per the official but mildly inaccurate AWS EC2 hostname docs
# # # (https://aws.amazon.com/premiumsupport/knowledge-center/linux-static-hostname-rhel7-centos7/)
setHostname() {
local fqdn=$1 ;
# # Probably the least necessary of all. (Try it: Comment it out and everything still works.)
updateSysconfigNetwork $fqdn ;
updateHostsTable $fqdn ;
sudo hostnamectl set-hostname $fqdn ;
# /etc/hostname handled by hostnamectl set-hostname
if [[ -e /etc/cloud/cloud.cfg ]] ; then
local x=`egrep 'preserve_hostname: *true' /etc/cloud/cloud.cfg` ;
[[ $x ]] || echo -e "\npreserve_hostname: true" | sudo tee -a /etc/cloud/cloud.cfg ;
fi ;
}
updateSysconfigNetwork() {
local fqdn=$1 ;
local f=/etc/sysconfig/network ;
if [[ -e $f ]] ; then
local tmpf=`mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX"` ;
cat $f > $tmpf ;
cat $tmpf | egrep -v '^\s*(NETWORKIN(G|G_IPV6)|HOSTNAME)[=:]' \
| sudo tee $f \
;
echo 'NETWORKING=yes' | sudo tee -a $f ;
echo 'NETWORKING_IPV6=no' | sudo tee -a $f ;
echo 'HOSTNAME=$fqdn' | sudo tee -a $f ;
fi ;
}
updateHostsTable() {
local fqdn=$1 ;
local f=/etc/hosts ;
if [[ -e $f ]] ; then
local tmpf=`mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX"` ;
cat $f > $tmpf ;
echo -e \
"127.0.0.1 $fqdn localhost localhost.localdomain localhost4 localhost4.localdomain4" \
| sudo tee $f \
;
cat $tmpf | egrep -v '^\s*127.0.0.1\s' \
| sudo tee -a $f \
;
fi ;
}
setHostname "$@" > /dev/null
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment