I want to dump the public key that matches the private key I am currently using. The idea is to reference whatever variable is pointing to that private key, create the public key from it, and push that onto a VM with virt-copy-in
.
If you did not configure any specific key for a particular host, you are using the default ssh key of the current user running the playbook. If you have several keys (e.g. rsa, dsa, ecdsa, ed25519.....) the one used will depend on the negotiation with your target ssh host, as you can inspect with ssh -v <your_server>
. Unfortunately, you can only inspect this correctly once the key has been pushed over the target and it is authenticating correctly.
Chances are you only have a default rsa key (created with the default options to ssh-keygen
) which is the one you want to use, so it should be $HOME/.ssh/id_rsa
. In my below example, I take for granted your are able to determine this default key you want to use. You can enhance with more tasks/commands adapted to your specific case if you need an auto-detection for this as well.
If you have configured a specific key to be used (either globally or per host/group in your inventory), then you have set the variable ansible_ssh_private_key_file
to the correct path. This var is then available for the hosts that have to use it.
The following playbook is an example of how you could retrieve the correct key for all servers in your inventory
---
- name: Show key for server
hosts: all
gather_facts: false
vars:
default_private_key_file: "{{ lookup('env', 'HOME') }}/.ssh/id_rsa"
server_private_key_file: "{{ ansible_ssh_private_key_file | default(default_private_key_file) }}"
tasks:
- name: show key for current server
debug:
var: server_private_key_file
- name: do something with that key from localhost
shell: 'echo "I will use {{ server_private_key_file }}"'
delegate_to: localhost
Thank you. It was
ansible_ssh_private_key_file
that I was looking for. (It is unfortunate thatansible
does not define it in the default case. I should look into that.The var is described in behavioral inventory parameters in the documentation
Since
ansible
does not set it in the default case, I assumedansible
never set it, but was only an override you could put in the inventory.