Ansible 2.0 with_items failing on variable that doesn't exist even though it is in where clause.

This test playbook used to work in ansible 1.9.x and is no longer working. I have no variables (foo or php_packages)defined for this example.

`

This has not changed, when: always executes after with_ : , this is so
you can use 'item' in your when clause to conditionally execute each
loop iteration. This means you CANNOT use it to prevent an undefined
error in with_, you need to use default() to provide an empty list,
which will skip the task:

- name: Install php and packages from php_packages
  yum: name={{ item }} enablerepo=epel state=present
  with_items:
      - '{{ php_packages|default() }}'

When statements are evaluated for every loop of with_items. So your when statement will not prevent ansible from attempting to loop over the value.

You will need to ensure that the value is at least an empty list. Something like:

  • name: Install php and packages from php_packages
    yum: name={{ item }} enablerepo=epel state=present
    with_items: php_packages|default()

The side effect, is that you also don’t need to check that it is defined, as the default filter will set it to an empty list which has no iterations, if the var was not defined to begin with.

Thanks Brian (and Matt) the |default() did fix it. I did test it on 1.9.4 as presented and it did work. Here is my output

`
[vagrant@ansibleserver provisioning]$ ansible --version
ansible 1.9.4
configured module search path = /usr/share/ansible

[vagrant@ansibleserver provisioning]$ ansible-playbook -i host test.yml

PLAY [configure and deploy the webservers and application code] ***************

GATHERING FACTS ***************************************************************
ok: [localhost]

TASK: [test | debug msg "Foo is " {{ foo }}] **********************************
skipping: [localhost]

TASK: [test | debug msg "Foo is " {{ foo }}] **********************************
skipping: [localhost]

TASK: [test | Install generic php] ********************************************
changed: [localhost] => (item=php)

TASK: [test | Install php and packages from php_packages] *********************
skipping: [localhost]

PLAY RECAP ********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0
`

You can see the step does get skipped when running on 1.9.4