Skip to main content

Set Hostname To VM Name

(2019-11-28)

Problem

/t

Solution

For whatever reason, the vmware-tools package (and the open-vm-tools corresponding package) does not expose the name of the vm to the vm. Weird. You can, however, set your own value in the vm properties and then query it yourself later.

So for example, before installing the OS in my vm, I edit the settings for it and go:

  • VM Options
  • Advanced
  • Configuration Parameters
  • Edit Configuration
  • Click Add Parameter
  • as the key, set something like guestinfo.xdroop.hostname and the for the value use the short name of your vm like wiki
  • I believe that the key has to start in the guestinfo space, but after that it is up to you.

Then after OS installation (and patching and open-vm-tools installation), you can do something like this:

#!/bin/bash

if [ -f /etc/.notAVM ] ; then
  exit
fi
if [ -x /usr/bin/vmtoolsd ] ; then
  if [ `cat /etc/hostname` = 'localhost.localdomain' ] ; then
    MyName=`/usr/bin/vmtoolsd --cmd "info-get guestinfo.xdroop.hostname"`
    if [ "$MyName" != "No value found" ] ; then
      hostnamectl set-hostname $MyName
      MyNetDevice=`nmcli connection show --active | grep -v UUID | sed -e 's/^.*ethernet//' | awk '{print $1}'`
      if [ -f /etc/sysconfig/network-scripts/ifcfg-$MyNetDevice ] ; then
        echo "DHCP_HOSTNAME="$MyName"" >> /etc/sysconfig/network-scripts/ifcfg-$MyNetDevice
      fi
      if [ -x /usr/bin/nmcli ] ; then
        nmcli con modify "System $MyNetDevice" ipv4.dhcp-hostname $MyName
      fi
    fi
  else
    touch /etc/.notAVM
  fi
fi

This should work on anything that uses Network Mangler and hostnamectl (which I believe is a systemd gig?) Obviously you'll have to change this if your key (above) is different and if your VM has more than one network connection then you'll have some massaging to do. It's worked for me on CentOS 7/8 and Fedora 30/31 so far.