Reputation: 3085
I have difficulties to get the differences between the following syntaxes when I set vars or facts in a YAML role:
vars:
app_path1: "{{ (ansible_facts.env.ProgramFiles + '\\\\' + item.installation_directory) if item.executable else root_dir }}"
app_path2: >
{{ (ansible_facts.env.ProgramFiles + '\\' + item.installation_directory) if item.executable else root_dir }}
app_path3: |
{{ (ansible_facts.env.ProgramFiles + '\\' + item.installation_directory) if item.executable else root_dir }}
Here is the result:
{
"app_path1": "C:\\Program Files\\\\MyCompany\\TheAppName",
"app_path2": "C:\\Program Files\\\\MyCompany\\TheAppName\n",
"app_path3": "C:\\Program Files\\\\MyCompany\\TheAppName\n"
}
Why app_path2
and app_path3
added a mysterious \n
at the end? And why must I escape twice the backslashes in app_path1? It's a kind of black magic for me.
Upvotes: 2
Views: 387
Reputation: 39264
For the new line, this is the behaviour of those two YAML style indicator.
There is "strip chomping indicator" to get rid of them though:
So, app_path2
and app_path3
should be
app_path2: >-
{{
(ansible_facts.env.ProgramFiles + '\\' + item.installation_directory)
if item.executable else root_dir
}}
app_path3: |-
{{
(ansible_facts.env.ProgramFiles + '\\' + item.installation_directory)
if item.executable else root_dir
}}
As for the double escaping, this is quite simple, since you are in a double quoted string, this remark applies:
The double-quoted style is specified by surrounding “
"
” indicators. This is the only style capable of expressing arbitrary strings, by using “\
” escape sequences. This comes at the cost of having to escape the “\
” and “"
” characters.
Source: https://yaml.org/spec/1.2.2/#73-flow-scalar-styles
Since you want to display two backslashes and that you have to escape them both, you end up with four of them.
Note: a pretty good tool for the explanation of all this is https://yaml-multiline.info
Upvotes: 2