Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 519
Tessa Lau Avatar asked Oct 15 '14 23:10

Tessa Lau


People also ask

What is the method you need to write for accessing a variable name in Ansible?

Playbook Variables To define a variable in a playbook, simply use the keyword vars before writing your variables with indentation. To access the value of the variable, place it between the double curly braces enclosed with quotation marks.

How do you pass variable value while running Ansible playbook?

To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.


2 Answers

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

like image 106
Tony Cesaro Avatar answered Nov 28 '22 08:11

Tony Cesaro


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

like image 27
Ramon de la Fuente Avatar answered Nov 28 '22 08:11

Ramon de la Fuente