escape special char in ansible

Need help with escaping special characters for lineinfile

I'm trying to do the following to simply change the bash prompt

- name: Editing bashrc to change bash prompt lineinfile: path: /etc/bashrc regexp: "export PS1='\[\033[01;31m\]\u@\h\[\033[01;34m\] \w #\[\033[00m\]'" line: "export PS1='\[\033[01;31m\]\u@\h\[\033[01;34m\] \w #\[\033[00m\]'"

but as you can see, the regexp: value is full of special characters that I need to escape. Is there a simple way to escape the entire line? Or maybe there's another way I should be doing this?

i did try to do the following: 1 : add the text in a variable for re-use

- hosts: ssh vars: export: "export PS1='\[\033[01;31m\]\u@\h\[\033[01;34m\] \w #\[\033[00m\]'"
- name: Editing bashrc to change bash prompt lineinfile: path: /etc/bashrc line: "{{ export }}"

and even with !unsafe for raw_strings

  1. To escape special characters within a regex, use the “regex_escape” filter:

{{ '^f.o(.)$' | regex_escape() }}

maybe my syntax is not goot but i keep having an issue:

The offending line appears to be: vars: export: "export PS1='\[\033[01;31m\]\u@\h\[\033[01;34m\] \w #\[\033[00m\]'" ^ here

Thanks!

0

1 Answer

This is a non exhaustive answer but these are the most straightforward examples IMO.

Option 1: escape the backslashes inside the double quotes

export: "export PS1='\\[\\033[01;31m\\]\\u@\\h\\[\\033[01;34m\\] \\w #\\[\\033[00m\\]'"

Option 2: get rid off the outer quotes using a scalar block

export: |- export PS1='\[\033[01;31m\]\u@\h\[\033[01;34m\] \w #\[\033[00m\]'

You can have a look at e.g. learn yaml in Y minutes to get an overview of the different solutions to declare a string in yaml and the different types of escapes they support.

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like