我试图写一个剧本来创建两个文件。当定义了嵌套变量时。我有输出,但是这不是我期望的。我需要创建两个仅包含变量定义的文件
playbook.yml
- hosts: all
vars:
variable:
- name: "item1"
vars:
- { id: 1, type: "get" , resource: "Customerid" }
- { id: 17, type: "post", resource: "Cus" }
- name: "item2"
vars:
- { id: 2, type: "get", resource: "Customerid" }
tasks:
- template:
src: template.j2
dest: "{{ item.name }}"
with_items: "{{ variable }}"
{% for item in variable %}
Item Name: {{ item.name }}
{% for item_var in item.vars %}
{% if item_var['type'] == 'get' %}
Item ID: {{ item_var['id'] }}
Item Resource: {{ item_var['resource'] }}
Get function
{% else %}
Item ID: {{ item_var['id'] }}
Item Resource: {{ item_var['resource'] }}
Post function
{% endif %}
{% endfor %}
{% endfor %}
两个文件创建item1和item2的当前结果:
Item Name: item1
Item ID: 1
Item Resource: Customerid
Get function
Item ID: 17
Item Resource: Cus
Post function
Item Name: item2
Item ID: 2
Item Resource: Customerid
Get function
Item Name: item1
Item ID: 1
Item Resource: Customerid
Get function
Item ID: 17
Item Resource: Cus
Post function
Item Name: item2
Item ID: 2
Item Resource: Customerid
Get function
创建两个文件时,我想获得以下输出。不知道如何得到这个。所需的输出:
Item Name: item1
Item ID: 1
Item Resource: Customerid
Get function
Item ID: 17
Item Resource: Cus
Post function
Item Name: item2
Item ID: 2
Item Resource: Customerid
Get function
答案 0 :(得分:0)
只需从模板中删除重复循环即可。
Item Name: {{ item.name }}
{% for item_var in item.vars %}
{% if item_var['type'] == 'get' %}
Item ID: {{ item_var['id'] }}
Item Resource: {{ item_var['resource'] }}
Get function
{% else %}
Item ID: {{ item_var['id'] }}
Item Resource: {{ item_var['resource'] }}
Post function
{% endif %}
{% endfor %}
模板可能会简化
Item Name: {{ item.name }}
{% for item_var in item.vars %}
Item ID: {{ item_var.id }}
Item Resource: {{ item_var.resource }}
{{ item_var.type|capitalize }} function
{% endfor %}