Bootstrap FreeKB - Ansible - whoami using lookup env user or ansible_user_id
Ansible - whoami using lookup env user or ansible_user_id

Updated:   |  Ansible articles

The lookup plugin is always executed on the control node (that's your Ansible server), which is to say that the lookup plugin does not do something on your managed nodes (the target systems).

To use the env plugin, the Python env.py script must be in your Ansible plugins lookup directory, such as /usr/lib/python3.12/site-packages/ansible/plugins/lookup/env.py.

The env or printenv command will display certain global variables, something like this.

[john.doe@server1 ~]$ env
HOSTNAME=server1
SHELL=/bin/bash
USER=john.doe

 

The lookup plugin can be used to get the value of the global variables. For example, to display the value of the USER global variable.

---
- hosts: localhost
  tasks:
  - debug:
      msg: "{{ lookup('env', 'USER') }}"
...

 

Running this play should return the following.

TASK [debug]
ok: [localhost] => {
    "msg": "john.doe"
}

 

Or, you may want to use the ansible_user_id variable to display the user being used in the SSH connection to each managed nodes. This is often more practical, since john.doe may be invoking the ansible-playbook command but the --user command line option or the remote_user parameter may be used so that some other user (e.g. jane.doe) is being used in the SSH connection to each managed node.

Be aware that if you set gather_facts: false then the ansible_user_id variable will return VARIABLE IS NOT DEFINED.

---
- hosts: localhost
  remote_user: jane.doe
  tasks:
  - debug:
      var: ansible_user_id
...

 

Running this play should return the following.

ok: [localhost] => {
    "ansible_user_id": "jane.doe"
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 7cd904 in the box below so that we can be sure you are a human.