我在Ansible中有一个Jinja2模板,我需要有条件地包含一些文件.
基本上,我有一个for循环,其中包含可能存在或可能不存在的"子部分".下面的示例演示了如果所有工具实际上都有一个'pbr.j2'文件可以使用的基本代码,但它崩溃了,因为Ansible找不到一些文件:
{% for tool in tools %}
{% set template = 'tools/' + tool.name + '/pbr.j2' %}
{% include template %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我也曾尝试exists
和is_file
过滤器,但我总是得到"错误的",即使该文件存在.这是我尝试过的示例代码:
{% for tool in tools %}
{% set template = 'tools/' + tool.name + '/pbr.j2' %}
{% if template|exists %}
{% include template %}
{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
最后一个示例的结果是没有包含文件.如果我更换exists
有is_file
,我得到了相同的行为.
我需要改变什么来完成我想要的东西?
Dri*_*zzt 10
我找到了解决问题的方法:ignore missing
在include指令中使用.
在这种情况下,我会使用:
{% for tool in tools %}
{% set template = 'tools/' + tool.name + '/pbr.j2' %}
{% include template ignore missing %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
Ansible将忽略丢失的文件,只包含该循环中的现有文件.