Ansible

From Sidvind
Jump to: navigation, search

Combine with_items with undefined variable[edit]

Pre-ansible 2 it was possible to use

 - name: example task
   when: foo is defined
   with_items: foo
   ..


However since 2.0 this yields a deprecation warning:

 [DEPRECATION WARNING]: Using bare variables is deprecated. Update your playbooks so that the environment value uses the full variable syntax ('{{foo}}').
 This feature will be removed in a future release. 
 Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

Surrounding the variable with quotes yields another:

 [DEPRECATION WARNING]: Skipping task due to undefined Error, in the future this will be a fatal error.: 'foo' is undefined.
 This feature will be removed in a future release. Deprecation warnings can be disabled by
  setting deprecation_warnings=False in ansible.cfg.

This is because "when" is evaluated for each with_item iteration thus "foo" is accessed before the condition happens. The proper way to fix this is to use | default([]):

 - name: example task
   with_items: "{{ foo | default([]) }}"
   ..