How to reset a KVM clone virtual Machines with virt-sysprep on Linux nixCraft

I know how to clone a KVM VM. Once cloned I would like to reset cloned VM. How do I reset, unconfigure or customize a virtual machine so clones can be made? How can I reset a KVM clone virtual Machines with virt-sysprep command on a Linux server based hypervisor?

Introduction: You need to use the virt-sysprep command to reset a virtual machine. You can remove ssh-keys, hostname, network mac configuration, user accounts and more. You can enable or disable specific features. This page shows how to use the virt-clone and virt-sysprep commands together to clone a KVM VM on a Linux based server.

Syntax to reset a KVM clone virtual Machines with virt-sysprep command

The syntax is:
virt-sysprep -d kvmDomain
virt-sysprep -d kvmDomainHere options

A list of sysprep operations to perform on a KVM VM to reset it

abrt-dataRemove the crash data generated by ABRT
backup-filesRemove editor backup files from the guest
bash-historyRemove the bash history in the guest
blkid-tabRemove blkid tab in the guest
ca-certificatesRemove CA certificates in the guest
crash-dataRemove the crash data generated by kexec-tools
cron-spoolRemove user at-jobs and cron-jobs
customizeCustomize the guest
dhcp-client-stateRemove DHCP client leases
dhcp-server-stateRemove DHCP server leases
dovecot-dataRemove Dovecot (mail server) data
firewall-rulesRemove the firewall rules
flag-reconfigurationFlag the system for reconfiguration
fs-uuidsChange filesystem UUIDs
kerberos-dataRemove Kerberos data in the guest
logfilesRemove many log files from the guest
lvm-uuidsChange LVM2 PV and VG UUIDs
machine-idRemove the local machine ID
mail-spoolRemove email from the local mail spool directory
net-hostnameRemove HOSTNAME and DHCP_HOSTNAME in network interface configuration
net-hwaddrRemove HWADDR (hard-coded MAC address) configuration
pacct-logRemove the process accounting log files
package-manager-cacheRemove package manager cache
pam-dataRemove the PAM data in the guest
passwd-backupsRemove /etc/passwd- and similar backup files
puppet-data-logRemove the data and log files of puppet
rh-subscription-managerRemove the RH subscription manager files
rhn-systemidRemove the RHN system ID
rpm-dbRemove host-specific RPM database files
samba-db-logRemove the database and log files of Samba
scriptRun arbitrary scripts against the guest
smolt-uuidRemove the Smolt hardware UUID
ssh-hostkeysRemove the SSH host keys in the guest
ssh-userdirRemove “.ssh” directories in the guest
sssd-db-logRemove the database and log files of sssd
tmp-filesRemove temporary files
udev-persistent-netRemove udev persistent net rules
user-accountRemove the user accounts in the guest
utmpRemove the utmp file
yum-uuidRemove the yum UUID

You can choose which sysprep operations to perform. Give a comma-separated list of operations, for example:
virt-sysprep -d {vmDomainHere} --enable ssh-hostkeys,udev-persistent-net

Step 1. Clone your VM and spawn new instances in KVM

First use the virsh list command to get a list of all running VM domains/guest:
virsh list
Sample outputs:

 1 openbsd62 running 2 freebsd11-nixcraft running 3 fedora28-nixcraft running 4 rhel7 running 5 centos7-nixcraft running 6 sles12sp3 running 16 bionic running

First suspend the KVM, run:
virsh suspend bionic
Domain bionic suspended

To clone vm named ‘bionic’ as testvm using the virt-clone command, run:
virt-clone --original bionic --name testvm --auto-clone
virt-clone linux command demo
You may resume bionic VM, run:
virsh resume bionic
Domain bionic resumed

Step 2. Use virt-sysprep command

Simply run as follows to reset everything:
virt-sysprep -d testvm
reset a KVM clone virtual Machines with virt-sysprep command
You can setup the hostname of the guest and force to keep the user account named vivek in the guest:
virt-sysprep -d testvm --hostname testvm --enable user-account --keep-user-accounts vivek
You can create a new Linux user account called tom and force password change on first login as follows:
virt-sysprep -d testvm --firstboot-command 'useradd -s /bin/bash -m -G sudo tom; chage -d 0 tom'
You can set root user account password too:
virt-sysprep -d testvm --root-password password:MySuperSecureRootPasswordHere
Or combine all of them:
virt-sysprep -d testvm --hostname testvm --keep-user-accounts vivek --root-password password:MySuperSecureRootPasswordHere

How to skip certain guest VM reset features

You can enable specific operations with --enable. For example, enable all options except resetting fs-uuids ( Change filesystem UUIDs), lvm-uuids ( Change LVM2 PV and VG UUIDs), and ssh-userdir ( Remove “.ssh” directories in the guest):

w=$(virt-sysprep --list-operations | egrep -v 'fs-uuids|lvm-uuids|ssh-userdir' | awk '{ printf "%s,", $1}' | sed 's/,$//')
echo "$w"

