-
-
Save EntropyWorks/a768b3bc4444146d56be81af05d73fed to your computer and use it in GitHub Desktop.
--- | |
# Original idea found at http://stackoverflow.com/a/39083724 | |
# | |
# ansible -i inventory.ini add-ssh-keys.yml | |
# | |
- name: Store known hosts of 'all' the hosts in the inventory file | |
hosts: localhost | |
connection: local | |
vars: | |
ssh_known_hosts_command: "ssh-keyscan -T 10" | |
ssh_known_hosts_file: "{{ lookup('env','HOME') + '/.ssh/known_hosts' }}" | |
ssh_known_hosts: "{{ groups['all'] }}" | |
tasks: | |
- name: For each host, scan for its ssh public key | |
shell: "ssh-keyscan {{ item }},`dig +short {{ item }}`" | |
with_items: "{{ ssh_known_hosts }}" | |
register: ssh_known_host_results | |
ignore_errors: yes | |
tags: | |
- ssh | |
- name: Remove the public key in the '{{ ssh_known_hosts_file }}' | |
known_hosts: | |
name: "{{ item.item }}" | |
state: "absent" | |
path: "{{ ssh_known_hosts_file }}" | |
with_items: "{{ ssh_known_host_results.results }}" | |
tags: | |
- ssh | |
- name: Add/update the public key in the '{{ ssh_known_hosts_file }}' | |
known_hosts: | |
name: "{{ item.item }}" | |
key: "{{ item.stdout }}" | |
state: "present" | |
path: "{{ ssh_known_hosts_file }}" | |
with_items: "{{ ssh_known_host_results.results }}" | |
tags: | |
- ssh | |
- name: For each host, ssh-copy-id my ssh public keys to the host | |
shell: "sshpass -p {{ ansible_ssh_pass }} ssh-copy-id {{ item }}" | |
with_items: "{{ ssh_known_hosts }}" | |
when: not (( ansible_ssh_pass is undefined ) or ( ansible_ssh_pass is none ) or ( ansible_ssh_pass | trim == '')) | |
tags: | |
- sshcopy |
Nice play! I have a question. I'm confused by your use of dig. When I run this, I get errors "dig: not found". Researching this, it looks to me like dig is an ansible lookup plugin: https://docs.ansible.com/ansible/2.5/plugins/lookup/dig.html. Shouldn't your dig line look more like:
"ssh-keyscan {{ item }},lookup('dig', '{{ item }}')"
?? How does your dig line even work?
@timblaktu dig is a part of bind-utils package (on RedHat systems) or dnsutils (on Debian systems).
Line 33 you have an indent error, but thanks for the code! This was handy for a quick way to get this done!
Thanks!
In the last task where to put the: ansible_ssh_pass?
I guess you do not use the ssh_known_hosts_command var later at all?
Thank you for putting this altogether, adapted it, works fine.
You can also do
export ANSIBLE_HOST_KEY_CHECKING=False && ansible-playbook -e 'record_host_keys=True' ping.yml
Line 33 you have an indent error, but thanks for the code! This was handy for a quick way to get this done!