【问题标题】:Ansible condition always evaluates to falseAnsible 条件始终评估为 false
【发布时间】:2015-03-05 16:32:53
【问题描述】:

我正在尝试检查 shell 命令的输出以查找指示错误的特定字符串,并且应该终止 playbook。

我正在尝试像这样调试它:

- debug: var=foo_result

- debug: msg={{ 'Some error text' in foo_result }}

在此示例中,install_result 已注册以包含命令的输出,并且确实如此:

TASK: [do_stuff | debug var=foo_result] **************************** 
ok: [some-node] => {
    "foo_result": {
        "changed": true, 
        "msg": "All items completed", 
        "results": [
            {
                "changed": true, 
[Snip..]
                "stderr": "", 
                "stdout": "...Some error text..."
            }
        ]
    }
}

第二个调试语句,它检查foo_result 中的“一些错误文本”总是评估为“假”。

我仍然觉得 Ansible 语法有点混乱,我不确定我在这里做错了什么。

Ansible 版本:1.6.10

【问题讨论】:

    标签: ansible ansible-playbook


    【解决方案1】:

    你几乎拥有它。您想在 foo_result.results.stdout 中测试输出,而不仅仅是在 foo_result 中。从这个例子:

      - debug: var=foo_result
    
      - debug: msg={{ 'Some error text' in foo_result }}
    
      - debug: msg={{ 'Some error text' in foo_result.results.stdout }}
    

    我们得到以下输出(我运行的是 1.7.2 版):

    TASK: [debug var=foo_result] **************************************************
    ok: [localhost] => {
        "foo_result": {
            "changed": "true",
            "msg": "all items completed",
            "results": {
                "changed": "true",
                "stderr": "",
                "stdout": ".... Some error text ..."
            }
        }
    }
    
    TASK: [debug msg=False] *******************************************************
    ok: [localhost] => {
        "msg": "False"
    }
    
    TASK: [debug msg=True] ********************************************************
    ok: [localhost] => {
        "msg": "True"
    }
    

    【讨论】:

    • 嗯,不,我收到此错误:无法在模板字符串中查找名称或访问属性。确保您的变量名称不包含无效字符,例如“-”。 如果我使用 {{ 'some error' in foo_result.results.stdout }}
    【解决方案2】:

    Ansible 很奇怪。也许我只是没有“得到”它......

    请注意,在原始输出中,foo_install.results 包含一个具有单个元素的数组。如果你想调试或测试stdout 的文本,你可以这样做:

    - debug: msg={{ 'My Error' in foo_result.results[0].stdout }}
      when: foo_result.changed
    

    请注意,我必须添加数组索引符号才能正确打印“true”。

    但如果我这样做:

    - name: Do Foo Stuff
      shell: /some/path/to/some/command
      register: foo_result
      failed_when: "'My Error' in foo_result.stdout"
    

    我不需要参考results[0]。我不知道这种差异是怎么回事。我不知道为什么访问foo_result 似乎工作不同,如果我从注册它的同一个任务访问它而不是不同的任务。

    也许这已在较新的版本中得到修复,但这是我需要做的以使其在 1.6.10 中正常工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 2021-12-19
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多