Ansible条件基于stdout的结果?

iba*_*ash 25 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
Run Code Online (Sandbox Code Playgroud)

R. *_* S. 47

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

- hosts: myhosts
  tasks:
  - name: echo hello
    command: echo hello
    register: result
  - command: somecommand {{ result.stdout }}
    when: result.stdout != ""
  - command: someothercommand
    when: result.stdout == ""
Run Code Online (Sandbox Code Playgroud)


sor*_*rin 19

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

when: result.stdout | length > 0
Run Code Online (Sandbox Code Playgroud)

那是 Pythonic 评估真值、空值、空字符串、空列表的方法,所有评估结果都为假。

其他不推荐甚至不工作的旧替代方案:

  • result.stdout != "" 不会通过 ansible-lint 检查!
  • result.stdout | bool不会工作,因为大多数字符串将评估为 False,只有在 stdout 恰好是true, yes,... 类型的字符串之一时才会返回 true 的情况。
  • result.stdout 曾经工作,但现在触发:

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