Set Password or SSH Key for CentOS Cloud Images

By | 2017/05/08

CentOS provides cloud images for various cloud environments such as Openstack, RHV, Azure, or just KVM. It is possible to alter user passwords or SSH keys on these images without using cloud-init! This is nifty for use in Jenkins, Packer, local dev work or other use cases to just write changes to the image so it is ready to go. Check this out!


Official cloud images for CentOS are available here:

http://cloud.centos.org/centos/7/images/


Pre-req: make sure to have the package libguestfs-tools installed (Debian or Fedora)!
sudo dnf install libguestfs-tools

or

sudo apt install libguestfs-tools


The command virt-customize can edit images in a variety of ways. Here are some examples to get you started:


Set a random root password in the image
sudo virt-customize -a CentOS-7-x86_64-GenericCloud-1703.qcow2 --root-password random
[   0.0] Examining the guest ...
[  11.2] Setting a random seed
[  11.2] Setting passwords
virt-customize: Setting random password of root to 132Tfe6cfCCr8Pv8
[  12.2] Finishing off


Set a specific root password of: CoolPasswordBro!
virt-customize -a CentOS-7-x86_64-GenericCloud-1703.qcow2 --root-password password:CoolPasswordBro!
[   0.0] Examining the guest ...
[  12.1] Setting a random seed
[  14.5] Setting passwords
[  15.9] Finishing off


Install or remove packages, add SSH key to default cloud user: centos

Here I’m installing the package epel-release to enable epel, and putting in my ssh key for the existing user on CentOS cloud images, centos:

sudo virt-customize -a CentOS-7-x86_64-GenericCloud-1703.qcow2 --install epel-release --ssh-inject centos:string:"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKCqX6EZIrGHoGaMII4QAqr0QC72t+Kg/c5ZIRNTMb6Q+BwzejQgjhBTXeyPnp0rfE9XI4pTxkZqAUOGSK9Bfqg= smiller@bruckner"
[   0.0] Examining the guest ...
[  12.6] Setting a random seed
[  12.6] Installing packages: epel-release
[  13.2] SSH key inject: centos
[  14.3] Finishing off

I can now start this image under kvm on my workstation and ssh in right away.


Rock on,