Modify the key pair of a VM
You can replace the key pair assigned to a VM (Virtual Machine).
When you modify a key pair with the console or the API (Application Programming Interface), the metadata of the VM is modified to reflect the new public key, but the replacement is not yet taken into account by the operating system of the VM. To finalize the change and concretely apply the new key pair, you must perform further actions inside the VM.
Permissions
This action requires the following IAM (Identity and Access Management) permissions:
- compute.vm.update
- Console
- API
- Terraform
- From the left-hand side menu, click Compute → VM;
- Select the VM whose key pair you want to modify;
- Click the Modify the key pair action;
- Select the new key pair from the drop-down list;
- Click Confirm.
To modify the public key associated with the metadata of the VM, use the PUT /compute/spaces/{spaceId}/vms/{id} command.
Example request: Modifying a VM
Apply the new key pair with scripts-per-boot
To apply the new key pair using cloud-init start-up scripts (scripts-per-boot), follow these steps:
-
Access the VM
-
Create a file in
/var/lib/cloud/scripts/per-boot/Name this file, for example,
update-keypair.sh, and add the following content:#!/bin/bashcurl http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key/ > /home/numspot/.ssh/authorized_keys -
Make the file executable
sudo chmod +x /var/lib/cloud/scripts/per-boot/update-keypair.sh -
Restart the VM
The new key pair will be applied after the VM restarts. This script downloads the public key from the metadata of the VM and places it in the
authorized_keysfile of the specified user. Make sure that the path/home/numspot/.ssh/authorized_keyscorresponds to that of the user for whom you want to add the key.
Apply the new key pair with cloud_init_modules
To apply the new key pair using the cloud_init_modules modules of cloud-init, follow these steps:
-
Access the VM
-
Modify the
/etc/cloud/cloud.cfgfileReplace the
- sshentry undercloud_init_modules:with:- [ssh, always]This tells cloud-init to always reconfigure SSH (Secure Shell) at each start-up of the VM.
-
Restart the VM
This method regenerates the SSH signature of the VM, which changes its fingerprint. You will therefore receive a warning when you reconnect to the VM, because the fingerprint of the SSH key will have changed. Make sure that you are ready to accept this change on your next connection.
The Terraform documentation is available on the Numspot registry ↗.