add-ssh-keys.yml

Add all the hosts from your ansible inventory to your .ssh/known_hosts and add keys to the hosts.

3

Votes

---
# Original idea found at http://stackoverflow.com/a/39083724
#
#   ansible -i inventory.ini add-ssh-keys.yml
#
- name: Store known hosts of 'all' the hosts in the inventory file
  hosts: localhost
  connection: local
  vars:
    ssh_known_hosts_command: "ssh-keyscan -T 10"
    ssh_known_hosts_file: "{{ lookup('env','HOME') + '/.ssh/known_hosts' }}"
    ssh_known_hosts: "{{ groups['all'] }}"


  tasks:
  - name: For each host, scan for its ssh public key
    shell: "ssh-keyscan {{ item }},`dig +short {{ item }}`"
    with_items: "{{ ssh_known_hosts }}"
    register: ssh_known_host_results
    ignore_errors: yes
    tags:
      - ssh

  - name: Remove the public key in the '{{ ssh_known_hosts_file }}'
    known_hosts:
      name: "{{ item.item }}"
      state: "absent"
      path: "{{ ssh_known_hosts_file }}"
    with_items: "{{ ssh_known_host_results.results }}"
    tags:
      - ssh

  - name: Add/update the public key in the '{{ ssh_known_hosts_file }}'
    known_hosts:
      name: "{{ item.item }}"
      key: "{{ item.stdout }}"
      state: "present"
      path: "{{ ssh_known_hosts_file }}"
    with_items: "{{ ssh_known_host_results.results }}"
    tags:
      - ssh

  - name: For each host, ssh-copy-id my ssh public keys to the host
    shell: "sshpass -p {{ ansible_ssh_pass }} ssh-copy-id {{ item }}"
    with_items: "{{ ssh_known_hosts }}"
    when: not (( ansible_ssh_pass is undefined ) or ( ansible_ssh_pass is none ) or ( ansible_ssh_pass | trim == ''))
    tags:
      - sshcopy

Vote Here

You must earn at least 1 vote on your snippets to be allowed to vote

Terms Of Use

Privacy Policy

Featured snippets are MIT license

Gears & Masters

Advertise

DevOpsnipp.com © 2020

medium.png