0

I am trying to create a template in cloudstack but /etc/hostname and /etc/hosts is not set when creating a new VM instance.

I am using this script:

#!/bin/sh
# dhclient change hostname script for Ubuntu
oldhostname=$(hostname -s)
if [ $oldhostname = 'localhost' ]
then
    sleep 30 # Wait for configuration to be written to disk
    hostname=$(cat /var/lib/dhcp/dhclient.eth0.leases  |  awk ' /host-name/ { host = $3 }  END { printf host } ' | sed     's/[";]//g' )
    fqdn="$hostname.$(cat /var/lib/dhcp/dhclient.eth0.leases  |  awk ' /domain-name/ { domain = $3 }  END { printf     domain } ' | sed 's/[";]//g')"
    ip=$(cat /var/lib/dhcp/dhclient.eth0.leases  |  awk ' /fixed-address/ { lease = $2 }  END { printf lease } ' | sed     's/[";]//g')
    echo "cloudstack-hostname: Hostname _localhost_ detected. Changing hostname and adding hosts."
    printf " Hostname: $hostname\n FQDN: $fqdn\n IP: $ip"
    echo "Hostname: $hostname\n FQDN: $fqdn\n IP: $ip" >> "/var/log/hostchange"
    # Update /etc/hosts
    echo "$ip $fqdn $hostname" > /etc/hosts.dhcp.tmp
    #awk -v i="$ip" -v f="$fqdn" -v h="$hostname" "/^127/{x=1} !/^127/ && x { x=0; print i,f,h; } { print $0; }" /etc/hosts > /etc/hosts.dhcp.tmp
    mv /etc/hosts /etc/hosts.dhcp.bak
    mv /etc/hosts.dhcp.tmp /etc/hosts
    # Rename Host
    echo $hostname > /etc/hostname
    hostname -b -F /etc/hostname
    echo $hostname > /proc/sys/kernel/hostname
    # Recreate SSH2
    export DEBIAN_FRONTEND=noninteractive
    dpkg-reconfigure openssh-server
fi
### End of Script ###

When I set the hostname to localhost and do a reboot everything works.

When I create a new instance it doesn't work: the hostname of the previous VM is used (the VM I used to create the template)

When I run rm -f /var/lib/dhcp/dhclient.* before I create the template the hostname will be blank. But in the lease file is the right data.

womble
  • 95,029
  • 29
  • 173
  • 228

2 Answers2

1

When I set the hostname to localhost and do a reboot everything works.

When I create a new instance it doesn't work: the hostname of the previous VM is used (the VM I used to create the template)

Doesn't this suggest that the hostname isn't 'localhost' so

if [ $oldhostname = 'localhost' ]

isn't going to work and therefore the rest of the script is skipped.

Wouldn't you be better testing for the name of the template? Perhaps have the script delete itself after it has run once successfully - then you don't need to check for the hostname.

user9517
  • 114,104
  • 20
  • 206
  • 289
0

Cloud-init is a better option for your use case. It has Cloudstack provider support: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/4.8/virtual_machines/user-data.html