element of item list in if clause in ansible jinja2 template

Viewed 80

I have a list with several vars which I would like to loop over a template.

myList:
 - { var1: true, var2: this is another var, ... }

Within this template I want to check some conditions like

{% if item.var1|bool %}
  
--> fill something

{% endif %}

my task is using the building template function and uses with_items to iterate over the list.

The strange thing is, that jinja2 complains about unknown tag 'item' in the template.

When I remove the item and only do this:

{% if var1|bool %}
  
--> fill something

{% endif %}

then jinjy2 complains about unknown tag var1.

Is there a special way to use elements of item lists in conditionals?

2 Answers

The playbook

shell> cat pb.yml
- hosts: localhost
  vars:
    myList:
      - {var1: true, var2: this is another var}
      - {var1: false, var2: this is also another var}
  tasks:
    - template:
        src: myTemplate.txt.j2
        dest: "{{ ansible_loop.index }}.txt"
      loop: "{{ myList }}"
      loop_control:
        extended: true

and the template below

shell> cat myTemplate.txt.j2
# myTemplate.txt starts here
{% if item.var1|bool %}

  <something>

{% endif %}
# myTemplate.txt ends here

work as expected and create the files 1.txt and 2.txt

shell> cat 1.txt 
# myTemplate.txt starts here

  <something>

# myTemplate.txt ends here
shell> cat 2.txt 
# myTemplate.txt starts here
# myTemplate.txt ends here

The problem was sitting Infront of the computer...

missing if in one of the conditionals was the problem.

Related