set_fact 的 YAML 语法和 ansible 中的变量

YAML syntax for set_fact and vars in ansible

当我在 YAML 角色中设置 vars 或 facts 时,我很难区分以下语法:

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 }}

结果如下:

{        
  "app_path1": "C:\Program Files\\MyCompany\TheAppName",
  "app_path2": "C:\Program Files\\MyCompany\TheAppName\n",
  "app_path3": "C:\Program Files\\MyCompany\TheAppName\n"
}

为什么app_path2app_path3最后加了个神秘的\n?为什么我必须转义 app_path1 中的两次反斜杠?这对我来说是一种黑魔法。

对于新行,这是这两个 YAML 样式指示器的行为。
不过有 "strip chomping indicator" 可以摆脱它们:

所以,app_path2app_path3应该是

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 
  }}

至于双重转义,这个就很简单了,因为你是在双引号字符串中,所以这句话适用:

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.

来源:https://yaml.org/spec/1.2.2/#73-flow-scalar-styles

由于您想显示两个反斜杠并且必须将它们都转义,因此您最终得到了四个反斜杠。


注意:解释这一切的一个很好的工具是https://yaml-multiline.info