Skip to content

Instantly share code, notes, and snippets.

@sgargan
Created February 13, 2015 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sgargan/ccf04b5a202a226aec26 to your computer and use it in GitHub Desktop.
Save sgargan/ccf04b5a202a226aec26 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