基于结果标准输出的 Ansible 条件?

新手上路,请多包涵

如何根据 register: result 的标准输出使用 when 语句?如果存在标准输出,我希望运行某个命令,如果不存在标准输出,我希望运行另一个命令。

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

原文由 ibash 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 504
2 个回答

尝试检查它是否等于空白字符串?

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

原文由 R. S. 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

 when: result.stdout | length > 0

那是评估真理的pythonic方式,null,空字符串,空列表都评估为false。

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

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

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

原文由 sorin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题