Ansible 2.2 strategy for using when conditional statements to skip tasks

953 views
Skip to first unread message

Sean Cavanaugh

unread,
Nov 11, 2016, 11:14:24 AM11/11/16
to Ansible Project
In a lot our templates we have loads of variables that we may or may not use within tasks.  The desired behavior is 'if' the variable is not defined within vars or group_vars that we just skip the task.  This has been wonderful b/c we can use the same template across multiple data centers and keep improving it over time.
One of the problems we are hitting now is that when you list through with_items it will display an error prior to the when conditional being applied (pretty sure this exact error: https://github.com/ansible/ansible/issues/14383)

Within this ticket: 

jimi-c We're keeping it as a warning for now. In the future, this will be a play-ending error.

 The only work-around (which I have not tried) was this-> with_items: "{{undefined_var| default(omit) }}"

What is the preferred method?  Is there a way to do this with our work-flow that makes more sense?  Customized playbooks per project is not going to scale well so we really like the behavior prior to 2.2

Brian Coca

unread,
Nov 11, 2016, 11:23:44 AM11/11/16
to ansible...@googlegroups.com
The documentation shows this as the prefered method: `with_items: "{{undefined_var| default([]) }}"`. 
An empty list for the loop will skip the task, no need for `when`.


A strategy that does as you describe will have several issues, many `when`​ conditions will issue undefined errors as they expect the loop variable (normally `item`) or some other variable that derives it's value directly or indirectly from it. Since it can also be renamed via `loop_control` searching for `item` is not feasible. 

This pattern was always an error, it 'worked' in 1.9 because a bug in ansible 'ignored' the exception, 2.0 stopped doing that and made it a fatal error. Since many users had this issue we changed it to a deprecation warning and scheduled it for removal in 2.2. Since this is a 'definition' error we are remiss to just 'skip' those as we cannot be sure that the `when` clause is meant to catch them or not. The conditinoals are also dynamic and not resolved until inside the loop, which is also the reason we cannot 'special case' defined/undefined conditionals, since they can be written many different ways.


----------
Brian Coca
Reply all
Reply to author
Forward
0 new messages