Handling unreachable hosts

I have a playbook to lock a user this works as expected but fails when any of the server in the inventory is unreachable
lock_user.yml

Hi,

Error is not about hosts being unreachable per say, but about a undefined variable (user_exists.rc here) that is still being evaluated for each host, whether it is reachable or not.
I’m not sure on how to change this behavior, but you should be able to circumvent the issue by checking whether var is defined before evaluating it :

when: “user_exists.rc is defined and user_exists.rc == 0 and inventory_hostname in groups[‘linux’] and user not in myusers”

Or setting a default value, here with ‘default’ jinja filter, though you can also initialize somewhere else :

when: “user_exists.rc|d() == 0 and inventory_hostname in groups[‘linux’] and user not in myusers”

On a side note, you should probably use more specific modules than shell / command when you can help it, though I don’t know much of your context. Here you could use ‘ansible.builtin.user’ module :).