Skip to content

Instantly share code, notes, and snippets.

@fessmage
Created April 22, 2021 12:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fessmage/e09354ec4df9cec012dd2246005c0d27 to your computer and use it in GitHub Desktop.
Save fessmage/e09354ec4df9cec012dd2246005c0d27 to your computer and use it in GitHub Desktop.
Add all hosts from ansible inventory to ssh known_hosts file of current user
- name: Gather facts from 'all' hosts in inventory
hosts: all
vars:
ansible_host_key_checking: false
ansible_ssh_extra_args: '-o UserKnownHostsFile=/dev/null'
tasks:
- setup:
gather_subset: network
- name: Add public keys to known_hosts file
hosts: localhost
connection: local
vars:
ssh_known_hosts_file: "{{ lookup('env','HOME') + '/.ssh/known_hosts' }}"
ssh_known_hosts: "{{ groups['all'] }}"
tasks:
- known_hosts:
path: "{{ ssh_known_hosts_file }}"
name: "{{ item }}"
key: "{{ lookup('pipe','ssh-keyscan -T 10 ' + item + ',' + lookup('dig',item)) }}"
state: present
loop: "{{ ssh_known_hosts | map('extract', hostvars, ['ansible_fqdn']) | list }}"
become: no
@SSmale
Copy link

SSmale commented Jan 16, 2024

This is what I needed to get it to work

---
- name: Gather facts from 'all' hosts in inventory
  hosts: all
  vars:
    ansible_host_key_checking: false
    ansible_ssh_extra_args: '-o UserKnownHostsFile=/dev/null'
  tasks:
    - name: Get network info
      ansible.builtin.setup:
        gather_subset: network

- name: Add public keys to known_hosts file
  hosts: localhost
  connection: local
  vars:
    ssh_known_hosts_file: "{{ lookup('env','HOME') + '/.ssh/known_hosts' }}"
    ssh_known_hosts: "{{ groups['all'] }}"
  tasks:
    - name: Add to known_hosts
      ansible.builtin.known_hosts:
        path: '{{ ssh_known_hosts_file }}'
        name: '{{ item }}'
        key: "{{ lookup('pipe', 'ssh-keyscan -T 10 ' + item + ',' + lookup('dig', item)) }}"
        state: present
      with_items: '{{ ssh_known_hosts }}'
      become: false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment