Ansible: Copy Agent Keys to Remote Servers
Background: you use SSH and ssh-agent and you can get a list of keys you presently have “ready to fire” via:
djh@djh-MBP:~/devops$ ssh-add -l
4096 SHA256:JtmLhsoPoSfBsFnrIsZc6XNScJ3ofghvpYmhYGRWwsU .ssh/id_ssh (RSA)
Aaaand, you want to set up passwordless SSH for the remote hosts in your Ansible. There are lots of examples that involve file lookups for blah blah blah dot pub but why not just get a list from the agent?
A playbook:
- hosts: all gather_facts: no tasks: - name: Get my SSH public keys local_action: shell ssh-add -L register: ssh_keys - name: List my SSH public keys debug: msg="{{ ssh_keys.stdout }}" - name: Install my SSH public keys on Remote Servers authorized_key: user={{lookup('env', 'USER')}} key="{{item}}" with_items: "{{ ssh_keys.stdout }}"
This is roughly based on a Stack Overflow answer.
The two tricky bits are:
1) Running a local_action
to get a list of SSH keys.
2) Doing with_items
to iterate if there are multiple keys.
A bonus tricky bit:
3) You may need to install sshpass if you do not already have key access to the remote servers. Last I knew, the brew command on Mac OS will balk at you for trying to install this.