How to conigre vCenter templates to create VM clones with custom hostname and ip address.
Having a VM to clone is handy: no need to install packages or dependencies, ssh certs and users are already configured - of course, we can use
cloud-init (which is not really well integrated in vCenter)
or chef/puppet to provision and configure our servers, but in most cases we only need to spin up a vm that is exactly the same as the others.
Cloning a vm seems a good way, but it comes with 2 main issues:
The problem is that the cloned vm is, well, a clone. It is exactly equal to the parent. Some configurations are automatically managed by vCenter (mac address), but it is not enough: the clone hostname will be the same of its parent, and unfortunately, also its ip address! Why? scroll down…
Naming things is hard. Usually, the vm hostname is configured to match the vm name in vCenter. Usually the DHCP offer the possibility to register a DNS entry with the hostname of the vm, very handy.
Setting the hostname equal to the vm name is easy in vCenter: all we need to do is to create a VM Customization Specification. In the vCenter menu, select VM Policies and Profile and create a new item.
In the vCenter menu, select VM Policies and Profile
Under computer name, select Use the virtual machine name
That’s it! Now we can customize the os of the vm setting the hostname equal to the vm name.
This is something related to systemd:
dhclient by default uses the link-layer address (MAC address), while
systemd-networkd uses the contents
Since the VMs were cloned, they have the same machine-id and the DHCP server returns the same IP for both. We want to setup a new machine-id on the first boot of the cloned vm.
To do so, we must:
We can use systemd to run this command online at the first power on: let’s create a new unit file,
systemd-firstboot.service with the following contents
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 [Unit] Description=First Boot Wizard Documentation=man:systemd-firstboot(1) DefaultDependencies=no Conflicts=shutdown.target After=systemd-remount-fs.service Before=systemd-sysusers.service sysinit.target shutdown.target ConditionPathIsReadWrite=/etc ConditionPathExists=!/etc/machine-id [Service] Type=oneshot RemainAfterExit=yes ExecStart=/etc/vmware-config.sh StandardOutput=tty StandardInput=tty StandardError=tty [Install] WantedBy=sysinit.target
This service file will
The executed script,
/etc/vmware-config.sh, is simple - it must only generate a machine-id :)
1 2 3 #!/bin/bash dbus-uuidgen --ensure=/etc/machine-id dbus-uuidgen --ensure
We have to remove 2 files:
1 2 rm -f /etc/machine-id rm /var/lib/dbus/machine-id
The last step is to power off the parent vm, and export to a template.
Done! Now you can create a new vm from the template, and it will have its hostname equal to the vm name and a unique machine-id!