Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ansible 变量为YAML树。如何保存缩进?_Ansible_Ansible Template - Fatal编程技术网

Ansible 变量为YAML树。如何保存缩进?

Ansible 变量为YAML树。如何保存缩进?,ansible,ansible-template,Ansible,Ansible Template,我有带模板的yml文件。模板是从yml树的中间开始的键的一部分 模板工作正常,但缩进仅为最后一个关键点保存。如何保存所有键的缩进 base.yml: app: config1: base: {{ service1.company.backend | to_nice_yaml(indent=2) }} config2: node: {{ service1.company.addr | to_nice_yaml(indent=2) }} service1: compan

我有带模板的
yml
文件。模板是从yml树的中间开始的键的一部分

模板工作正常,但缩进仅为最后一个关键点保存。如何保存所有键的缩进

base.yml

app:
  config1:
    base: {{ service1.company.backend | to_nice_yaml(indent=2) }}
  config2:
    node: {{ service1.company.addr | to_nice_yaml(indent=2) }}
service1:
  company:
    backend:
      node1: "xxx"
      node2: "yyy"
      node3: "zzz"
    addr:
      street: ""
config.yml

app:
  config1:
    base: {{ service1.company.backend | to_nice_yaml(indent=2) }}
  config2:
    node: {{ service1.company.addr | to_nice_yaml(indent=2) }}
service1:
  company:
    backend:
      node1: "xxx"
      node2: "yyy"
      node3: "zzz"
    addr:
      street: ""
我需要得到:

app:
  config1:
    base:
      node1: "xxx"
      node2: "yyy"
      node3: "zzz"
  config2:
    node:
      street: ""
但真正的结果是:

app:
  config1:
    base:
      node3: "zzz"
node1: "xxx"
node2: "yyy"
  config2:
    node:
      street: ""
node1
node2
不保存缩进,Jinja2解析器获取最后一个节点。在下一步中,其他角色使用了不正确的文件,无法正确处理该文件。

在Jinja2中使用适当的缩进设置(同时
to_nice_yaml
会产生一个尾随的换行符,因此
修剪
是必要的):


或者创建一个helper变量,并依赖Ansible
to_nice\u yaml
过滤器对整个值进行过滤。例如:

...

vars:
  helper_var:
    app:
      config1:
        base: "{{ service1.company.backend }}"
      config2:
        node: "{{ service1.company.addr }}"

...

tasks:
  - copy:
      content: "{{ helper_var | to_nice_yaml(indent=2) }}"
      dest: my_file

谢谢大家!<代码>缩进效果很好,但我认为应该更恰当地使用helper变量。我喜欢这两种方法。不过,我最终还是使用了第一个,这样我就可以限制用户在我创建的配置文件中可以更改的内容。