问题描述
谁可以告诉您如何在输入名为region1a的模板时实现name1组中所有区域的输出,而在输入名为region2b的模板时如何输出name2组中的所有区域
Who can tell you how to implement the output of all regions in the name1 group when entering a template named region1a, and when entering a template named region2b, output all regions from the name2 group
我是这样实现的:有一个任务可以开始生成模板:
I implement it like this:there is a task that starts template generation:
vars:
AllCountry:
- name1
- name2
name1:
- region1a
- region1b
name2:
- region2a
- region2b
tasks:
- name:
template:
src: "regions.j2"
dest: "{{ item }}.conf"
loop:
- region1a
- region2b
---regions.j2---
regions [{%for count in name1%} "my country = {{count}}", {%end for %}]
这将提供所需的输出,但这仅是因为已明确指定要输出的名称(1或2)
this gives the desired output, but only because it is explicitly specified for which name (1 or 2) to output
regions "my country = region1a", "my country = region1b"
对于循环中指定的每个值,必须生成一个模板配置文件.当您在循环中指定值时,region1a和region1b模板应在region1a.conf的配置文件中仅生成一行
For each value specified in the loop, a template configuration file must be generated.When you specify values in loop region1a and region1b template should generate only one row in the configuration file for region1a.conf
regions "my country = region1a", "my country = region1b"
对于region1b在配置文件中只为region1b.conf生成一行
for region1b generate only one row in the configuration file for region1b.conf
regions "my country = region1a", "my country = region1b"
用户β.εηοιτ.βε提出了一种更优化的结构.如果方便的话,您可以使用它.
User β.εηοιτ.βε a more optimal structure was proposed. If convenient, you can use it.
vars:
countries:
country1:
regions:
- region1
- region2
- region3
capital: region1
country2:
regions:
- region4
- region5
capital: region5
推荐答案
谢谢大家的帮助.尽管如此,我还是自己弄清楚了.这是最终的解决方案:
Thank you all for your help. Still, I managed to figure it out myself.Here is the final solution:
{% for country in AllCountry %}
{% if item in lookup('vars', country) %}{% for count in lookup('vars', country) %} "My country = {{ count }}"{% if not loop.last %},{% endif %}{% endfor %}{% endif %}{% endfor %}
这篇关于jinja2中的Ansible模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!