Now run it as follows:
virt-sysprep -d testvm --hostname testvm --keep-user-accounts vivek --enable $w
Another example:
virt-sysprep -d testvm --hostname testvm --keep-user-accounts vivek --enable $w --firstboot-command 'dpkg-reconfigure openssh-server'

virt-sysprep command list options

 -a, --add <file> Add disk image file --append-line <FILE:LINE> Append line(s) to the file -c, --connect <uri> Set libvirt URI --chmod <PERMISSIONS:FILE> Change the permissions of a file --color, --colors, --colour, --colours Use ANSI colour sequences even if not tty --commands-from-file <FILENAME> Read customize commands from file --copy <SOURCE:DEST> Copy files in disk image --copy-in <LOCALPATH:REMOTEDIR> Copy local files or directories into image -d, --domain <domain> Set libvirt guest name --delete <PATH> Delete a file or directory -n, --dryrun, --dry-run Perform a dry run --echo-keys Don't turn off echo for passphrases --edit <FILE:EXPR> Edit file using Perl expression --enable <operations> Enable specific operations --firstboot <SCRIPT> Run script at first guest boot --firstboot-command <'CMD+ARGS'> Run command at first guest boot --firstboot-install <PKG,PKG..> Add package(s) to install at first boot --format <format> Set format (default: auto) --help Display brief help --hostname <HOSTNAME> Set the hostname --install <PKG,PKG..> Add package(s) to install --keep-user-accounts <users> Users to keep --keys-from-stdin Read passphrases from stdin --link <TARGET:LINK[:LINK..]> Create symbolic links --list-operations List supported operations --mkdir <DIR> Create a directory --mount-options <opts> Set mount options (eg /:noatime;/var:rw,noatime) --move <SOURCE:DEST> Move files in disk image --network Enable appliance network --no-logfile Scrub build log file --no-network Disable appliance network (default) --no-selinux-relabel Compatibility option, does nothing --operation, --operations <operations> Enable/disable specific operations --password <USER:SELECTOR> Set user password --password-crypto <md5|sha256|sha512> Set password crypto -q, --quiet Don't print progress messages --remove-user-accounts <users> Users to remove --root-password <SELECTOR> Set root password --run <SCRIPT> Run script in disk image --run-command <'CMD+ARGS'> Run command in disk image --script <script> Script or program to run on guest --scriptdir <dir> Mount point on host --scrub <FILE> Scrub a file --selinux-relabel Relabel files with correct SELinux labels --sm-attach <SELECTOR> Attach to a subscription-manager pool --sm-credentials <SELECTOR> Credentials for subscription-manager --sm-register Register using subscription-manager --sm-remove Remove all the subscriptions --sm-unregister Unregister using subscription-manager --ssh-inject <USER[:SELECTOR]> Inject a public key into the guest --timezone <TIMEZONE> Set the default timezone --touch <FILE> Run touch on a file --truncate <FILE> Truncate a file to zero size --truncate-recursive <PATH> Recursively truncate all files in directory --uninstall <PKG,PKG..> Uninstall package(s) --update Update packages --upload <FILE:DEST> Upload local file to destination -V, --version Display version and exit -v, --verbose Enable libguestfs debugging messages --write <FILE:CONTENT> Write file -x Enable tracing of libguestfs calls

Step 3. Start the VM

virsh start testvm
Domain testvm started

Verify it with the following virsh command:
virsh list

Step 4. Login to the VM

Find/get the DHCP IP address of testvm using the following command along with the grep command:
virsh net-dhcp-leases default
virsh net-dhcp-leases default | grep testvm
virsh net-dhcp-leases default | grep testvm | awk '{ print $5}'

Sample outputs:

Use the ssh command:
ssh vivek@


You just learned how to clone a KVM VM and reset the data. I strongly suggest that you read virt-sysprep help page here.

Get 15% off on Linux Foundation certified SysAdmin, Progamming, Kubernetes/Containers and Open Stack certification & course. Use “SPLASH15” coupon code. Offer expires on August 27, 2018

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Facebook Comments

More Stuff

CentOS Pulse Newsletter, September 2018 (#1804) Dear CentOS enthusiast, Here's what's been happening in the past month at CentOS Releases and Updates The following releases and updates happened in A...
Languages and Hybrid Design Here’s a new one for the debate regarding semantic tableless CSS-based design versus old-fashioned tables-for-everything HTML. Let’s say you design a ...
Continuous integration tests for the CentOS Vagrant images Continuous integration tests for the CentOS Vagrant images Thursday , 1, September 2016 Lauren?iu P?ncescu cicoSince yesterday, we have production...
Ubuntu 18.04 Setup SSH Public Key Authentication nixCraft I am a new Ubuntu 18.04 LTS user and I would like to setup ssh public key authentication. How do I set up ssh keys based authentication on Ubuntu Lin...
Spread the love

Posted by News Monkey