ansible_user Is Undefined on Localhost

I rely on Ansible for configuring my workstation, so I can easily synchronize it across multiple computer. However, I recently ran into an intriguing issue when my playbook failed with the following error after adding a third-party role:

'ansible_user' is undefined

This puzzled me, because by default all ansible_* variables should be automatically populated, unless gather_facts has been explicitly disabled. It turns out that this behavior does not apply for ansible_user, if you run the playbook on localhost with a local connection instead of SSH.

To resolve this problem, you have two options. Firstly, you can specify user using the -u parameter with ansible-playbook. Alternatively, you can specify it in the vars section of your playbook with the following line:

ansible_user: "{{ ansible_env.USER }}"

I hope this explanation saves you some time you would have spent searching for a solution.