-
-
Save apfelchips/91e88eca586879e0784de6889974747b to your computer and use it in GitHub Desktop.
Add all the hosts from your ansible inventory to your .ssh/known_hosts and also use ssh-copy-id to add keys to the hosts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment