This entry is the 11th day post of Ansible 3 Advent Calendar 2019. It was just vacant, so I wrote it.
--Set Ansible so that the confirmation message at the first SSH connection is not displayed.
--I want to prevent the confirmation message from being issued only when connecting to a specific host by SSH. --Assuming that there are host A and host B, SSH connection to A-> B --Assuming that the client executing Ansible can make SSH connection to both A and B -** Don't mess with StrictHostKeyChecking settings **
--Enter B's public key information directly in A's known_hosts --Use Ansible's known_hosts module
main.yml
# vars:
#     - ssh_host_and_user:
#         - from:
#             user: vagrant
#             host: A
#           to:
#             user: root
#             host: B
#Store the public key of the root user of host B in a variable
- name: Copy public key to variable
  slurp:
    src: "{{ ROOT_PUBLIC_KEY_HOST_B }}"
  with_items: "{{ ssh_host_and_user }}"
  register: to_host_public_key
  when: item.to.host == inventory_hostname
#Host A,Get the home directory of any user
- name: Get home direcotry of from.user
  shell: |
    set -o pipefail
    egrep "^{{ item.from.user }}:" /etc/passwd | awk -F: '{ print $6 }'
  register: from_user_home_directory
  with_items: "{{ ssh_host_and_user }}"
  changed_when: false
  failed_when: from_user_home_directory.rc != 0
  when: item.from.host == inventory_hostname
#Host B's root user's public key, Host A's known_Write to hosts
- name: Add Host B infomation to known_hosts in Host A
  become: item.from.user
  known_hosts:
    key: "{{ item.to.host }}
          {{ hostvars[item.to.host].to_host_public_key.results[0].content | b64decode }}"
    name: "{{ item.to.host }}"
    path: "{{ hostvars[item.from.host].from_user_home_directory.results[my_idx].stdout }}/.ssh/known_hosts"
    state: present
  with_items: "{{ ssh_host_and_user }}"
  loop_control:
    index_var: my_idx
  when: item.from.host == inventory_hostname
Using the known_hosts module, I wrote a process so as not to issue the SSH initial confirmation message. --It was possible to prevent the confirmation message from being issued only when making an SSH connection to a specific host. --In some cases, it may be more convenient to tweak the StrictHostKeyChecking settings.
Recommended Posts