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

With the following 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}}"

I see the following error:

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"}

This is of course a very useful error message when on the command line, but in ansible, not so much. My attempt at capturing the error output and dispalying it in debug has not been very fruitful. So the question is:

How can I get more details about the reason why ansible.systemd failed in this case?

Should I try to invoke journalctl -xe or systemctl status docker.service manually, or is there some other more ansible friendly way?



Solution 1:[1]

Whatever ansible module capture is already there stderr or stdout return values.. If you want to get more details of the error, you can try 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 }}"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KrishnaR