【问题标题】:ansible failed_when string contains "fail" or "error" or "fault" case insensitiveansible failed_when 字符串包含“fail”或“error”或“fault”不区分大小写
【发布时间】:2021-04-05 06:24:50
【问题描述】:

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

【问题讨论】:

    标签: regex ansible jinja2 powershell-4.0


    【解决方案1】:

    编写此条件检查是否有任何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)
    

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

    【讨论】:

    • 父双引号字符串中的单引号字符串也是一种消歧方式:corrected_key1: "'a quoted string' and some garbage chars"
    • 这就是为什么我指出# non exhaustive list。那一个也可以这样做 => '''a quoted string'' and some garbage',我们还没有结束...更多信息,您可以查看 learnxinyminutes.com/docs/yamlyaml-multiline.info 作为两个文档示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 2012-02-18
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多