7

Based on this example:

- lineinfile: dest=/opt/jboss-as/bin/standalone.conf regexp='^(.*)Xms(\d+)m(.*)$' line='\1Xms${xms}m\3' backrefs=yes

from this documentation, it was tried to do a regex-replace in Ansible.

Ansible version

user@server:/home$ ansible --version
ansible 2.1.1.0

/path/to/file:

helloworld

Ansible snippets:

- lineinfile:
  dest: /path/to/file
  regexp='^(hello)world$'
  line='\1030'

attempt 2

- lineinfile:
  dest: /path/to/file
  regexp='^(hello)world$'
  line="\1030"

Expected outcome:

hello030

Current outcome:

\1030

Questions

  1. Why is the outcome \1030 instead of hello030?
  2. How to solve it?
030
  • 5,901
  • 13
  • 68
  • 110

2 Answers2

11

Why is the outcome \1030 instead of hello030?

The lineinfile module default is backrefs: false. Your regexp='^(hello)world$' matches the entire contents of file. Literal from line='\1030' replaces contents.

How to solve it?

  1. Turn on backrefs with backrefs: true
  2. Use a named group in line:

A backref followed by numbers will not function as expected. You will need a named group instead. e.g. \g<1>

- name: Replace the world
  lineinfile:
    dest: file
    regexp: '^(hello)world$'
    line: '\g<1>030'
    backrefs: true
030
  • 5,901
  • 13
  • 68
  • 110
jscott
  • 24,484
  • 8
  • 79
  • 100
-2

I suppose it is because it matches whole \1030 (as 1030-th backref). Maybe try \1 030 first and you will see, if it is the reason.