Problem with regexp in ansible module shell

In my ansible-playbook, task realize problem replace in file text with characters. I'm using ansible module shell with sed.

i want realize problem

txt.file: Some text @@VAR_NUMBER_ONE@@

new txt.file: Some text {{VAR_NUMBER_ONE}}

  - name: sed
      shell: sed -i 's|@@\([a-zA-Z_ ]*\)@@|\{{\1}}|g' txt.file

I've got fatal error

fatal: [localhost]: FAILED! => { "msg": "An unhandled exception occurred while templating 's|@@\([a-zA-Z_ ]*\)@@|\{{\1}}|g'. Error was a , original message: unexpected char u'\\' at 25" }

Upvotes: 0

Views: 451

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68394

Q: "replace in file text with characters"

txt.file before: Some text @@VAR_NUMBER_ONE@@

txt.file after: Some text {{VAR_NUMBER_ONE}}

A: The task below does the job.

- replace:
    path: "txt.file"
    regexp: '^(.*)@@(.*)@@$'
    replace: '{{ "\1" + "{{" + "\2" + "}}" }}'

The regexp string explained:

  • ^ beginning of the string
  • (.*) any sequence stored in \1
  • @@ matches @@
  • (.*) any sequence stored in \2
  • @@ matches @@
  • $ end of the string

The replace string is created by concatenation of 4 strings because in YAML {{ and }} is used to expand variables.

Upvotes: 0

Related Questions