---
- name: Add host keys in /etc/ssh/ssh_known_hosts for live/cold-migration
  become: true
  check_mode: no
  block:
    # Workaround https://bugs.launchpad.net/tripleo/+bug/1810932
    # Ansible modules perform a replace instead of in-place modification.
    # This breaks propagation of changes to containers that bind mount ssh_known_hosts
    - name: Create temporary file for ssh_known_hosts
      tempfile:
        state: file
      register: ssh_known_hosts_tmp
    - name: Create a temporary copy of ssh_known_hosts
      shell: |
        if [[ -e /etc/ssh/ssh_known_hosts ]]; then
          cat /etc/ssh/ssh_known_hosts > '{{ ssh_known_hosts_tmp.path }}'
        fi
    - name: Add host keys to temporary ssh_known_hosts
      lineinfile:
        path: "{{ ssh_known_hosts_tmp.path }}"
        line: "{{ ssh_known_hosts[hostvars[item]['ansible_hostname'] | lower] + ' ssh-rsa ' + hostvars[item]['ansible_ssh_host_key_rsa_public'] }}"
        create: yes
      with_items: "{{ groups['overcloud']|intersect(play_hosts) }}"
    - name: In-place update of /etc/ssh_known_hosts
      shell: |
        cat '{{ ssh_known_hosts_tmp.path }}' > /etc/ssh/ssh_known_hosts
        rm -f '{{ ssh_known_hosts_tmp.path }}'
  tags:
    - tripleo_ssh_known_hosts

