问题
I'm trying to examine the output of a shell command for a particular string which indicates an error, and that the playbook should be terminated.
I'm trying to debug it something like this:
- debug: var=foo_result
- debug: msg={{ 'Some error text' in foo_result }}
In this example, install_result
was registered to contain the output of the command, and it does:
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..."
}
]
}
}
The second debug statement, which checked for "some error text" in foo_result
always evaluates to "false".
I'm still finding the Ansible syntax a little confusing, I'm not sure what I did wrong here.
Ansible version: 1.6.10
回答1:
You almost have it. You want to be testing for the output in foo_result.results.stdout, not just in foo_result. From this example:
- debug: var=foo_result
- debug: msg={{ 'Some error text' in foo_result }}
- debug: msg={{ 'Some error text' in foo_result.results.stdout }}
We get the following output (I'm running version 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"
}
回答2:
Ansible is weird. Maybe I'm just not "getting" it...
Notice in the original output, that foo_install.results
contains an array with a single element. If you want to debug or test stdout
for text, you can do it this way:
- debug: msg={{ 'My Error' in foo_result.results[0].stdout }}
when: foo_result.changed
Notice I had to add array index notation to get this to print "true" properly.
But if I do this:
- name: Do Foo Stuff
shell: /some/path/to/some/command
register: foo_result
failed_when: "'My Error' in foo_result.stdout"
I don't need to refer to results[0]
. I don't know what's up with that difference. I don't know why accessing foo_result
seems to work differently if I access it from the same task that registered it vs. a different task.
Maybe this is fixed in more recent versions, but this is what I needed to do to get this working in 1.6.10
来源:https://stackoverflow.com/questions/28882891/ansible-condition-always-evaluates-to-false