背景:
这是使用模板从模板构造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,因此我需要保留缩进。看来无论如何我都会缩进。
我需要最终结果,以使其看起来完全:
private_key:
- "-----BEGIN PRIVATE KEY-----"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "asdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfssadf"
- "zzzzzzzzzzzzzzzzzz="
- "-----END PRIVATE KEY-----"
答案 0 :(得分:0)
发布问题后,我立即在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-----"