【问题标题】:Ansible: check whether a file contains only given lines, no moreAnsible:检查文件是否只包含给定的行,不再包含
【发布时间】:2018-04-15 07:42:15
【问题描述】:

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

  1. 如果缺少,请添加(没问题,lineinfile
  2. 如果其他人偷偷输入了额外的密钥(不在“with_items”列表中),请将其删除并返回一些警告或其他内容。嗯...“更改”也可以接受,但最好以某种方式区分“缺失”和“潜入”行。

第一部分很简单:

- 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

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

有什么想法吗?

【问题讨论】:

  • lineinfile 不是你的朋友。
  • 为什么不总是用源文件覆盖目标?
  • @NeilMcGuigan:这可行,但我不知道是否缺少某些键或是否有一些额外的键。

标签: security ansible ssh-keys system-administration


【解决方案1】:

authorized_key_moduleexclusive 选项。
但请注意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         

使用前测试!

如果您在文件中有密钥,您会发现this 回答很有用。

【讨论】:

  • 哇!那很好!但是,如何定义 ssh_keys 变量?我尝试使用多行字符串,它只是将其拆分为带有换行符的字符...这是否等同于使用带有“with_file”选项的密钥文件?
  • 抱歉,忘记定义了。此外,如果您在文件中有密钥,我已经添加了指向其他答案的链接。
  • 谢谢!这正是我想要的。
  • 像魅力一样工作。谢谢!
猜你喜欢
  • 2013-04-22
  • 2018-05-23
  • 1970-01-01
  • 2011-10-28
  • 2013-08-04
  • 2011-08-22
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多