Home > OS >  Ansible regex lookaround cannot replace the pattern
Ansible regex lookaround cannot replace the pattern

Time:09-23

My regex can fetch the correct word; however, the ansible fails to change it enter image description here

My ansible code:

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 }}"

Result: it's "ok" but not changed

enter image description here enter image description here

CodePudding user response:

You can use

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 }}"

Here,

  • ^(\s*disable\s*=\s*)yes\s*$ - matches
    • ^ - start of string
    • (\s*disable\s*=\s*) - Capturing group 1 (it can be referred to with \1 or \g<1>): zero or more whitespaces, disable, zero or more whitespaces, =, zero or more whitespaces
    • yes - yes string
    • \s* - zero or more whitespaces
    • $ - end of string.
  • '\g<1>no' replaces the matched line with the value in Group 1 and no string.
  • Related