Step 1:
Generate XML Template from Existing Virtual Machine to create new virtual machines
Use the following command to generate an XML template from an existing virtual machine:
virsh dumpxml VM_name > vm_template.xml
Replace with the name of your virtual machine.
Step 2:
Customize XML Template
Replace the MAC addresses of network interfaces and update the guest name in the XML template. Also, mention the path to the new disk that is going to be copied.
Example:
<!-- Update MAC addresses and guest name -->
<mac address='52:54:00:ab:cd:ef'/>
<name>new_guest_name</name>
<!-- Mention the path of the new disk -->
<source file='/path/to/new/disk.qcow2'/>
Step 3:
Copy a Stopped Virtual Machine Disk
Copy the stopped virtual machine disk to another name and verify the path specified in the XML file of the virtual machine.
cp <disk_of_old_VM> <name_of_new_VM_disk>
Step 4:
Prepare Disk Image Using virt-sysprep
Use virt-sysprep to prepare the disk image: (Delete all machine fingerprints)
virt-sysprep --hostname <guestname> -a /data1/guest-images/<guestname>.qcow2 --firstboot /root/scripts/<guestname>.sh
Shell Script /root/scripts/.sh
#!/bin/bash
# Remove existing SSH server and reinstall
apt purge openssh-server -y
apt install openssh-server -y
# Restart SSH server
systemctl restart ssh
systemctl status ssh
# Backup and set custom machine IDs
cp /etc/machine-id /etc/machine-id.bkp
cp /var/lib/dbus/machine-id /var/lib/dbus/machine-id.bkp
echo "<mac-id>" > /etc/machine-id
echo "<mac-id>" > /var/lib/dbus/machine-id
# Restart SSH server after setting machine IDs
systemctl restart ssh
This script generates host keys and sets a custom machine UUID for the guest machine at the first boot start of guest VM.
Step 5: Create Virtual Machine
Define and start the virtual machine using the updated XML file:
virsh define vm_template.xml
virsh start <guestname>
This starts the virtual machine and executes the first boot process including the custom shell script.
Step 6: Connect to VM Console
Check the guest machine name and run virsh console command to connect to the virtual machine console
virsh console {Guest_Name}
**Step 7
:** Verify Configuration
Check the machine UUID and network interface MAC addresses to ensure everything is configured correctly:
# Check machine UUID
cat /etc/machine-id
ip addr show
Ensure that the machine UUID and network interfaces match the configurations set in the XML file and shell script.