gpt4 book ai didi

ansible - 保留缩进和换行符时的YAML多行字符串

转载 作者:行者123 更新时间:2023-12-03 16:53:28 30 4
gpt4 key购买 nike

背景:

这是使用模板从模板构造yaml文件的Ansible剧本。所以基本上我有一个带有这样一行的jinja2模板文件:

private_key: {{ myvar }}

Ansible使用yaml定义变量。因此,我将像这样填写 myvar值。在这里,我使用 |特殊字符来定义多行字符串:
myvar: |

- "-----BEGIN PRIVATE KEY-----"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "zzzzzzzzzzzzzzzzzz="
- "-----END PRIVATE KEY-----"

但是输出会缩进缩进:
  private_key:
- "-----BEGIN PRIVATE KEY-----"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "zzzzzzzzzzzzzzzzzz="
- "-----END PRIVATE KEY-----"

由于输出文件本身是Yaml,因此我需要保留缩进。看来无论如何我都会缩进。

I need the end result to look EXACTLY like this:


  private_key:
- "-----BEGIN PRIVATE KEY-----"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "zzzzzzzzzzzzzzzzzz="
- "-----END PRIVATE KEY-----"

最佳答案

发布问题后,我立即在Google搜索中找到了答案。

本质上,yaml字符串将去除缩进,因此在这种情况下,我们必须使用Jinja在要去除它们的位置插入空格。幸运的是,这很容易做到:

在模板文件中,我将其替换为:

private_key: {{ myvar }}

有了这个:
private_key: {{ myvar | indent( width=4, indentfirst=True) }}
width字段可以调整为需要多少个缩进空间。

实际的变量声明与我在问题中发布的完全一样。但是,现在在模板中添加了缩进后,我现在有了带有缩进的所需输出:
  private_key:
- "-----BEGIN PRIVATE KEY-----"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "zzzzzzzzzzzzzzzzzz="
- "-----END PRIVATE KEY-----"

关于ansible - 保留缩进和换行符时的YAML多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55411080/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com