我想在Ansible中使用“with_items”构造执行几个命令。如果命令失败,我想打印其标准输出。我举了一个简单的例子来说明问题。
- action: shell echo {{item}}
with_items:
- 1
- 2
register: task
- debug: var=item.stdout_lines
with_items: "{{task.results}}"
问题是不仅打印了stdout行。我该如何解决这个问题?
答案 0 :(得分:2)
如果命令失败,我想打印其标准输出。
如果shell以非零状态退出,则Ansible将退出该错误。
话虽如此,如果你改变
- debug: var=item.stdout_lines
with_items: "{{task.results}}"
到
- debug: var=item
with_items: "{{ task.results | map(attribute='stdout_lines') | list }}"
将打印所有输出行,而不包含结果字典中的所有其他信息。
答案 1 :(得分:0)
您也可以使用blocks。
---
- hosts: all
tasks:
- block:
- name: test
shell: date; /bin/false
register: cmd_reg
rescue:
- debug: var=cmd_reg
# fail the build ?
输出:
ap test.yml -c local -i 'localhost, '
PLAY [all] *********************************************************************
TASK [setup] *******************************************************************
ok: [localhost]
TASK [test] ********************************************************************
fatal: [localhost]: FAILED! => {"changed": true, "cmd": "date; /bin/false", "delta": "0:00:00.011686", "end": "2016-11-23 11:43:26.554559", "failed": true, "rc": 127, "start": "2016-11-23 11:43:26.542873", "stderr": "/bin/sh: /bin/false: No such file or directory", "stdout": "Wed 23 Nov 2016 11:43:26 GMT", "stdout_lines": ["Wed 23 Nov 2016 11:43:26 GMT"], "warnings": []}
TASK [debug] *******************************************************************
ok: [localhost] => {
"cmd_reg": {
"changed": true,
"cmd": "date; /bin/false",
"delta": "0:00:00.011686",
"end": "2016-11-23 11:43:26.554559",
"failed": true,
"rc": 127,
"start": "2016-11-23 11:43:26.542873",
"stderr": "/bin/sh: /bin/false: No such file or directory",
"stdout": "Wed 23 Nov 2016 11:43:26 GMT",
"stdout_lines": [
"Wed 23 Nov 2016 11:43:26 GMT"
],
"warnings": []
}
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0
需要注意的事项: