Hostname and FQDN configuration

by willemkokke
0 deployments · 0 still active · last rev. 10 months ago

This is a library to configure the hostname and fully qualified domain name on a new server.
Do not deploy directly, but include it with:

source <ssinclude StackScriptID=14149>

You need to copy the UDF declarations into the main calling script as only the main script seems to be parsed for UDF declarations.

@willemkokke

Compatible with: Ubuntu 14.04 LTS
						#!/bin/bash
# @willemkokke
# Copy this into the main calling script
# <UDF name="hostname" label="Hostname" default="" example="eg. my server - leave blank to use reverse dns"  />
# <UDF name="fqdn" label="Fully Qualified Domain Name" default="" example="eg. myserver.example.com - leave blank to use reverse dns"/>

function get_ipv4_address {
    local ip=$(ip -o addr show up primary scope global | awk '/inet / { print $4 }');
    echo ${ip%/*};
}

function get_ipv6_address {
    local ip=$(ip -o addr show up primary scope global | awk '/inet6/ { print $4 }');
    echo ${ip%/*};
}

function get_reverse_dns {
    # get_reverse_dns(ip_address)
    # $1 ip_address

    if [ ! -e /usr/bin/host ]; then
        aptitude -y install dnsutils > /dev/null
    fi
    echo $(host $1 | awk '/pointer/ {print $5}' | sed 's/\.$//')
}

function get_fqdn {
    echo $(get_reverse_dns $(get_ipv4_address))
}

function get_hostname {
    fqdn=$(get_reverse_dns $(get_ipv4_address))
    echo ${fqdn%%\.*}
}

function configure_hostname {
    if [ -z "$HOSTNAME" ]; then
        export HOSTNAME=`get_hostname`
    fi

    echo "$HOSTNAME" > /etc/hostname
    hostname -F /etc/hostname

    sed -i -r "s/(127.0.0.1\s+localhost)/\1 $HOSTNAME/" /etc/hosts

    log "Set hostname to $HOSTNAME"
}

function configure_fqdn {
    if [ -z "$FQDN" ]; then
        export FQDN=`get_fqdn`
    fi

    echo >> /etc/hosts
    echo # Configured by StackScript  >> /etc/hosts
    echo $(get_ipv4_address) "$FQDN"  >> /etc/hosts
    echo $(get_ipv6_address) "$FQDN"  >> /etc/hosts

    log "Set FQDN to $FQDN"
}