Regex_replace behavior changes when multi-line string used

Using Ansible 2.18.1 core, this command:

ansible-playbook repro.yml

with this playbook:

- name: Run the test play
  hosts: 127.0.0.1
  connection: local
  tasks:
    - name: Map issue
      delegate_to: localhost
      vars:
        wai1: "{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}"
        wai2: >-
          {{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}
      ansible.builtin.debug:
        msg:
          - "{{ wai1 }}"
          - "{{ wai2 }}"

produces this result:

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [127.0.0.1]

TASK [Map issue] ***************************************************************************************************************************************
ok: [127.0.0.1 -> localhost] => {
    "msg": [
        "able",
        "a\\1"
    ]
}

The template, taken from the first example in the filter documentation is the same in both variables, but the output is not correct in the multi-line template.

Can somebody tell me what’s going on, and how I can make this filter work in a multi-line string?

Thanks!

This related topic provided the answer: multiline automatically escapes \ so this change works:

    wai2: >-
      {{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\1') }}
2 Likes