Home > Back-end >  How to exclude an host in Ansible Jinja2 template for-loop?
How to exclude an host in Ansible Jinja2 template for-loop?

Time:09-15

I have a template named foo.yml.j2 used in an Ansible task to generate a foo.yml file:

      {% for host in ansible_play_hosts_all %}
      {{ host }},
      {% endfor %}

Everything works fine except I need something like the following statement: For every host in ansible_play_hosts_all except for host==bar do this or that.

Is this achievable or the only way to do this is to categorize my hosts in different groups and use ansible_play_hosts_group?

CodePudding user response:

You can use the reject filter to take your host out of the list so that it is not part of your loop:

{% for host in ansible_play_hosts_all | reject('==', 'bar') %}
{{ host }},
{% endfor %}

CodePudding user response:

There are more options. The trivial one is using the condition in Jinja

{% for host in ansible_play_hosts_all %}
{% if host != 'bar' %}
{{ host }},
{% endif %}
{% endfor %}

Fit the format to your needs.


Example of a complete playbook for testing

- hosts: host_1,host_2,host_3
  gather_facts: false
  tasks:
    - debug:
        msg: |
          {% for host in ansible_play_hosts_all %}
          {% if host != 'host_2' %}
          {{ host }},
          {% endif %}
          {% endfor %}
      run_once: true

gives (abridged)

  msg: |-
    host_1,
    host_3,

The next option is to remove blacklisted hosts from the loop, e.g.

blacklist: [host_2]

The template below gives the same result

          {% for host in ansible_play_hosts_all|difference(blacklist) %}
          {{ host }},
          {% endfor %}
  • Related