问题描述
在我的 ansible playbook 中,我有一个执行 shell
命令的任务.该命令的参数之一是密码.当 shell 命令失败时,ansible 会打印包含具有密码的命令的整个 json 对象.如果我使用 no_log: True
那么我会得到审查的输出并且无法获得 stderr_lines
.当shell命令执行失败时,有没有办法自定义输出?
In my ansible playbook I have a task that executes a shell
command. One of the parameters of that command is password. When the shell command fails, ansible prints the whole json object that includes the command having password. If I use no_log: True
then I get censored output and not able to get stderr_lines
. Is there a way to customize the output when shell command execution fails?
推荐答案
您可以利用 ansible blocks 及其错误处理功能.
You can take advantage of ansible blocks and their error handling feature.
这是一个示例剧本
---
- name: Block demo for shell
hosts: localhost
gather_facts: false
tasks:
- block:
- name: my command
shell: my_command is bad
register: cmdresult
no_log: true
rescue:
- name: show error
debug:
msg: "{{ cmdresult.stderr }}"
- name: fail the playbook
fail:
msg: Error on command. See debug of stderr above
得到以下结果:
PLAY [Block demo for shell] *********************************************************************************************************************************************************************************************************************************************
TASK [my command] *******************************************************************************************************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result", "changed": true}
TASK [show error] *******************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": "/bin/sh: 1: my_command: not found"
}
TASK [fail the playbook] ************************************************************************************************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Error on command. See debug of stderr above"}
PLAY RECAP **************************************************************************************************************************************************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=1 ignored=0
这篇关于如何在 ansible playbook 任务中在 shell 命令执行失败时仅打印 stderr_lines的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!