I want to setup freshly imaged Raspberry Pi's with ansible. For this I have tasks to add users, ssh keys and configs. But when I come to the step where I want to regenerate the default ssh_host_*_keys, I lose connection.
I've tried it on 2 ways. 1st by removing all keys and rebooting the host. In this case the host regenerates the keys at boot. All I would have to do is wait, but this doesnt work.
- name: SSH | Delete ssh host keys
file:
path: '{{ item }}'
state: absent
with_items:
- /etc/ssh/ssh_host_ecdsa_key
- /etc/ssh/ssh_host_rsa_key
- /etc/ssh/ssh_host_ecdsa_key.pub
- /etc/ssh/ssh_host_ed25519_key
- /etc/ssh/ssh_host_rsa_key.pub
- /etc/ssh/ssh_host_ed25519_key.pub
- /etc/ssh/ssh_host_dsa_key
- /etc/ssh/ssh_host_dsa_key.pub
when: ansible_lsb.id == "Raspbian"
notify: wait-for-reboot
This gives me the following error
TASK [../roles/os : SSH | Delete ssh host keys] *******
ok: [raspi4] => (item=/etc/ssh/ssh_host_ecdsa_key)
changed: [raspi4] => (item=/etc/ssh/ssh_host_rsa_key)
changed: [raspi4] => (item=/etc/ssh/ssh_host_ecdsa_key.pub)
fatal: [raspi4]: FAILED! => {"msg": "Failed to connect to the host via ssh: Connection reset by 192.168.100.12 port 22"}
My 2nd try:
- name: SSH | Generate ECDSA Host Key
openssh_keypair:
path: /etc/ssh/ssh_host_ecdsa_key
owner: root
state: present
type: ecdsa
size: 521
regenerate: full_idempotence
force: no
The result:
TASK [../roles/os : SSH | Generate ECDSA Host Key] ******************************
fatal: [raspi4]: FAILED! => {"msg": "Failed to connect to the host via ssh: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\n@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @\r\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\r\nIT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Edit: I already have the "host_key_checking = False" in my ansible.cfg. This is needed for the first time connecting to the host. Otherwise I would have to add it to my known_hosts manually by connecting via ssh.