The behavior of ~ in ansible "when" statements is puzzling. For example, if LIB is a fact, set by set_fact, with a value of "lib64" I would expect the following statement to be true if /usr/lib64/cernlib/2006 exists, and false otherwise:

  when: '"/usr/" ~ LIB ~ "/cernlib/2006" is exists'

What I find, though, is that the conditional is always true.

The conditional behaves as expected if I omit reference to LIB and just write:

  when: '"/usr/lib64/cernlib/2006" is exists'

I can easily imagine a typo that would cause "when" to give me a "false" result, but I'm puzzled by the fact that this always gives me "true".

Am I just doing something wrong?

1 Answers

0
Vladimir Botka On

Test syntax says:

The syntax for using a jinja test is as follows:

variable is test_name

- set_fact:
    my_path: "/scratch/{{ LIB }}/cernlib/2006"
- debug:
    msg: "{{ mypath }} exists"
  when: my_path is exists

1) Using string instead of a variable results in error.

- debug:
    msg: "/scratch/test-83.yml exists"
  when: /scratch/test-83.yml is exists

shows:

fatal: [localhost]: FAILED! => {"msg": "The conditional check '/scratch/test-83.yml is exists' failed. The error was: template error while templating string: unexpected '/'.

2) Quotation of the string does not help

- debug:
    msg: "/scratch/test-83.yml exists"
  when: "/scratch/test-83.yml" is exists

shows:

ERROR! Syntax Error while loading YAML.
  did not find expected key
...
The offending line appears to be:

    msg: "/scratch/test-83.yml exists"
  when: "/scratch/test-83.yml" is exists
                               ^ here
This one looks easy to fix.  It seems that there is a value started
with a quote, and the YAML parser is expecting to see the line ended
with the same kind of quote.  For instance:
  when: "ok" in result.stdout
Could be written as:
  when: '"ok" in result.stdout'
Or equivalently:
   when: "'ok' in result.stdout"

3) Only this specific combination of single and double quotation works

- debug:
    msg: "/scratch/test-83.yml exists"
  when: "'/scratch/test-83.yml' is exists"

Tested with

> ansible --version
ansible 2.7.9
python version = 2.7.15rc1 (default, Nov 12 2018, 14:31:15) [GCC 7.3.0]