How to add ssh key to qcow2 Linux cloud images using virt-sysprep
I have installed and setup KVM server on an Ubuntu Linux. I downloaded various .qcow2 cloud images. How do I setup public ssh keys for downloaded CentOS/FreeBSD/Ubuntu cloud images using virt-sysprep?
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):
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 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.