--- - name: Collect servers SSH public keys to known_hosts hosts: localhost connection: local vars: targets: "{{ hostvars[groups['all']] }}" tasks: - name: Generate known_hosts ansible.builtin.copy: dest: known_hosts content: | # Use `ansible-playbook ansible-update-ssh-config.yml` to update this file {% for host in groups['all'] | sort %} {{ lookup('ansible.builtin.pipe', 'ssh-keyscan -t ecdsa %s ' % ( hostvars[host].get('ansible_host', host))) }} # {{ host }} {% endfor %} - name: Generate ssh_config ansible.builtin.copy: dest: ssh_config content: | # Use `ansible-playbook ansible-update-ssh-config.yml` to update this file {% for host in groups['all'] | sort %} Host {{ host }} User root Hostname {{ hostvars[host].get('ansible_host', host) }} GlobalKnownHostsFile known_hosts UserKnownHostsFile /dev/null {% endfor %}