Ansible:检查文件是否只包含给定的行,没有更多

Ansible: check whether a file contains only given lines, no more

通过使用 Ansible,我尝试确保我们服务器的 .ssh/authorized_keys 文件仅包含一组给定的 ssh 密钥。不管怎样安排。

  1. 如有遗漏,补上(没问题,lineinfile
  2. 如果其他人偷偷输入了额外的密钥(不在 "with_items" 列表中),请将其删除并 return 一些警告或其他内容。好吧... "changed" 也可以接受,但是最好以某种方式区分 "missing" 和 "sneaked in" 行。

第一部分很简单:

- 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

但第二部分看起来更棘手。至少要用简短而优雅的代码来完成它。

有什么想法吗?

authorized_key_module 并且有 exclusive 选项。
但请注意 exclusive 不适用于 with_items.

使用这样的东西:

- 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         

使用前测试!

如果文件中有密钥,您会发现 有用的答案。