如何在 ansible playbook 任务中在 shell 命令执行失败时仅打印 stderr_lines

Moo*_*oon 2 ansible

在我的 ansible playbook 中,我有一个执行shell命令的任务。该命令的参数之一是密码。当 shell 命令失败时,ansible 会打印包含具有密码的命令的整个 json 对象。如果我使用,no_log: True那么我会得到审查的输出并且无法获得stderr_lines. 当 shell 命令执行失败时,有没有办法自定义输出?

Zei*_*tor 5

您可以利用 ansible及其错误处理功能。

这是一个示例剧本

---
- 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
Run Code Online (Sandbox Code Playgroud)

这给出了以下结果:

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
Run Code Online (Sandbox Code Playgroud)