Ansible: check if my user exists on the remote host, otherwise use the root user to connect to ssh

I am currently writing an Ansible script that should update openssl on every host running Debian or CentOS. On hosts, our SSH keys are deposited for my own or root user. I want to check if my user exists on the host if I do not want to authenticate with the root user. Is there any way to do this? I tried it with the bash command, but I want to check if my user exists before I run the tasks. There may be other solutions to my problem, but I do not know them. Running this piece causes a syntax error. My script looks like this:

---
- hosts: "{{ host_group }}" 
  remote_user: "{{ username }}"
  tasks:

# Check whether there a existinig user or whether you have to use root
    - name: Check whether there your user on the machine
      action: shell /usr/bin/getent passwd $username | /usr/bin/wc -l | tr -d ''
      register: user_exist
      remote_user: root
      when: user_exist.stdout == 0
      tags:
         - users

# Install openssl on Ubuntu or Debian
    - name: Install openssl on Ubuntu or Debian
      become: True
      become_user: root
      apt: name=openssl state=latest
      when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu'

# Install openssl on CentOS or RHEL
    - name: Install openssl on CentOS or RHEL
      become: True
      become_user: root
      yum: name=openssl state=latest
      when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux'
+5
1

local_action.
, , host unreachable .
- :

- hosts: myservers
  gather_facts: no  # or it will fail on the setup step
  tasks:
    - name: Test user
      local_action: "command ssh -q -o BatchMode=yes -o ConnectTimeout=3 {{ inventory_hostname }} 'echo ok'"
      register: test_user
      ignore_errors: true
      changed_when: false

    - name: Do useful stuff
      remote_user: "{{ test_user | success | ternary(omit, 'root') }}"
      command: echo ok
+4

Source: https://habr.com/ru/post/1655804/


All Articles