Multiple when statements in loop?

For reference, this is a continuation of: https://groups.google.com/forum/#!topic/ansible-project/XhU9iPXjjcw

Can you use multiple when statements in a loop? or is there a different way to approach this without having to write out a task for each item? Take the following for example. I know the syntax is wrong, but it gives you a better idea of what I mean.

`

  • name: Insert audit rules
    lineinfile:
    path: “/etc/audit/audit.rules”
    line: “{{ item.line }}”
    regexp: “{{ item.regexp }}”
    state: present
    insertafter: EOF
    notify: Restart auditd
    with_items:
  • { line: ‘-w /home/GOMER/Scripts -p w -k copperfield’, regexp: ‘.*GOMER.Scripts.’ }
    when: directories.results.0.stat.exists
  • { line: ‘-w /home/PYLE/Scripts -p w -k copperfield’, regexp: ‘.PYLEScripts.*’ }
    when: directories.results.1.stat.exists

`

I think instead of doing that, you should use with_together and a single when statement that meets your needs


line: “{{ item.1.line }}”
regexp: “{{ item1.regexp }}”

when: item.0.stat.exists
with_together:

  • “{{ directories.results }}”

Thanks. with_together is new to me. I am having a hard time wrapping my mind around the example you gave. Can you explain it to me?

I created the following playbook, and this works as expected, but I don’t understand it in context to what you recommended:

`

It allows you to loop 2 parallel sets of data.

See http://docs.ansible.com/ansible/latest/playbooks_loops.html#looping-over-parallel-sets-of-data

Right, I saw that… I don’t understand why in the example you gave you are referencing item.1.* and then using a when statement of item.0