Manually Adding SSH Keys to a Cloud Image

Not all of my virtual machines run on OpenStack; I have to run a fair number of virtual machines on my personal workstation via libvirt. However, I like using the cloud versions of RHEL, as they most closely match what I do run in OpenStack. The disconnect is that the Cloud images are designed to accept cloud-init, which pulls the ssh public keys from a metadata web server. Without that, there are no public keys added to the cloud-user account, and the VM is unaccessable. Here is how I add the ssh keys manually.

Start by guest-mounting the image. You can do this from and to anywhere on your system. I ran:

sudo guestmount -a /var/lib/libvirt/images/tower --rw /mnt/vms/tower/  -m /dev/sda1

To add the key:

sudo cp /home/ayoung/.ssh/id_rsa.pub /mnt/vms/tower/home/cloud_init//ssh/authorized_keys
sudo chown 1000:1000 /mnt/vms/tower/home/cloud_init//ssh/authorized_keys

The .ssh directory was pre-created with the right permissions, as was the authorized_keys file. If you overwrite it, it might be necessary to chmod the file as well:

sudo chmod 600 /mnt/vms/tower/home/cloud_init/.ssh/authorized_keys

Unmount and boot the virtual machine. To get the IP address:

$ sudo umount /mnt/vms/tower 
$ sudo virsh start tower
Domain tower started
 
$ sudo virsh list
 Id   Name    State    
-----------------------
 2    tower   running  
$ sudo virsh domifaddr 2
 Name       MAC address          Protocol     Address
-------------------------------------------------------------------------------
 vnet0      52:54:00:01:cd:61    ipv4         192.168.122.252/24
$ sudo virsh domifaddr 2
 Name       MAC address          Protocol     Address
-------------------------------------------------------------------------------
 vnet0      52:54:00:01:cd:61    ipv4         192.168.122.252/24
 
$ ssh cloud-user@192.168.122.252

4 thoughts on “Manually Adding SSH Keys to a Cloud Image

  1. Adam, had you considered using “virt-customize” from the same suite of tools (libguestfs)? I found it easier to do this as a one-liner like this… which installs my public key, creates a password, removes the cloud-init RPM and cleans up the SELinux labels. I’ve seen the SELinux labels of the ~/.ssh/authorized_keys file get weird doing it this way…

    $ sudo virt-customize -a rhel-guest-image.qcow2 \
    –ssh-inject root:file:/home/myUserID/.ssh/id_rsa.pub \
    –root-password password:mySecretPassword \
    –uninstall cloud-init \
    –selinux-relabel

  2. I was going to look into that general approach, but I was thinking in terms of setting up a simple web server. This way looks better. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.