当 ansible.systemd 重启失败时如何获取错误输出?

How to get error output when ansible.systemd fails with restart?

使用以下 ansible:

- name: Reload changes in configuration and restart docker service
  systemd:
    name: docker
    enabled: true
    daemon_reload: true
    state: restarted
    register: command_output
- name: Print to console
  debug:
    msg: "{{command_output.stdout}}"

我看到以下错误:

fatal: [xxxxxx]: FAILED! => {"changed": false, "msg": "Unable to start service docker: Job for docker.service failed because the control process exited with error code.\nSee "systemctl status docker.service" and "journalctl -xe" for details.\n"}

这在命令行中当然是一个非常有用的错误信息,但在ansible中,就不是那么多了。我尝试捕获错误输出并在调试中显示它,但收效甚微。所以问题是:

如何获得有关 ansible.systemd 在这种情况下失败的原因的更多详细信息?

我应该尝试手动调用 journalctl -xesystemctl status docker.service,还是有其他更友好的方式?

无论什么ansible模块捕获已经存在stderr或stdout return值..如果你想获得错误的更多细节,你可以尝试Block and Rescue ... Block and Resuce Documentation

block:
  - name: Reload changes in configuration and restart docker service
    systemd:
      name: docker
      enabled: true
      daemon_reload: true
      state: restarted
      register: command_output
  - name: Print to console
    debug:
      msg: "{{command_output.stdout}}"
rescue:
  - name: get errors
    shell: journalctl -xe  # or systemctl status docker.service
    register: err_msg
  - name: Print error message to console
    debug:
      msg: "{{ err_msg.stdout }}"