在 YAML 中使用 enter 处理空格的更漂亮的方法

A prettier way to handle spaces with enters in YAML

这更像是一个样式问题。我有这段丑陋的代码:

- name: download something
  shell: "wget https://www.{{ my_var }}\
    a_string\
    {{ a_very_long_string_to_show_what_i_mean }}"

在我看来,这看起来很难看。由于 URL 必须是 'whole',没有空格和引号等等,我需要用 \ 转义每个换行符。呸

但是,我不能使用休息时间,例如>| 因为这将在最终结果中包含空格,并且代码会出错。

遵循 ansible-lint 准则,我不希望单行上的字符串大小大于大约 84 个字符。在这个例子中,当我必须下载一个文件时,我不能简单地将字符串放在一行上。

预期输出:

- name: pretty download something
  shell:
    wget https://www.{{ my_var }}
    a_string
    {{ a_very_long_string_to_show_what_i_mean }}

However, I can't use breaks, e.g. > or | since that will include spaces in the end result, and the code will error.

这实际上只说对了一半。
你可以将它与 Jinja 的 whitespace control mechanism 结合起来,去除那些不需要的白色space。

基本上,在表达式块的开头或结尾添加破折号 trim 前后的多余白色space 或回车符 return。


鉴于:

- hosts: localhost
  gather_facts: no

  tasks:
    - debug:
        msg: >-
          wget https://www.{{ my_var -}}
          a_string
          {{- a_very_long_string_to_show_what_I_mean -}}
      vars:
        my_var: example.org/
        a_very_long_string_to_show_what_I_mean: _foo

这产生:

ok: [localhost] => 
  msg: wget https://www.example.org/a_string_foo

请注意:

wget https://www.{{ my_var -}}

不需要开头小胡子上的破折号,因为在该变量之前没有额外的 space。