1

By using Ansible, I try to make sure that the .ssh/authorized_keys files of our servers contain only a given set of ssh keys. No matter the arrangement.

  1. If one is missing, add it (no problem, lineinfile)
  2. If someone else sneaked in an extra key (which is not in the "with_items" list), remove it and return some warning, or something. Well... "changed" could be acceptable too, but it would be nice to differentiate somehow the "missing" and "sneaked in" lines.

The first part is easy:

- name: Ensure ssh authorized_keys contains the right users
  lineinfile:
    path: /root/.ssh/authorized_keys
    owner: root
    group: root
    mode: 0600
    state: present
    line: '{{ item }}'

  with_items:
    - ssh-rsa AABBCC112233... root@someserver.com
    - ssh-rsa DDEEFF112233... user@anothersomeserver.com

But the second part looks more tricky. At least to get it done with short and elegant code.

Any ideas?

Julen Larrucea
  • 149
  • 1
  • 9

1 Answers1

4

There's authorized_key_module and it has exclusive option.
But pay attention that exclusive doesn't work with with_items.

Use something like this:

- name: Ensure ssh authorized_keys contains the right users
  authorized_key:
    user: root
    state: present
    exclusive: yes
    key: '{{ ssh_keys | join("\n") }}'
  vars:
    ssh_keys:
      - ssh-rsa AABBCC112233... root@someserver.com
      - ssh-rsa DDEEFF112233... user@anothersomeserver.com         

Test before use!

If you have keys in files, you can find this answer useful.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193