Skip to content

Instantly share code, notes, and snippets.

@apfelchips
Forked from EntropyWorks/add-ssh-keys.yml
Created March 29, 2022 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apfelchips/91e88eca586879e0784de6889974747b to your computer and use it in GitHub Desktop.
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
---
# 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