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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With