Ansible conditional based on stdout of result?

前端 未结 2 1890
陌清茗
陌清茗 2020-12-29 04:10

How do I use the when statement based on the standard output of register: result? If standard output exists I want somecommand to run if no standard output exists I want so

相关标签:
2条回答
  • 2020-12-29 04:55

    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 == ""
    
    0 讨论(0)
  • 2020-12-29 05:07

    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.`

    0 讨论(0)
提交回复
热议问题