2016-01-08

Ansible: using numbered backreference followed by digit in lineinfile

While playing around with Ansible I've stumbled over a problem with backreferences followed by a digit.

The problem

I've want to modify some lines in a file like this:
# an example
something=xxxx
Lets assume I want to update the xxxx with some values.

A possible ansible playbook may look as follows:
---
- hosts: localhost
  tasks:
  - name: create file
    copy: src=./demo dest=/tmp/demo

  - name: update xxxx
    lineinfile:
      dest: /tmp/demo
      regexp: '^(.*)xxxx'
      line:   '\1{{ansible_date_time.year}}'
      backrefs: yes
      state: present

The update task "update xxxx" should inspect the file, search for the line with "xxxx" and replace the "xxxx" while keeping the part in front of it.
But the result is:
# an example
P16

The problem is that the backreference \1 is not resolved as expected but merged with (some) of the year digits. This results in the "P".

Solution

To solve it you have to use named groups. A named group is defined by (?P<name>pattern) and can than be reference with \g<1> or \g<name>

The following playbook shows all three variants.
For the example file
# an example
simple backref=xxxx
group backref with number=yyyy
group backref with name=zzzz
the generated output is:
# an example
P16
group backref with number=2016
group backref with name=2016

Update 2019-10-29: Replace inline code by embedded github gist to fix issue with not shown group in example.

Keine Kommentare

Kommentar veröffentlichen