How to print failure message in Ansible builtin.getent when user not found and continue with rest of tasks

I am trying to run a playbook if a specific system user does not exist and make it fail and print a message if the user exists. Below the how I do the user check:

- name: 'Check system user'
  getent:
    database: passwd
    key: '{{USER}}'
  register: result

How do I make it fail and print message if user exists and make it continue with the rest of tasks if user does not exist?

THanks in advance.


Solution 1:

Q: "Fail and print a message if the user exists and continue with the rest of the tasks if the user does not exist."

A: For example, given the variable

USER: admin

The tasks below

    - getent:
        database: passwd
    - assert:
        that: "{{ USER in getent_passwd }}"
        fail_msg: "User {{ USER }} does not exist."
        success_msg: "User {{ USER }} exists."
    - debug:
        msg: Continue

gives

TASK [assert] **************************************************************
ok: [localhost] => changed=false 
  msg: User admin exists.

TASK [debug] ***************************************************************
ok: [localhost] => 
  msg: Continue

Test a missing user. For example

USER: joker 

The same tasks will fail and print the message

TASK [assert] **************************************************************
fatal: [localhost]: FAILED! => changed=false 
  assertion: false
  evaluated_to: false
  msg: User joker does not exist.