首页 > 解决方案 > ansible failed_when 字符串包含“fail”或“error”或“fault”不区分大小写

问题描述

目前我正在使用failed_when: "'failed' in result|lower or 'error' in result|lower or 'fault' in result|lower"捕获 ansible 任务的失败情况。编写此条件检查failed/error/fault返回的win_shell命令返回的状态字符串中是否有任何条件的最佳方法是什么?

标签: regexansiblejinja2powershell-4.0

解决方案


编写此条件检查failed/error/fault返回的 win_shell 命令中是否有任何返回状态字符串的最佳方法是什么?

第一件事:编写正确的 yaml。您最初的问题是简单的语法:

# This a yaml key containing a simple value
a_key: a value

# This is the same value but the string is optionally quoted
other_key: "a value"

# But if you use quotes the string stops at the closing quote
# so the below will fire a parsing error
error_key: "a quoted string" and some garbage chars

# In this case you need disambiguation using other quotes,
# escaping, scalar blocks....
corrected_key1: '"a quoted string" and some garbage chars'
corrected_key2: "\"a quoted string\" and some garbage chars"
corrected_key3: >
  "a quoted string" and some garbage chars
# non exhaustive list

作为第一个修复,我们可以简单地重写您的条件如下:

failed_when: '"failed" in result|lower or "error" in result|lower or "fault" in result|lower'

但是,避免重复搜索词和过滤器以针对您要测试的每个案例将其转换为小写的更好方法是使用regex测试:

failed_when: result is regex('^.*(failed|error|fault).*$', ignorecase=true)

根据错误消息的确切模式,甚至可能有“更好”的方法来编写此条件。


推荐阅读