handle backslash in ansible

I have a variable which has value: “domain\user”. I am trying to split to get the user name

I have tried the below code which works well but can’t handle escape sequence like \n \r etc. for example “domain\naman”

Could someone please check and let me know if I am missing something here.

tasks:

  • name: handle escape character in domain user

set_fact:

username: “{{ domain_username.split(separator)[-1] }}”

vars:

separator: ''

Use "Single-Quoted Style" to declare domain_username.
https://yaml.org/spec/1.2/spec.html#id2788097

For example

- hosts: localhost
  vars:
    dname: 'domain\naman'
    sep: '\'
  tasks:
    - debug:
        msg: "{{ dname.split(sep)[-1] }}"

gives

    "msg": "naman"

HTH,

  -vlado

It worked when domain user is inside the playbook. but it doesn't work when
passed at runtime.

ansible-playbook play.yml -e dname='domain\namam'

>
> Use "Single-Quoted Style" to declare domain_username.
> https://yaml.org/spec/1.2/spec.html#id2788097
>
> For example
>
> - hosts: localhost
> vars:
> dname: 'domain\naman'
> sep: '\'
> tasks:
> - debug:
> msg: "{{ dname.split(sep)[-1] }}"
>
> gives
>
> "msg": "naman"

Right. Command-line can't work. It's evaluated by the shell. Put the extra
variables into a file and let YAML to evaluate the "single-quoted" variables.
For example the command-line below works fine again

cat myvar.yml

dname: 'domain\namam'

cat playbook.yml

- hosts: localhost
  tasks:
    - debug:
        msg: "{{ dname.split(sep)[-1] }}"
      vars:
        sep: '\'

ansible-playbook playbook.yml -e @myvar.yml

...
TASK [debug]