You need to use a command called virt-sysprep that lets you reset or unconfigure virtual machines in preparation for cloning them.
Step 1: Install virt-sysprep
Type the following apt-get command/apt command to install virt-sysprep on a Debian or Ubuntu Linux:
$ sudo apt install libguestfs-tools
If you are using a CentOS/RHEL/Oracle/Scientific Linux, type the following yum command:
$ sudo yum install libguestfs-tools
If you are using a Fedora Linux, type the following dnf command to install the same:
$ sudo dnf install libguestfs-tools
Step 2: Download cloud image in .qcow2 format
You can grab cloud images from the following sites (grab the file ending with .qcow2/.qcow2.xz extensions):
- CentOS 7
- CentOS 6.x
- Debian 8.x
- Debian 9.x
- Fedora 26
- Ubuntu 16.04 LTS
- FreeBSD 11.x
- openSUSE/SLES
- AWS Linux
- RHEL 7 (subscription only)
- RHEL 6(subscription only)
- SLES(subscription only)
For demo purpose I am downloading and using CentOS 7 image using wget command:
$ wget https://cloud.centos.org/centos/7/images/CentOS-7-x86_64-GenericCloud.qcow2.xz
Use xz command for decompression:
$ xz -v -d CentOS-7-x86_64-GenericCloud.qcow2.xz
Step 3: Setup/inject an ssh keys
To inject an ssh key so the given “USER” will be able to log in over ssh without supplying a password. The “USER” must exist already in the guest. For CentOS 7 user name is centos:
$ sudo virt-sysprep -a CentOS-7-x86_64-GenericCloud.qcow2 \
--ssh-inject centos:file:/home/vivek/.ssh/id_rsa.pub
Where,
- --ssh-inject centos:file:/home/vivek/.ssh/id_rsa.pub : Read the ssh key from id_rsa.pub.
It is also possible to create a new user named vivek and add ssh-key as follows:
$ sudo virt-sysprep -a CentOS-7-x86_64-GenericCloud.qcow2 \
--run-command 'useradd vivek' \
--ssh-inject vivek:file:/home/vivek/.ssh/id_rsa.pub
Sample outputs:
Step 4: Launch a new VM using CentOS-7-x86_64-GenericCloud-1503.qcow2 image
The syntax is:
$ virt-install --import \
--name centos7-vm1 \
--memory 1024 \
--vcpus 2 \
--cpu host \
--disk path=/var/lib/libvirt/images/centos7.qcow2,size=10,bus=virtio,format=qcow \
--os-type=linux \
--os-variant=centos7.0 \
--graphics spice \
--noautoconsole \
--disk /home/vivek/modifyisoimages/CentOS-7-x86_64-GenericCloud.qcow2
Step 5: Test it with ssh
To find out your vm’s IP address run:
$ virsh net-list
$ virsh net-dhcp-leases default
To login using ssh command:
$ ssh vivek@vms-ip-address-here
Other options to set ssh key for your cloud images
- Use uvt-kvm on a Ubuntu Linux to setup ssh-keys for cloud image.
- Use cloudinit to setup ssh keys
- Also read virt-sysprep man page.