Use 7.3.2. Single-Quoted Style. Quoting:
| the “\” and “"” characters may be freely used.
For example, given the variable
parent_region: "1933"
the tasks below
- set_fact:
parent_region: 'r"{{ parent_region }}"'
- debug:
var: parent_region
- debug:
msg: "{{ parent_region|type_debug }}"
give (the quotes are part of the string)
parent_region: r"1933"
msg: str
The default type in Ansible (Python3) is a Unicode string, e.g.
- set_fact:
parent_region: "1933"
- debug:
var: parent_region
- debug:
msg: "{{ parent_region|type_debug }}"
give (the quotes are NOT part of the string)
parent_region: '1933'
msg: AnsibleUnicode
You can create a custom filter and choose the encoding, e.g.
shell> cat filter_plugins/python_encode.py
def python_encode(s, encoding):
return s.encode(encoding)
class FilterModule(object):
def filters(self):
return {
'python_encode': python_encode,
}
then the tasks
- set_fact:
parent_region: "{{ parent_region|python_encode('raw_unicode_escape') }}"
- debug:
var: parent_region
- debug:
msg: "{{ parent_region|type_debug }}"
give
parent_region: b'1933'
msg: str
See Python str vs unicode types.