【问题标题】:yaml multi line syntax without newline to space conversion没有换行符的yaml多行语法到空格转换
【发布时间】:2015-06-25 20:28:36
【问题描述】:

我有类似这本词典的东西:

env: qat
target_host: >
         {%if env in ['prd'] %}one
         {%elif env in ['qat','stg'] %}two
         {%else%}three
         {%endif%}

当我打印它时,我得到:

好的:[本地主机] => { “变量”:{ “target_host”:“两个” } }

所以它将行尾的 \n 转换为空格。这正是它应该做的。但是在这种情况下,我只是试图分散线条以使 if/else 的结构更具可读性,并且我不想要额外的空间。如果我将其全部放在一行上而不使用 >,它会按预期工作,但我希望能够使其成为多行,以便更易于阅读。

我发现了这个问题 Is there a way to represent a long string that doesnt have any whitespace on multiple lines in a YAML document?

所以我可以这样做:

env: qat
target_host: "{%if env in ['prd'] %}one\
              {%elif env in ['qat','stg'] %}two\
              {%else%}three\
              {%endif%}"

这给出了预期的结果。

有没有办法做到这一点而不会更加混乱?

【问题讨论】:

标签: ansible


【解决方案1】:

在 Jinja* 中,您可以通过在块的开头/结尾添加减号来去除空格/换行符。这应该可以解决问题:

env: qat
target_host: >
         {%if env in ['prd'] -%}one
         {%- elif env in ['qat','stg'] -%}two
         {%- else -%}three
         {%- endif%}

* Jinja 2 是 Ansible 使用的模板引擎。

【讨论】:

  • 完美!正是我想要的。
【解决方案2】:

也许您需要的是 | 文字?

env: qat
target_host: |
         {%if env in ['prd'] %}one
         {%elif env in ['qat','stg'] %}two
         {%else%}three
         {%endif%}

这不会像> 那样将换行符“折叠”到空格中

【讨论】:

  • 这个给我加了“\n”
猜你喜欢
  • 2013-10-10
  • 2017-05-21
  • 2018-02-05
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 2018-04-20
  • 2011-09-15
  • 1970-01-01
相关资源
最近更新 更多