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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay