- name: Authorize the "{{ ssh_relayed_hostname | default(ssh_hostname) }}" host key tags: - ssh block: - name: Retrieve the host's key ansible.builtin.command: cat /etc/ssh/ssh_host_ed25519_key.pub register: host_key delegate_to: "{{ ssh_relayed_hostname | default(ssh_hostname) }}" changed_when: false - name: Authorize the host key on a linux host when: ansible_facts['os_family'] != 'Windows' vars: known_hosts_path: "{{ system_known_hosts_path if system_known_hosts_file.stat.exists and system_known_hosts_file.stat.writeable else user_known_hosts_path }}" block: - name: Detect if global known hosts file is writable ansible.builtin.stat: path: "{{ system_known_hosts_path }}" register: system_known_hosts_file - name: Authorize the {{ ssh_hostname }} host key vars: host_line: "{% if ssh_port == 22 %}{{ ssh_hostname }}{% else %}[{{ ssh_hostname }}]:{{ ssh_port }}{% endif %}" ansible.builtin.known_hosts: path: "{{ known_hosts_path }}" name: "{{ host_line }}" key: "{{ host_line }} {{ host_key.stdout }}" - name: "Authorize the {{ ssh_hostname }} IP addresses" when: include_host_ip_addresses block: - name: Authorize the {{ ssh_hostname }} IPv4 Address vars: ipv4_address: "{{ lookup('community.general.dig', ssh_hostname) }}" host_line: "{% if ssh_port == 22 %}{{ ipv4_address }}{% else %}[{{ ipv4_address }}]:{{ ssh_port }}{% endif %}" ansible.builtin.known_hosts: path: "{{ known_hosts_path }}" name: "{{ host_line}}" key: "{{ host_line }} {{ host_key.stdout }}" - name: Authorize the {{ ssh_hostname }} IPv6 Address vars: ipv6_address: "{{ lookup('community.general.dig', ssh_hostname, 'qtype=AAAA') }}" host_line: "{% if ssh_port == 22 %}{{ ipv6_address }}{% else %}[{{ ipv6_address }}]:{{ ssh_port }}{% endif %}" ansible.builtin.known_hosts: path: "{{ known_hosts_path }}" name: "{{ host_line}}" key: "{{ host_line }} {{ host_key.stdout }}" - name: Authorize the host key on a windows host when: ansible_facts['os_family'] == 'Windows' vars: ipv4_address: "{{ lookup('community.general.dig', ssh_hostname) }}" ipv6_address: "{{ lookup('community.general.dig', ssh_hostname, 'qtype=AAAA') }}" host_line: >- {% if ssh_port == 22 %}{{ ssh_hostname }}{% else %}[{{ ssh_hostname }}]:{{ ssh_port }}{% endif %}" {% if include_host_ip_addresses %} ,{% if ssh_port == 22 %}{{ ipv4_address }}{% else %}[{{ ipv4_address }}]:{{ ssh_port }}{% endif %}" ,{% if ssh_port == 22 %}{{ ipv6_address }}{% else %}[{{ ipv6_address }}]:{{ ssh_port }}{% endif %}" {% endif %} community.windows.win_lineinfile: create: true path: "{{ windows_system_known_hosts_path }}" line: "{{ host_line }} {{ host_key.stdout }}"