How to display stderr output when stdout has no result

Viewed 397

I'm new in using ansible for automation, I am trying to check if user's account is existing on the manage hosts or not. The situation is, when the user account is existing the results will register to the stdout but when not it will display on the stderr. I am using a debug module to display the result. I want to ask how to filter the results like when user account is existing, it will only display the stdout debug function, and when its not, it will only display the stderr function. Tried checking every page i know but cant find a resolution. Thanks in advance,

Code:

[root@ansible playbook]# vi UAA.yml
---
- hosts: all
  gather_facts: false
  remote_user: root
  ignore_errors: true
  vars_prompt:

    - name: userID #variable
      prompt: "Please enter userID"
      private: no

  tasks:

  - name: Checking if user exist
    command: id '{{ userID }}'
    register: result

  - debug:
      msg: " {{ result.stdout_lines }} "

  - debug:
      msg: " {{ result.stderr_lines }} "
1 Answers

Use when statement to validate if stdout is empty or not. Try as below.

---
- hosts: all
  gather_facts: false
  remote_user: root
  ignore_errors: true
  vars_prompt:

    - name: userID #variable
      prompt: "Please enter userID"
      private: no

  tasks:

  - name: Checking if user exist
    command: id '{{ userID }}'
    ignore_errors: yes
    register: result

  - debug:
      msg: " {{ result.stdout_lines }} "
    when: user.stdout != ""

  - debug:
      msg: " {{ result.stderr_lines }} "
    when: user.stdout == ""
Related