Skip to content

Instantly share code, notes, and snippets.

@jehaby
Forked from sgargan/remove_keys.yml
Created August 8, 2017 16:29
Show Gist options
  • Save jehaby/6363181cf7352cb3e4af99eb3902e164 to your computer and use it in GitHub Desktop.
Save jehaby/6363181cf7352cb3e4af99eb3902e164 to your computer and use it in GitHub Desktop.
Removing unknown keys from authorized keys with Ansible
- hosts: localhost
connection: local
gather_facts: false
tasks:
- name: add a couple of keys to an authorized_keys file
authorized_key: path='./keys' user=sgargan key="{{ lookup('file', './ansible.pub') }}"
- authorized_key: path='./keys' user=sgargan key="{{ lookup('file', './sgargan.pub') }}"
- name: count keys in file
shell: grep -c ssh keys
register: key_count
- name: validate there are 2 keys
assert:
that:
- key_count.stdout == '2'
# read in the valid key and use it to make regex using negative lookahead
- set_fact: valid_key="{{ lookup('file', './ansible.pub') }}"
- name: create regex using negative lookahead for 'doesn't start with the first 50 chars of valid key'
set_fact: regex="^(?!{{ valid_key[0:50] }}).*"
- name: replace all other keys in keys file using regex
replace: dest=./keys regexp='{{ regex }}' backup=yes
- shell: grep -c ssh keys
register: key_count
- name: validate there is only 1 key
assert:
that:
- key_count.stdout == '1'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment