5

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?
  • what version of ansible are you running? – Petter H Sep 15 '16 at 11:05
  • @PetterH ansible 2.1.1.0 – 030 Sep 15 '16 at 11:08
  • The default is backrefs: no, your snips don't define it. Can you test with backrefs: yes? I don't have access just now to do so. – jscott Sep 16 '16 at 1:25
9

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
-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.

  • line='\1Xms${xms}m\3' returns \1Xms as well – 030 Sep 15 '16 at 23:13

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.