I\'m running Ansible playbook and it works fine on one machine.
On a new machine when I try for the first time, I get the following error.
17:04:34
To update local known_hosts
file, I ended up using a combination of ssh-keyscan
(with dig
to resolve a hostname to IP address) and ansible module known_hosts
as follows: (filename ssh-known_hosts.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
- name: Add/update the public key in the '{{ ssh_known_hosts_file }}'
known_hosts:
name: "{{ item.item }}"
key: "{{ item.stdout }}"
path: "{{ ssh_known_hosts_file }}"
with_items: "{{ ssh_known_host_results.results }}"
To execute such yml, do
ANSIBLE_HOST_KEY_CHECKING=false ansible-playbook path/to/the/yml/above/ssh-known_hosts.yml
As a result, for each host in the inventory, all supported algorithms will be added/updated in the known_hosts
file under hostname,ipaddress pair record; such as
atlanta1.my.com,10.0.5.2 ecdsa-sha2-nistp256 AAAAEjZHN ... NobYTIGgtbdv3K+w=
atlanta1.my.com,10.0.5.2 ssh-rsa AAAAB3NaC1y ... JTyWisGpFeRB+VTKQ7
atlanta1.my.com,10.0.5.2 ssh-ed25519 AAAAC3NaCZD ... UteryYr
denver8.my.com,10.2.13.3 ssh-rsa AAAAB3NFC2 ... 3tGDQDSfJD
...
(Provided the inventory file looks like:
[master]
atlanta1.my.com
atlanta2.my.com
[slave]
denver1.my.com
denver8.my.com
)
As opposed to the Xiong's answer, this would properly handle the content of the known_hosts
file.
This play is especially helpful if using virtualized environment where the target hosts get re-imaged (thus the ssh pub keys get changed).