9

I have written an ansible script to remove SSH keys from remote servers:

---
- name: "Add keys to the authorized_keys of the user ubuntu"
  user: ubuntu
  hosts: www
  tasks:
  - name: "Remove key #1"
    authorized_key: user=ubuntu key="{{ item }}" state=absent
    with_file:
     - id_rsa_number_one.pub
  - name: "Remove key #2"
    authorized_key: user=ubuntu key="{{ item }}" state=absent
    with_file:
     - id_rsa_number_two.pub
...

Adding each file as a different task is preposterous, so I have tried using with_fileglob:

  - name: "Remove all keys at once"
    authorized_key: user=ubuntu key="{{ item }}" state=absent
    with_fileglob:
      - /Users/adamatan/ansible/id_rsa*.pub

But this fails with lines like this:

failed: [www.example.com] => (item=/Users/adamatan/ansible/id_rsa_one.pub) => {"failed": true, "item": "/Users/adamatan/ansible/id_rsa_one.pub"} msg: invalid key specified: /Users/adamatan/ansible/id_rsa_one.pub

The same key file is successfully removed using a unique task, but fails when it's a part of a fileglob.

How can I batch add or remove SSH keys using ansible?

Adam Matan
  • 128,757
  • 147
  • 397
  • 562

1 Answers1

15

I believe you are only getting the filenames using with_fileglob, but with_file retrieves the contents of the file. And the authorized_key module requires the actual key.

So you should still loop by using with_fileglob, but instead of sending the filename to the "key=" parameter, you should use the file lookup plugin).

- name: "Remove all keys at once"
    authorized_key: user=ubuntu key="{{ lookup('file', item) }}" state=absent
    with_fileglob:
      - /Users/adamatan/ansible/id_rsa*.pub
Ramon de la Fuente
  • 8,044
  • 3
  • 32
  • 31
  • 2
    So this modification works great for bulk updating/removing entries. Here's my issue - I have keys on servers from someone who is no longer here. How can I purge and overwrite the authorized_keys file with my master list of active keys? When I run this script it removes (if absent) my active keys or adds (if present) but it never removes the keys for which is not in my *.pub files. – Valien Aug 10 '16 at 15:59
  • 1
    @Valien for multiple exclusive keys, see the example in this [pull request](https://github.com/ansible/ansible-modules-core/pull/4167/files). – andrew-e Oct 24 '16 at 01:19
  • 1
    You could also create `~/.ssh/` and copy over static `authorized_keys` files for all the users in some host groups. In that case you would have full control over file contents. – andrew-e Oct 24 '16 at 02:08