Ansible conditional based on stdout of result?

Try checking to see it if equals a blank string or not?

- hosts: myhosts
  tasks:
  - name: echo hello
    command: echo hello
    register: result
  - command: somecommand {{ result.stdout }}
    when: result.stdout != ""
  - command: someothercommand
    when: result.stdout == ""

As of 2018, the recommended way to test if output is empty is just:

when: result.stdout | length > 0

That is the pythonic way of evaluating truth, null, empty strings, empty lists all evaluate as false.

Other older alternatives not recommended or even not working:

  • result.stdout != "" would not pass ansible-lint check!
  • result.stdout | bool will NOT work as most strings will evaluate as False, only cases where it would return true is if stdout happens to be one of the true, yes,... kind of strings.
  • result.stdout used to work but now triggers:

[DEPRECATION WARNING]: evaluating as a bare variable, this behaviour will go away and you might need to add |bool to the expression in the future. Also see CONDITIONAL_BARE_VARS configuration toggle.. This feature will be removed in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.`

Tags:

Linux

Ansible