Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a host to the known_host file with ansible?

I want to add the ssh key for my private git server to the known_hosts file with ansible 1.9.3 but it doesn't work.

I have the following entry in my playbook:

- name: add SSH host key
  known_hosts: name='myhost.com'
               key="{{ lookup('file', 'host_key.pub') }}"

I have copied /etc/ssh/ssh_host_rsa_key.pub to host_key.pub and the file looks like:

ssh-rsa AAAAB3NzaC1... [email protected]

If I run my playbook I always get the following error message:

TASK: [add SSH host key]
****************************************************** 
failed: [default] => {"cmd": "/usr/bin/ssh-keygen -F myhost.com -f /tmp/tmpe5KNIW", "failed": true, "rc": 1}

What I am doing wrong?

like image 833
user3389757 Avatar asked Nov 08 '15 11:11

user3389757


2 Answers

Your copy of the remote host public key needs a name, that name needs to match what you specify for your known hosts.

In your case, prepend "myhost.com " to your host_key.pub key file as follows:

myhost.com ssh-rsa AAAAB3NzaC1... [email protected]

Reference: Ansible known_hosts module, specifically the name parameter

like image 93
Mike D Avatar answered Nov 18 '22 04:11

Mike D


You can directly use ssh-keyscan within the ansible task:

- name: Ensure servers are present in known_hosts file
  known_hosts:
    name: "{{ hostvars[item].ansible_host }}"
    state: present
    key: "{{ lookup('pipe', 'ssh-keyscan {{ hostvars[item].ansible_host }}') }}"
    hash_host: true
  with_items: "{{ groups.servers }}"

In the above snipped, we iterate over all hosts in the group "servers" defined in your inventory, use ssh-keyscan on them, read the result with pipe and add it using known_hosts.

If you have only one host that you want to add, it's even simpler:

- name: Ensure server is present in known_hosts file
  known_hosts:
    name: "myhost.com"
    state: present
    key: "{{ lookup('pipe', 'ssh-keyscan myhost.com') }}"
    hash_host: true

Whether you need hash_host or not depends on your system.

like image 9
leosh Avatar answered Nov 18 '22 04:11

leosh