2022-12-24T07:48:54

Changing the ssh keypair for an active Openstack instance

In this article we are discussing 2 useful options of how to change the SSH Keypair of an active Openstack instance.

As an Openstack user, you might find yourself stumbled over changing the openstack keypair for an instance that you created.
Unfortunately, there is no easy or plug-and-play option to do that in openstack, since nova is not exposing any API that could inject a new ssh key in the instance while it’s live.
In fact, this is a more complicated topic and depends from one hypervisor to antother. For example, with QEMU/KVM, one would have to install qemu-gestagent to be able to execute remote operations on the instance while it’s alive.

While Openstack doesn’t provide a straightforward way to change the keypair of an existing instance, we found 2 workarounds for you.

Option 1: Update the authorized_keys manually

This is the simplest way, however this will not reflect the change on the Nova instance object itself. You have to ssh into your instance and run:

echo 'my_ssh_key' >> ~/.ssh/authorized_keys

Option 2: Snapshot and rebuild

There is an option to specify the –key-name when you rebuild an instance.
However, rebuilding will erase the current data and install a new image instead.
While this option is a more consistent way of changing the ssh key of an instance, it requires a shutdown.

First, shutdown your server to safely create a snapshot from it and then rebuild it.

openstack server stop $MY_SERVER

Then create a new snapshot from your server.

SNAP_ID=$(openstack server image create $MY_SERVER -c id -f value)

Finally, rebuild the server with the new key. Note: this operation requires

openstack server rebuild --image $SNAP_ID --key-name $MY_NEW_KEYPAIR $MY_SERVER

Optionally, remove the snapshot if you don’t need it anymore.

openstack image delete $SNAP_ID