Instantly share code, notes, and snippets.

What would you like to do?
Adding github to known_hosts with ansible
- name: ensure is a known host
dest: /root/.ssh/known_hosts
create: yes
state: present
line: "{{ lookup('pipe', 'ssh-keyscan -t rsa') }}"
regexp: "^github\\.com"

This comment has been minimized.

holms commented Sep 7, 2015

You're a genius, i couldn't find how this module works at all.. finally!!!


This comment has been minimized.

patricknelson commented Sep 18, 2015

I'm actually adapting this to puppet; I wasn't aware of this utility ssh-keyscan and that I could use it to lookup the key for use in known_hosts. Thank you and thanks google 👍

Example usage in puppet:

  # Ensure is in the "known_hosts" file...
  # NOTE: This is needed for npm (when deploying code).
  exec { "${username}_known_hosts":
    command => "/usr/bin/ssh-keyscan -t rsa >> /home/${username}/.ssh/known_hosts",
    unless  => "/bin/grep /home/${username}/.ssh/known_hosts",
    require => File["/home/${username}/.ssh"]

Note: This of course also assumes you've got a declaration for setting up the .ssh directory as well (see last require statement).


This comment has been minimized.

klemenkobetic commented Oct 16, 2015

i used this :

  • name: tell the host about our servers it might want to ssh to
    known_hosts: path='/home/deploy/.ssh/known_hosts' name='' key="{{ lookup('pipe', 'ssh-keyscan -t rsa') }}"
    sudo_user: deploy

This comment has been minimized.

chrisbeyer commented Dec 2, 2015

Nice one.
Thanks :)


This comment has been minimized.

IkeLutra commented Jan 28, 2016

It is worth noting that this leaves you vunerable to Man In The Middle attacks. It might be better to run ssh-keyscan once and store the key and use that rather look up every time. Though then it will not auto-update.


This comment has been minimized.

pumazi commented Mar 21, 2016

Thank you. 😄


This comment has been minimized.

whatthefrog commented Jun 16, 2016

Nice task, but 2 points to be noted

  • this "blindly" accept the scanned key as the legit one ... no-where its fingerprint is compared to the expected one
  • if using /etc/ssh/ssh_config option HashKnownHosts yes, this ansible task leaves the host ( unhashed in dest: /root/.ssh/known_hosts

This comment has been minimized.

pajtai commented Sep 8, 2017

Nice, I couldn't get the known_hosts module to work, but this did!

If you want hashing you can do: ssh-keyscan -H -t rsa

To check if you have hashing on you could register: cat /etc/ssh/ssh_config | grep -q 'HashKnownHosts\s\s*yes', then do a when succeeded for the hashing.

Checking if the lines been added gets trickier if you hash it though...

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