How do I get a variable with the name of the user running ansible?

I put something like the following in all templates:

# Placed here by {{ lookup('env','USER') }} using Ansible, {{ ansible_date_time.date }}.

When templated over it shows up as:

# Placed here by staylorx using Ansible, 2017-01-11.

If I use {{ ansible_user_id }} and I've become root then that variable indicates "root", not what I want most of the time.


If you gather_facts, which is enabled by default for playbooks, there is a built-in variable that is set called ansible_user_id that provides the user name that the tasks are being run as. You can then use this variable in other tasks or templates with {{ ansible_user_id }}. This would save you the step of running a task to register that variable.

See: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#variables-discovered-from-systems-facts


If you mean the username on the host system, there are two options:

You can run a local action (which runs on the host machine rather than the target machine):

- name: get the username running the deploy
  become: false
  local_action: command whoami
  register: username_on_the_host

- debug: var=username_on_the_host

In this example, the output of the whoami command is registered in a variable called "username_on_the_host", and the username will be contained in username_on_the_host.stdout.

(the debug task is not required here, it just demonstrates the content of the variable)


The second options is to use a "lookup plugin":

{{ lookup('env', 'USER') }}

Read about lookup plugins here: docs.ansible.com/ansible/playbooks_lookups.html