Warm tip: This article is reproduced from stackoverflow.com, please click
ansible

Is there a variable pointing to the private key file?

发布于 2020-04-08 23:42:58

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.

Questioner
Jack
Viewed
67
Zeitounator 2020-02-01 18:21

Default case

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.

Specific key

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.

Getting the correct key with default.

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