DEV Community

Roy
Roy

Posted on

ansible lineinfile 中 regexp 如果匹配多行,只会修改其中一行

    - name: sshd configuration
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "{{ item.regexp }}"
        line: "{{ item.line }}"
      loop:
        - { regexp: '^[\s#]*AllowTcpForwarding', line: "AllowTcpForwarding yes" }
      notify: reload sshd
Enter fullscreen mode Exit fullscreen mode

最开始 目标文件中有两行匹配 regexp ^[\s#]*AllowTcpForwarding, 但两行都匹配 line, 所以只有第二行被替换,如果要确保多余的行 AllowTcpForwarding no 被删除,需要使用

    - name: sshd configuration
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: "{{ item.regexp }}"
        line: "{{ item.line | default(omit) }}"
        state: "{{ item.state | default('present') }}"
      loop:
        - { regexp: '^\s*AllowTcpForwarding\s+no', state: "absent" }
        - { regexp: '^[\s#]*AllowTcpForwarding', line: "AllowTcpForwarding yes" }
      notify: reload sshd
Enter fullscreen mode Exit fullscreen mode

if state is absent, ansible will delete all lines match the regexp.

Top comments (0)