Understanding the "by design" behavior of "when" conditionals with "with_items"

Hi everybody,
following this bug [1] I’ve opened yesterday and the suggestion from Brian I want to understand in depth what is considered by design inside Ansible about “when”.

Now, leaving aside the usage of “when” inside roles, let’s start with this simple example:

`

This will avoid any and all problems with my_key definition.

   with_file: "{{ (my_key is defined)|ternary(my_key|default('') +
'.pub', )}}"

Hi Brian,
thanks for your answer. I changed the yaml as you suggested:

`

  • name: Configure key on remote host
    authorized_key:
    user: root
    key: “{{ item }}”
    with_file: “{{ (my_key is defined)|ternary(my_key|default(‘’) + ‘.pub’, )}}”
    become: true
    when: do_the_test|bool
    `

But it stills fail to locate the file:

`
TASK [bug_20919_bis : Configure key on remote host] ****************************
task path: /home/rasca/Red-Hat/ansible/tests/roles/bug_20919_bis/tasks/main.yml:12
[WARNING]: Unable to find ‘rasca.pub’ in expected paths.

File lookup using None as file
fatal: [192.168.122.100]: FAILED! => {
“failed”: true,
“msg”: “could not locate file in lookup: rasca.pub”
}
to retry, use: --limit @/home/rasca/Red-Hat/ansible/tests/bug_20919_bis.retry
`

So the problem here does not seem to be related at what is inside the variable passed to “with_file”, but to the fact that independently from what’s passed and from the “when:” variable, ansible looks for the file.

Thanks,

Raoul

The with_ section gets executed BEFORE the when, so you cannot use
when to avoid the with_ from being evaluated, the when runs once per
item (inside the with_ loop) to allow the task to be conditional PER
ITEM.

This is as documented :
http://docs.ansible.com/ansible/playbooks_conditionals.html#loops-and-conditionals