Ansible正则表达式环视无法替换模式。

3
我的正则表达式可以获取正确的单词;然而,ansible却无法更改它 在此输入图片描述

我的ansible代码:

hosts: all
gather_facts: False
become: true

tasks:
  - name: Checking if chargen configuration is present in the files
    ansible.builtin.replace:
      path:  /etc/xinetd.d/chargen
      regexp: '(?<=disable\s{9}\S\s)yes'
      replace: 'no'
    register: test
   - name: Gathered
    ansible.builtin.debug:
      msg: "{{ test }}"

结果:它是“ok”,但没有改变。

插入图像描述 插入图像描述


尝试使用 ansible.builtin.lineinfile:,然后使用 regexp: '^(\s*disable\s*=\s*)yes\s*$'line: '\g<1>no'backrefs: yes - Wiktor Stribiżew
你好,它可以工作,但它只改变了下面的那一行。它没有改变上面的那一行。我需要运行任务两次吗? - Ana Marie De Vera
有趣,ansible.builtin.replace: 能够按预期工作吗? - Wiktor Stribiżew
嗨,我用你的正则表达式解决了它。任务:
  • 名称:将Chargen“禁用”设置为NO ansible.builtin.replace: 路径:/etc/xinetd.d/chargen 正则表达式:'^(\sdisable\s=\s*)yes\s*$' 替换:'\g<1>no'
\g<1>是否指第一组,并且在使用时表示应用以下未通过组封装的更改?
- Ana Marie De Vera
1个回答

1

您可以使用

tasks:
  - name: Checking if chargen configuration is present in the files
    ansible.builtin.replace:
      path:  /etc/xinetd.d/chargen
      regexp: '^(\s*disable\s*=\s*)yes\s*$'
      line: '\g<1>no'
    register: test
   - name: Gathered
    ansible.builtin.debug:
      msg: "{{ test }}"

这里,

  • ^(\s*disable\s*=\s*)yes\s*$ - 匹配
    • ^ - 字符串开始
    • (\s*disable\s*=\s*) - 捕获组1(可以使用\1\g<1>引用它):零个或多个空格,disable,零个或多个空格,=,零个或多个空格
    • yes - yes字符串
    • \s* - 零个或多个空格
    • $ - 字符串结束。
  • '\g<1>no' 用捕获组1的值和no字符串替换匹配的行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接