Search code examples
variablesansible

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


I'm scripting a deployment process that takes the name of the user running the ansible script (e.g. tlau) and creates a deployment directory on the remote system based on that username and the current date/time (e.g. tlau-deploy-2014-10-15-16:52).

You would think this is available in ansible facts (e.g. LOGNAME or SUDO_USER), but those are all set to either "root" or the deployment id being used to ssh into the remote system. None of those contain the local user, the one who is currently running the ansible process.

How can I script getting the name of the user running the ansible process and use it in my playbook?


Solution

  • 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