使用ansible with replace/lineinfle模块删除conf文件中的重复条目

使用ansible with replace/lineinfle模块删除conf文件中的重复条目,ansible,Ansible,我正试图在replace和lineinfle模块的帮助下,使用ansible更新Linux中的ssh配置 我的要求是, ssh文件包含: PermitRootLogin Yes #PermitRootLogin Yes PermitRootLogin yes permitrootlogin yes 我的ansible剧本看起来像: lineinfile: path: /tmp/ssh regexp: "{{ item.From }}"

我正试图在replace和lineinfle模块的帮助下,使用ansible更新Linux中的ssh配置

我的要求是,

ssh文件包含:

PermitRootLogin Yes
#PermitRootLogin Yes
PermitRootLogin yes
permitrootlogin yes
我的ansible剧本看起来像:

lineinfile:
        path: /tmp/ssh
        regexp: "{{ item.From }}"
        line: "{{ item.To }}"
        state: present
        backrefs: yes
      with_items:
       - { From: '(?i)(.*PermitRootLogin Yes*)', To: '#PermitRootLogin No' }
       - { From: '(?i)(.*#PermitRootLogin Yes*)', To: '' }
       - { From: '(?i)(.*PermitRootLogin Yes*)', To: '' }
预期结果应为“permitrotlogin No”,配置文件中只应有一个条目

但事实并非如此。有人能帮忙吗?我需要一个任务来完成这项活动。不应该超过这个。

这是一个解决方案:

- name: PermitRootLogin other than 'No' is absent
  lineinfile:
    path: /tmp/ssh
    state: absent
    regexp: '(?i)^[\s#]*PermitRootLogin\s+[^N][^o]'

- name: PermitRootLogin No is present
  lineinfile:
    path: /tmp/ssh
    state: present
    regexp: '^[\s#]*PermitRootLogin\s'
    line: 'PermitRootLogin No'

别忘了通知你的处理程序重新启动或重新加载sshd。

请正确设置你的问题的格式,使用
code
格式,因为这样很难阅读。很好的答案,唯一的一点是,我不知道他是否想要“to”“#permitrologin No”在他的示例中,它的注释是,可能是他键入错误(对我来说,没有必要评论它)@Rene-我需要这个任务应该是单个任务,而不是多个任务。正如你提到的,第一个任务不是删除行。状态更改为“OK”.-name:permitrotlogin而不是'Yes'不存在lineinfle:path:/tmp/sshd_配置状态:不存在regexp:'(?i)^[\s#]*permitrotlogin\s+[^Y][^e][^s]'您的ssh文件除了这4行之外还有更多的内容?为什么只有一个任务?使用两个任务没有问题。@ikora-第一个任务工作不正常。'我已更新为“是”。它没有删除这一行。我已经提到了上面的一行。请尝试此regexp:'(?I)^[\s#]*permitrotlogin\s+[^Y][^e][^s]?'(添加问号)。这是因为“否”比“是”短一个字符。这当然有点特别。为什么需要将其作为单个任务?可以在块或循环中组合任务,但这有什么区别?