Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
- hosts: all
gather_facts: false
become: yes
target_user: /home/targetuser/.ssh/known_hosts
separator: /
#Run SSH-keygen and remove entries that use a FQDN or shortname
#Old file with be saved in {{ target_user }}/known_hosts.old
- name: "Run ssh-keygen and remove {{ target_host }}"
shell: |
ssh-keygen -R {{ target_host }} -f {{ target_user }}
ssh-keygen -R {{ target_host.split(".")[0] | lower }} -f {{ target_user }}
#Runs ssh-keyscan and adds host entry with the following formatting:, ssh-rsa [key]
- name: "Run ssh-keyscan and add {{ target_host }}"
shell: ssh-keyscan {{ target_host }} >> {{ target_user }}
#Since we have to use become to change this, it will change the permissions to root. This will revert back to previous permissions. Separator variable must be used because there is forward and backslash are
#hard to use for a split function without escaping them in weird ways.
- name: Fix ownership of known_hosts for "{{ target_user }}"
path: "{{ target_user }}"
owner: "{{ target_user.split(separator)[2] | lower }}"
group: "{{ target_user.split(separator)[2] | lower }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment