6

Ansible tasks can have when clauses like this:

- name: Conditional output
  debug:
    msg: This is a conditional output
  when: some_var

In order to protect about some_var being undefined, one can use

- name: Conditional output
  debug:
    msg: This is a conditional output
  when: some_var is defined and some_var

There also seems to be a variant like this:

- name: Conditional output
  debug:
    msg: This is a conditional output
  when: some_var | d() | bool

Are these variants the same? What are their advantages/disadvantages?

Zeitounator
  • 38,476
  • 7
  • 53
  • 66
pt1
  • 179
  • 1
  • 5

2 Answers2

5

The strict equivalence of your two safe examples would be:

when: some_var is defined and some_var | bool

vs

when: some_var | d() | bool

The bool filter makes sure the var content is interpreted as a boolean and that, as an example taken from my experience, a string answer to a vars_prompt is working as expected ("true" => true).

d is an alias to default and is documented in the official jinja2 documentation for the filter

The 2 above are strictly equivalent and will produce the same result on all occasion. But I do prefer the most compact one that I would further enhance for documentation reasons like this:

when: some_var | d(false) | bool
Zeitounator
  • 38,476
  • 7
  • 53
  • 66
4

The second form is less readable than the first, but is more flexible. It reads as follows:

The first form reads as follows:

  • If some_var is defined
  • Evaluation of some_var (as a Python boolean)

If some_var is truthy or has the potential to be truthy, then the first form could fail if it is not precisely True or False.

Makoto
  • 104,088
  • 27
  • 192
  • 230