Ansible: Include a file if it exists and do nothing if it doesn't

Viewed 8205

I have a Jinja2 template in Ansible and I need to include some files conditionally.

Basically, I have a for loop that includes "subparts" that might or might not be present. The following sample demonstrates the basic code that would work if all tools actually had a 'pbr.j2' file, but it crashes because Ansible cannot find some of the files:

{% for tool in tools %}
   {% set template = 'tools/' + tool.name + '/pbr.j2' %}
   {% include template %}
{% endfor %}

I have also tried the exists and is_file filters, but I always get "false" even when the file exists. Here is a sample code of what I have tried:

{% for tool in tools %}
   {% set template = 'tools/' + tool.name + '/pbr.j2' %}
   {% if template|exists %}
      {% include template %}
   {% endif %}
{% endfor %}

The result of this last sample is that no file gets included. If I replace exists with is_file, I get the same behavior.

What do I need to change to accomplish what I want?

2 Answers

I have found a solution to my problem: using ignore missing in the include directive.

In this case, I would use:

{% for tool in tools %}
   {% set template = 'tools/' + tool.name + '/pbr.j2' %}
   {% include template ignore missing %}
{% endfor %}

Ansible will ignore missing files and only the existing files from that loop will get included.

You are trying to use Ansible filters (exists, is_file) in a Jinja2 template. This works for templates processed by Ansible templating engine, but not for templates processed by the template module.

Jinja2 does not have capability to check the existence of a file, so you need to move your logic to Ansible.

For example: create a find task to search for directories in tools/, and provide an intersection of find-results list with tools list to Jinja2.

Related