Ansible条件基于stdout的结果?

时间:2014-10-01 13:17:34

标签: linux ansible

如何根据register:result的标准输出使用when语句?如果存在标准输出,我想在没有标准输出的情况下运行somecommand我想要运行其他命令。

- hosts: myhosts
  tasks:
  - name: echo hello
    command: echo hello
    register: result
  - command: somecommand {{ result.stdout }}
    when: result|success
  - command: someothercommand
    when: result|failed

2 个答案:

答案 0 :(得分:49)

如果等于空字符串,请尝试检查以查看它吗?

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

答案 1 :(得分:2)

截至2018年,测试输出是否为空的推荐方法是:

when: result.stdout | length > 0

这是评估真值,空值,空字符串,空列表都评估为false的Python方法。

其他较旧的替代品不推荐,甚至不起作用:

  • result.stdout != ""无法通过ansible-lint检查!
  • result.stdout | bool将不起作用,因为大多数字符串将评估为False,只有在stdout恰好是trueyes,...之一时,它才会返回true。一种字符串。
  • result.stdout曾经可以使用,但现在可以触发:
  

[DEPRECATION WARNING]:作为裸变量评估,此   行为将消失,您可能需要在| bool中添加| bool。   将来表达。另请参阅CONDITIONAL_BARE_VARS配置   切换。此功能将在2.12版中删除。弃用   可以通过在以下位置设置deprecation_warnings = False来禁用警告   ansible.cfg。`

相关问题