我在 Ansible 中有一个 Jinja2 模板,我需要有条件地包含一些文件。
基本上,我有一个 for 循环,其中包含可能存在也可能不存在的“子部分”。以下示例演示了在所有工具实际上都有一个“pbr.j2”文件的情况下可以工作的基本代码,但由于 Ansible 找不到某些文件而崩溃:
{% for tool in tools %}
{% set template = 'tools/' + tool.name + '/pbr.j2' %}
{% include template %}
{% endfor %}
我也试过
exists
和 is_file
过滤器,但即使文件存在,我也总是得到“假”。这是我尝试过的示例代码:{% for tool in tools %}
{% set template = 'tools/' + tool.name + '/pbr.j2' %}
{% if template|exists %}
{% include template %}
{% endif %}
{% endfor %}
最后一个示例的结果是没有包含任何文件。如果我更换
exists
与 is_file
,我得到了同样的行为。我需要改变什么才能实现我想要的?
最佳答案
我找到了解决问题的方法:使用 ignore missing
在包含指令中。
在这种情况下,我会使用:
{% for tool in tools %}
{% set template = 'tools/' + tool.name + '/pbr.j2' %}
{% include template ignore missing %}
{% endfor %}
Ansible 将忽略丢失的文件,并且只会包含该循环中的现有文件。
关于Ansible:如果存在则包含文件,如果不存在则不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46593974/