Ansible ‘raw’ module – using escape characters in regex to perform ‘sed’ command

ansible

I want to use the raw module to run a 'sed' command which will contain escape characters.

- name: Search for prefix in file and replace all following text with addition
  raw: "sed 's/\({{ prefix }}\)\(.*\)/\1 {{ addition }}/g' {{ file }} > {{ file }}.test"

This, however complains with:

ERROR! Syntax Error while loading YAML.
found unknown escape character

With the '^' pointing at the first '\' in the string. How to I include escape characters in this command without ansible trying to process them?

Best Answer

The task below works

- raw: 'sed --regexp-extended ''s/({{ prefix }})(.*)/\1 {{ addition }}/g'' {{ file }} > {{ file }}.test'

with variables

file: test
prefix: AAA
addition: XXX

gives

$ cat test
alsdjflaskdjfasn AAA fasdfasdfsadf

$ cat test.test 
alsdjflaskdjfasn AAA XXX

Modified regex from "^" till "$"

- raw: 'sed --regexp-extended ''s/^(.*)({{ prefix }})(.*)$/\1 {{ addition }}/g'' {{ file }} > {{ file }}.test2'

gives

$ cat test.test2
alsdjflaskdjfasn  XXX

Notes