From: David Galloway Date: Fri, 10 Nov 2017 17:20:44 +0000 (-0500) Subject: cobbler: Set hostname using DHCP every boot on testnodes X-Git-Url: http://git.apps.os.sepia.ceph.com/?a=commitdiff_plain;h=e665f85b0e23a8d3f326d6a134ee3136ec022c16;p=ceph-cm-ansible.git cobbler: Set hostname using DHCP every boot on testnodes This is for use with FOG. When we create an OS image, the image inherits the testnode's hostname that was used to create the image. This rc.local snippet will make sure the testnode's hostname is set to whatever the IP's PTR record is on every boot. `rclocal_nameserver` should be set in the inventory groupvars. Signed-off-by: David Galloway --- diff --git a/roles/cobbler/templates/snippets/cephlab_rc_local b/roles/cobbler/templates/snippets/cephlab_rc_local index 853e1dc..9bb5aab 100644 --- a/roles/cobbler/templates/snippets/cephlab_rc_local +++ b/roles/cobbler/templates/snippets/cephlab_rc_local @@ -9,13 +9,56 @@ #set script = '/etc/rc.local' #end if -cat > $script << EOF +cat > $script <<\EOF #!/bin/bash # First, redirect stderr and stdout to a logfile exec 2> /tmp/rc.local.log exec 1>&2 set -ex +{% if rclocal_nameserver is defined %} +#raw + +# Don't error out if the `ip` command returns rc 1 +set +e + +attempts=0 +myips="" +until [ "$myips" != "" ] || [ $attempts -ge 10 ]; do + myips=$(ip -4 addr | grep -oP '(?<=inet\s)\d+(\.\d+){3}' | grep -v '127.0.0.1\|127.0.1.1') + attempts=$[$attempts+1] + sleep 1 +done + +set -e + +if [ -n "$myips" ]; then + for ip in $myips; do + if timeout 1s ping -I $ip -nq -c1 {{ rclocal_nameserver }} 2>&1 >/dev/null; then + newhostname=$(dig +short -x $ip @{{ rclocal_nameserver }} | sed 's/\.com.*/\.com/g') + if [ -n "$newhostname" ]; then + hostname $newhostname + newdomain=$(hostname -d) + shorthostname=$(hostname -s) + echo $newhostname > /etc/hostname + if grep -q $newdomain /etc/hosts; then + # Replace + sed -i "s/.*$newdomain.*/$ip $newhostname $shorthostname/g" /etc/hosts + else + # Or add to top of file + sed -i '1i'$ip' '$newhostname' '$shorthostname'\' /etc/hosts + fi + fi + # Quit after first IP that can ping our nameserver + # in the extremely unlikely event the testnode has two IPs + break + fi + done +fi + +#end raw +{% endif %} + # Only run once. if [ -e $lockfile ]; then exit 0