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

问题描述

我正在尝试使用 ansible 在替换和 lineinfile 模块的帮助下更新 Linux 中的 ssh 配置。

我的要求是,

ssh 文件包含:

PermitRootLogin Yes
#PermitRootLogin Yes
PermitRootLogin yes
permitrootlogin yes

我的 ansible playbook 看起来像:

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: '' }

预期结果应该是“PermitRootLogin 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。