Pervent Ansible from changing \a to \u0007 in a variable

Viewed 175

I have this user name DOMAIN\adm123456789 as a --extra-vars called SPSiteOwnerAlias to my playbook:

- name: Display username
  debug:
    msg: '{{ SPSiteOwnerAlias }}'

When I execute the playbook it displays:

"msg": "DOMAIN\u0007dm123456789"

I seems for some reason Ansible is changing \a to \u0007.
How can I prevent this?

2 Answers

As pointed in one of the comment in the issue tracker of Ansible, using the key=value syntax could lead you to such issues. Of course, you won't be able to use YAML syntax, as advised in the comment there, because you are using the command line --extra-vars arguments, but even there, there are two possible sytaxes:

  1. key=value, as you are using it, most probably
  2. {'key':'value'}, with a JSON string format

And if you happen to use the later, then your issue is no more!

Given the playbook play.yml

- hosts: all
  gather_facts: no
      
  tasks:
    - debug: 
        msg: "{{ SPSiteOwnerAlias }}"

Here is a recap reproducing your issue:

$ ansible-playbook play.yml --extra-vars "SPSiteOwnerAlias=DOMAIN\adm123456789"

PLAY [all] ***********************************************************************************************************

TASK [debug] *********************************************************************************************************
ok: [localhost] => {
    "msg": "DOMAIN\u0007dm123456789"
}

PLAY RECAP ***********************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

And here is a recap, using the JSON format:

--extra-vars "{'SPSiteOwnerAlias':'DOMAIN\adm123456789'}"

This one works properly:

$ ansible-playbook play.yml --extra-vars "{'SPSiteOwnerAlias':'DOMAIN\adm123456789'}"

PLAY [all] ***********************************************************************************************************

TASK [debug] *********************************************************************************************************
ok: [localhost] => {
    "msg": "DOMAIN\\adm123456789"
}

PLAY RECAP ***********************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

The problem here is, that \a has a special meaning in python.
See this post.

You need to escape the \ by using \\ instead.

If you do not set the variable yourself (e.g. in the inventory), you can use a replace filter when using the variable:
'{{ SPSiteOwnerAlias | replace("\a", "\\a") }}'

Related